From 5e80ce1f774d84878bbd97a879ec4e381e948526 Mon Sep 17 00:00:00 2001 From: Fabio Zadrozny Date: Fri, 18 Mar 2022 15:56:12 -0300 Subject: [PATCH] More code changes related to dropping Python 2.7. --- setup.py | 2 +- src/debugpy/_vendored/_pydevd_packaging.py | 2 +- src/debugpy/_vendored/force_pydevd.py | 2 - .../_pydev_execfile.py | 0 .../_pydev_bundle/_pydev_imports_tipper.py | 4 +- .../_pydev_bundle/_pydev_jy_imports_tipper.py | 13 +- .../_pydev_saved_modules.py | 0 .../_pydev_sys_patch.py | 1 - .../_pydev_bundle/_pydev_tipper_common.py | 4 +- .../pydevd/_pydev_bundle/fsnotify/__init__.py | 18 +- .../fsnotify/scandir_vendored.py | 720 ------------------ .../_pydev_bundle/pydev_console_utils.py | 2 +- .../pydevd/_pydev_bundle/pydev_import_hook.py | 5 +- .../pydevd/_pydev_bundle/pydev_imports.py | 23 +- .../pydev_ipython_console_011.py | 5 +- .../_pydev_bundle/pydev_is_thread_alive.py | 2 +- .../pydevd/_pydev_bundle/pydev_localhost.py | 2 +- .../pydevd/_pydev_bundle/pydev_log.py | 2 +- .../pydevd/_pydev_bundle/pydev_monkey.py | 11 +- .../pydevd/_pydev_bundle/pydev_monkey_qt.py | 10 +- .../pydevd/_pydev_bundle/pydev_umd.py | 10 +- .../pydevd/_pydev_runfiles/pydev_runfiles.py | 123 ++- .../pydev_runfiles_parallel.py | 81 +- .../_pydev_runfiles/pydev_runfiles_pytest2.py | 47 +- .../pydev_runfiles_unittest.py | 83 +- .../pydevconsole_code_for_ironpython.py | 79 +- .../pydevd/_pydevd_bundle/pydevd_api.py | 6 +- .../_pydevd_bundle/pydevd_breakpoints.py | 2 +- .../_pydevd_bundle/pydevd_code_to_source.py | 4 +- .../pydevd_collect_bytecode_info.py | 80 +- .../pydevd/_pydevd_bundle/pydevd_comm.py | 8 +- .../pydevd_concurrency_analyser}/__init__.py | 0 .../pydevd_concurrency_logger.py | 4 +- .../pydevd_thread_wrappers.py | 21 +- .../pydevd/_pydevd_bundle/pydevd_constants.py | 17 +- .../_pydevd_bundle/pydevd_custom_frames.py | 2 +- .../pydevd/_pydevd_bundle/pydevd_cython.c | 16 +- .../pydevd/_pydevd_bundle/pydevd_cython.pyx | 2 +- .../_pydevd_bundle/pydevd_daemon_thread.py | 4 +- .../_pydevd_bundle/pydevd_dont_trace_files.py | 3 - .../pydevd/_pydevd_bundle/pydevd_filtering.py | 16 +- .../pydevd_gevent_integration.py | 2 +- .../pydevd_json_debug_options.py | 28 +- .../pydevd_net_command_factory_xml.py | 10 +- .../pydevd_process_net_command.py | 2 +- .../pydevd/_pydevd_bundle/pydevd_referrers.py | 6 +- .../pydevd/_pydevd_bundle/pydevd_resolver.py | 14 +- .../pydevd/_pydevd_bundle/pydevd_safe_repr.py | 37 +- .../pydevd/_pydevd_bundle/pydevd_signature.py | 3 +- .../pydevd/_pydevd_bundle/pydevd_stackless.py | 2 +- .../_pydevd_bundle/pydevd_suspended_frames.py | 2 +- .../_pydevd_bundle/pydevd_thread_lifecycle.py | 3 +- .../pydevd/_pydevd_bundle/pydevd_timeout.py | 2 +- .../pydevd_trace_dispatch_regular.py | 2 +- .../pydevd/_pydevd_bundle/pydevd_utils.py | 7 +- .../pydevd/_pydevd_bundle/pydevd_vars.py | 20 +- .../pydevd/_pydevd_bundle/pydevd_xml.py | 5 - .../pydevd_frame_evaluator.c | 16 +- .../pydevd_frame_evaluator.template.pyx | 2 +- .../pydevd_frame_tracing.py | 2 +- .../_vendored/pydevd/build_tools/build.py | 2 +- .../pydevd/build_tools/generate_code.py | 3 +- .../_vendored/pydevd/pycompletionserver.py | 4 +- .../_vendored/pydevd/pydev_coverage.py | 24 +- .../pydevd/pydev_ipython/inputhookglut.py | 2 +- .../pydevd/pydev_ipython/inputhookpyglet.py | 2 +- .../pydevd/pydev_ipython/inputhookwx.py | 2 +- .../_vendored/pydevd/pydev_run_in_console.py | 2 +- src/debugpy/_vendored/pydevd/pydevconsole.py | 13 +- src/debugpy/_vendored/pydevd/pydevd.py | 12 +- .../pydevd/pydevd_attach_to_process/_check.py | 2 +- .../winappdbg/interactive.py | 423 +++++----- .../winappdbg/plugins/README | 1 - .../winappdbg/plugins/__init__.py | 35 - .../winappdbg/plugins/do_example.py | 41 - .../winappdbg/plugins/do_exchain.py | 51 -- .../winappdbg/plugins/do_exploitable.py | 50 -- .../winappdbg/plugins/do_symfix.py | 37 - .../pydevd_concurrency_analyser/__init__.py | 0 .../_vendored/pydevd/pydevd_tracing.py | 10 +- src/debugpy/_vendored/pydevd/runfiles.py | 7 +- src/debugpy/_vendored/pydevd/setup.py | 7 +- ...setup_cython.py => setup_pydevd_cython.py} | 2 +- .../pydevd/tests/test_get_referrers.py | 2 +- .../pydevd/tests/test_pydev_ipython_011.py | 37 +- .../_vendored/pydevd/tests/test_pyserver.py | 36 +- .../pydevd/tests_python/debugger_unittest.py | 10 +- .../resources/_debugger_case_redirect.py | 5 +- .../tests_python/resources/_performance_1.py | 15 +- .../tests_python/resources/_performance_2.py | 15 +- .../tests_python/resources/_performance_3.py | 11 +- .../test_additional_thread_info.py | 15 +- .../tests_python/test_convert_utilities.py | 13 +- .../pydevd/tests_python/test_debugger.py | 9 +- .../pydevd/tests_python/test_debugger_json.py | 6 +- .../pydevd/tests_python/test_safe_repr.py | 27 +- 96 files changed, 574 insertions(+), 1960 deletions(-) rename src/debugpy/_vendored/pydevd/{_pydev_imps => _pydev_bundle}/_pydev_execfile.py (100%) rename src/debugpy/_vendored/pydevd/{_pydev_imps => _pydev_bundle}/_pydev_saved_modules.py (100%) rename src/debugpy/_vendored/pydevd/{_pydev_imps => _pydev_bundle}/_pydev_sys_patch.py (99%) delete mode 100644 src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/scandir_vendored.py rename src/debugpy/_vendored/pydevd/{_pydev_imps => _pydevd_bundle/pydevd_concurrency_analyser}/__init__.py (100%) rename src/debugpy/_vendored/pydevd/{ => _pydevd_bundle}/pydevd_concurrency_analyser/pydevd_concurrency_logger.py (99%) rename src/debugpy/_vendored/pydevd/{ => _pydevd_bundle}/pydevd_concurrency_analyser/pydevd_thread_wrappers.py (84%) delete mode 100644 src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/README delete mode 100644 src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/__init__.py delete mode 100644 src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_example.py delete mode 100644 src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exchain.py delete mode 100644 src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exploitable.py delete mode 100644 src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_symfix.py delete mode 100644 src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/__init__.py rename src/debugpy/_vendored/pydevd/{setup_cython.py => setup_pydevd_cython.py} (99%) diff --git a/setup.py b/setup.py index 02f97e42..adce48b5 100644 --- a/setup.py +++ b/setup.py @@ -38,7 +38,7 @@ def cython_build(): subprocess.call( [ sys.executable, - os.path.join(PYDEVD_ROOT, "setup_cython.py"), + os.path.join(PYDEVD_ROOT, "setup_pydevd_cython.py"), "build_ext", "-i", ] diff --git a/src/debugpy/_vendored/_pydevd_packaging.py b/src/debugpy/_vendored/_pydevd_packaging.py index 8ede7ba9..dbc0c10f 100644 --- a/src/debugpy/_vendored/_pydevd_packaging.py +++ b/src/debugpy/_vendored/_pydevd_packaging.py @@ -9,7 +9,7 @@ from ._util import cwd, iter_all_files INCLUDES = [ - 'setup_cython.py', + 'setup_pydevd_cython.py', ] diff --git a/src/debugpy/_vendored/force_pydevd.py b/src/debugpy/_vendored/force_pydevd.py index 641c410b..370348ac 100644 --- a/src/debugpy/_vendored/force_pydevd.py +++ b/src/debugpy/_vendored/force_pydevd.py @@ -44,12 +44,10 @@ pydevd_constants.MAXIMUM_VARIABLE_REPRESENTATION_SIZE = 2 ** 32 # following). preimport('pydevd', [ '_pydev_bundle', - '_pydev_imps', '_pydev_runfiles', '_pydevd_bundle', '_pydevd_frame_eval', 'pydev_ipython', - 'pydevd_concurrency_analyser', 'pydevd_plugins', 'pydevd', ]) diff --git a/src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_execfile.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_execfile.py similarity index 100% rename from src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_execfile.py rename to src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_execfile.py diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_imports_tipper.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_imports_tipper.py index c66e4ff3..7f89c750 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_imports_tipper.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_imports_tipper.py @@ -13,8 +13,6 @@ def getargspec(*args, **kwargs): return arg_spec.args, arg_spec.varargs, arg_spec.varkw, arg_spec.defaults, arg_spec.kwonlyargs or [], arg_spec.kwonlydefaults or {} -xrange = range - # completion types. TYPE_IMPORT = '0' TYPE_CLASS = '1' @@ -351,7 +349,7 @@ def signature_from_docstring(doc, obj_name): # now, get rid of unwanted chars l = len(args) - 1 r = [] - for i in xrange(len(args)): + for i in range(len(args)): if i == 0 or i == l: r.append(args[i]) else: diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_jy_imports_tipper.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_jy_imports_tipper.py index 2ed86e67..a30c4d35 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_jy_imports_tipper.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_jy_imports_tipper.py @@ -11,8 +11,6 @@ from org.python.core import PyReflectedFunction # @UnresolvedImport from org.python import core # @UnresolvedImport from org.python.core import PyClass # @UnresolvedImport -xrange = range - # completion types. TYPE_IMPORT = '0' TYPE_CLASS = '1' @@ -134,9 +132,6 @@ class Info: '''@returns this class information as a string (just basic format) ''' args = self.args - if sys.version_info[0] <= 2: - # Supress the u'' - args = [arg.encode('utf-8') if isinstance(arg, unicode) else arg for arg in args] s = 'function:%s args=%s, varargs=%s, kwargs=%s, docs:%s' % \ (self.name, args, self.varargs, self.kwargs, self.doc) return s @@ -235,7 +230,7 @@ def ismethod(func): # print_ ' PyReflectedFunction' infos = [] - for i in xrange(len(func.argslist)): + for i in range(len(func.argslist)): # things to play in func.argslist[i]: # 'PyArgsCall', 'PyArgsKeywordsCall', 'REPLACE', 'StandardCall', 'args', 'compare', 'compareTo', 'data', 'declaringClass' @@ -254,7 +249,7 @@ def ismethod(func): parameterTypes = met.getParameterTypes() args = [] - for j in xrange(len(parameterTypes)): + for j in range(len(parameterTypes)): paramTypesClass = parameterTypes[j] try: try: @@ -341,12 +336,12 @@ def dir_obj(obj): except TypeError: declaredFields = obj.getDeclaredFields(obj) - for i in xrange(len(declaredMethods)): + for i in range(len(declaredMethods)): name = declaredMethods[i].getName() ret.append(name) found.put(name, 1) - for i in xrange(len(declaredFields)): + for i in range(len(declaredFields)): name = declaredFields[i].getName() ret.append(name) found.put(name, 1) diff --git a/src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_saved_modules.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_saved_modules.py similarity index 100% rename from src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_saved_modules.py rename to src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_saved_modules.py diff --git a/src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_sys_patch.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_sys_patch.py similarity index 99% rename from src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_sys_patch.py rename to src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_sys_patch.py index 2000d014..f5067509 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_sys_patch.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_sys_patch.py @@ -1,4 +1,3 @@ - import sys diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_tipper_common.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_tipper_common.py index ba2799ae..d97e95d1 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_tipper_common.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_tipper_common.py @@ -1,8 +1,6 @@ import inspect import re -from _pydevd_bundle.pydevd_constants import xrange - def do_find(f, mod): import linecache @@ -14,7 +12,7 @@ def do_find(f, mod): if inspect.isclass(mod): name = mod.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') - for i in xrange(len(lines)): + for i in range(len(lines)): if pat.match(lines[i]): return f, i, 0 diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/__init__.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/__init__.py index b001799e..fe6ed413 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/__init__.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/__init__.py @@ -41,15 +41,7 @@ import threading import sys from os.path import basename from _pydev_bundle import pydev_log -try: - from os import scandir -except: - try: - # Search an installed version (which may have speedups). - from scandir import scandir - except: - # If all fails, use our vendored version (which won't have speedups). - from .scandir_vendored import scandir +from os import scandir try: from enum import IntEnum @@ -261,12 +253,12 @@ class Watcher(object): # Sort by the path len so that the bigger paths come first (so, # if there's any nesting we want the nested paths to be visited # before the parent paths so that the max_recursion_level is correct). - paths = sorted(set(paths), key=lambda path: -len(path)) + paths = sorted(set(paths), key=lambda path:-len(path)) path_watchers = set() self._single_visit_info = _SingleVisitInfo() - initial_time = time.time() + initial_time = time.time() for path in paths: sleep_time = 0. # When collecting the first time, sleep_time should be 0! path_watcher = _PathWatcher( @@ -279,9 +271,9 @@ class Watcher(object): ) path_watchers.add(path_watcher) - + actual_time = (time.time() - initial_time) - + pydev_log.debug('Tracking the following paths for changes: %s', paths) pydev_log.debug('Time to track: %.2fs', actual_time) pydev_log.debug('Folders found: %s', len(self._single_visit_info.visited_dirs)) diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/scandir_vendored.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/scandir_vendored.py deleted file mode 100644 index e38df9c7..00000000 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/fsnotify/scandir_vendored.py +++ /dev/null @@ -1,720 +0,0 @@ -"""scandir, a better directory iterator and faster os.walk(), now in the Python 3.5 stdlib - -scandir() is a generator version of os.listdir() that returns an -iterator over files in a directory, and also exposes the extra -information most OSes provide while iterating files in a directory -(such as type and stat information). - -This module also includes a version of os.walk() that uses scandir() -to speed it up significantly. - -See README.md or https://github.com/benhoyt/scandir for rationale and -docs, or read PEP 471 (https://www.python.org/dev/peps/pep-0471/) for -more details on its inclusion into Python 3.5 - -scandir is released under the new BSD 3-clause license. - -Copyright (c) 2012, Ben Hoyt -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 Ben Hoyt 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 HOLDER 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. -""" - -from __future__ import division - -from errno import ENOENT -from os import listdir, lstat, stat, strerror -from os.path import join, islink -from stat import S_IFDIR, S_IFLNK, S_IFREG -import collections -import sys - -try: - import _scandir -except ImportError: - _scandir = None - -try: - import ctypes -except ImportError: - ctypes = None - -if _scandir is None and ctypes is None: - import warnings - warnings.warn("scandir can't find the compiled _scandir C module " - "or ctypes, using slow generic fallback") - -__version__ = '1.10.0' -__all__ = ['scandir', 'walk'] - -# Windows FILE_ATTRIBUTE constants for interpreting the -# FIND_DATA.dwFileAttributes member -FILE_ATTRIBUTE_ARCHIVE = 32 -FILE_ATTRIBUTE_COMPRESSED = 2048 -FILE_ATTRIBUTE_DEVICE = 64 -FILE_ATTRIBUTE_DIRECTORY = 16 -FILE_ATTRIBUTE_ENCRYPTED = 16384 -FILE_ATTRIBUTE_HIDDEN = 2 -FILE_ATTRIBUTE_INTEGRITY_STREAM = 32768 -FILE_ATTRIBUTE_NORMAL = 128 -FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192 -FILE_ATTRIBUTE_NO_SCRUB_DATA = 131072 -FILE_ATTRIBUTE_OFFLINE = 4096 -FILE_ATTRIBUTE_READONLY = 1 -FILE_ATTRIBUTE_REPARSE_POINT = 1024 -FILE_ATTRIBUTE_SPARSE_FILE = 512 -FILE_ATTRIBUTE_SYSTEM = 4 -FILE_ATTRIBUTE_TEMPORARY = 256 -FILE_ATTRIBUTE_VIRTUAL = 65536 - -IS_PY3 = sys.version_info >= (3, 0) - -if IS_PY3: - unicode = str # Because Python <= 3.2 doesn't have u'unicode' syntax - - -class GenericDirEntry(object): - __slots__ = ('name', '_stat', '_lstat', '_scandir_path', '_path') - - def __init__(self, scandir_path, name): - self._scandir_path = scandir_path - self.name = name - self._stat = None - self._lstat = None - self._path = None - - @property - def path(self): - if self._path is None: - self._path = join(self._scandir_path, self.name) - return self._path - - def stat(self, follow_symlinks=True): - if follow_symlinks: - if self._stat is None: - self._stat = stat(self.path) - return self._stat - else: - if self._lstat is None: - self._lstat = lstat(self.path) - return self._lstat - - # The code duplication below is intentional: this is for slightly - # better performance on systems that fall back to GenericDirEntry. - # It avoids an additional attribute lookup and method call, which - # are relatively slow on CPython. - def is_dir(self, follow_symlinks=True): - try: - st = self.stat(follow_symlinks=follow_symlinks) - except OSError as e: - if e.errno != ENOENT: - raise - return False # Path doesn't exist or is a broken symlink - return st.st_mode & 0o170000 == S_IFDIR - - def is_file(self, follow_symlinks=True): - try: - st = self.stat(follow_symlinks=follow_symlinks) - except OSError as e: - if e.errno != ENOENT: - raise - return False # Path doesn't exist or is a broken symlink - return st.st_mode & 0o170000 == S_IFREG - - def is_symlink(self): - try: - st = self.stat(follow_symlinks=False) - except OSError as e: - if e.errno != ENOENT: - raise - return False # Path doesn't exist or is a broken symlink - return st.st_mode & 0o170000 == S_IFLNK - - def inode(self): - st = self.stat(follow_symlinks=False) - return st.st_ino - - def __str__(self): - return '<{0}: {1!r}>'.format(self.__class__.__name__, self.name) - - __repr__ = __str__ - - -def _scandir_generic(path=unicode('.')): - """Like os.listdir(), but yield DirEntry objects instead of returning - a list of names. - """ - for name in listdir(path): - yield GenericDirEntry(path, name) - - -if IS_PY3 and sys.platform == 'win32': - def scandir_generic(path=unicode('.')): - if isinstance(path, bytes): - raise TypeError("os.scandir() doesn't support bytes path on Windows, use Unicode instead") - return _scandir_generic(path) - scandir_generic.__doc__ = _scandir_generic.__doc__ -else: - scandir_generic = _scandir_generic - - -scandir_c = None -scandir_python = None - - -if sys.platform == 'win32': - if ctypes is not None: - from ctypes import wintypes - - # Various constants from windows.h - INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value - ERROR_FILE_NOT_FOUND = 2 - ERROR_NO_MORE_FILES = 18 - IO_REPARSE_TAG_SYMLINK = 0xA000000C - - # Numer of seconds between 1601-01-01 and 1970-01-01 - SECONDS_BETWEEN_EPOCHS = 11644473600 - - kernel32 = ctypes.windll.kernel32 - - # ctypes wrappers for (wide string versions of) FindFirstFile, - # FindNextFile, and FindClose - FindFirstFile = kernel32.FindFirstFileW - FindFirstFile.argtypes = [ - wintypes.LPCWSTR, - ctypes.POINTER(wintypes.WIN32_FIND_DATAW), - ] - FindFirstFile.restype = wintypes.HANDLE - - FindNextFile = kernel32.FindNextFileW - FindNextFile.argtypes = [ - wintypes.HANDLE, - ctypes.POINTER(wintypes.WIN32_FIND_DATAW), - ] - FindNextFile.restype = wintypes.BOOL - - FindClose = kernel32.FindClose - FindClose.argtypes = [wintypes.HANDLE] - FindClose.restype = wintypes.BOOL - - Win32StatResult = collections.namedtuple('Win32StatResult', [ - 'st_mode', - 'st_ino', - 'st_dev', - 'st_nlink', - 'st_uid', - 'st_gid', - 'st_size', - 'st_atime', - 'st_mtime', - 'st_ctime', - 'st_atime_ns', - 'st_mtime_ns', - 'st_ctime_ns', - 'st_file_attributes', - ]) - - def filetime_to_time(filetime): - """Convert Win32 FILETIME to time since Unix epoch in seconds.""" - total = filetime.dwHighDateTime << 32 | filetime.dwLowDateTime - return total / 10000000 - SECONDS_BETWEEN_EPOCHS - - def find_data_to_stat(data): - """Convert Win32 FIND_DATA struct to stat_result.""" - # First convert Win32 dwFileAttributes to st_mode - attributes = data.dwFileAttributes - st_mode = 0 - if attributes & FILE_ATTRIBUTE_DIRECTORY: - st_mode |= S_IFDIR | 0o111 - else: - st_mode |= S_IFREG - if attributes & FILE_ATTRIBUTE_READONLY: - st_mode |= 0o444 - else: - st_mode |= 0o666 - if (attributes & FILE_ATTRIBUTE_REPARSE_POINT and - data.dwReserved0 == IO_REPARSE_TAG_SYMLINK): - st_mode ^= st_mode & 0o170000 - st_mode |= S_IFLNK - - st_size = data.nFileSizeHigh << 32 | data.nFileSizeLow - st_atime = filetime_to_time(data.ftLastAccessTime) - st_mtime = filetime_to_time(data.ftLastWriteTime) - st_ctime = filetime_to_time(data.ftCreationTime) - - # Some fields set to zero per CPython's posixmodule.c: st_ino, st_dev, - # st_nlink, st_uid, st_gid - return Win32StatResult(st_mode, 0, 0, 0, 0, 0, st_size, - st_atime, st_mtime, st_ctime, - int(st_atime * 1000000000), - int(st_mtime * 1000000000), - int(st_ctime * 1000000000), - attributes) - - class Win32DirEntryPython(object): - __slots__ = ('name', '_stat', '_lstat', '_find_data', '_scandir_path', '_path', '_inode') - - def __init__(self, scandir_path, name, find_data): - self._scandir_path = scandir_path - self.name = name - self._stat = None - self._lstat = None - self._find_data = find_data - self._path = None - self._inode = None - - @property - def path(self): - if self._path is None: - self._path = join(self._scandir_path, self.name) - return self._path - - def stat(self, follow_symlinks=True): - if follow_symlinks: - if self._stat is None: - if self.is_symlink(): - # It's a symlink, call link-following stat() - self._stat = stat(self.path) - else: - # Not a symlink, stat is same as lstat value - if self._lstat is None: - self._lstat = find_data_to_stat(self._find_data) - self._stat = self._lstat - return self._stat - else: - if self._lstat is None: - # Lazily convert to stat object, because it's slow - # in Python, and often we only need is_dir() etc - self._lstat = find_data_to_stat(self._find_data) - return self._lstat - - def is_dir(self, follow_symlinks=True): - is_symlink = self.is_symlink() - if follow_symlinks and is_symlink: - try: - return self.stat().st_mode & 0o170000 == S_IFDIR - except OSError as e: - if e.errno != ENOENT: - raise - return False - elif is_symlink: - return False - else: - return (self._find_data.dwFileAttributes & - FILE_ATTRIBUTE_DIRECTORY != 0) - - def is_file(self, follow_symlinks=True): - is_symlink = self.is_symlink() - if follow_symlinks and is_symlink: - try: - return self.stat().st_mode & 0o170000 == S_IFREG - except OSError as e: - if e.errno != ENOENT: - raise - return False - elif is_symlink: - return False - else: - return (self._find_data.dwFileAttributes & - FILE_ATTRIBUTE_DIRECTORY == 0) - - def is_symlink(self): - return (self._find_data.dwFileAttributes & - FILE_ATTRIBUTE_REPARSE_POINT != 0 and - self._find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK) - - def inode(self): - if self._inode is None: - self._inode = lstat(self.path).st_ino - return self._inode - - def __str__(self): - return '<{0}: {1!r}>'.format(self.__class__.__name__, self.name) - - __repr__ = __str__ - - def win_error(error, filename): - exc = WindowsError(error, ctypes.FormatError(error)) - exc.filename = filename - return exc - - def _scandir_python(path=unicode('.')): - """Like os.listdir(), but yield DirEntry objects instead of returning - a list of names. - """ - # Call FindFirstFile and handle errors - if isinstance(path, bytes): - is_bytes = True - filename = join(path.decode('mbcs', 'strict'), '*.*') - else: - is_bytes = False - filename = join(path, '*.*') - data = wintypes.WIN32_FIND_DATAW() - data_p = ctypes.byref(data) - handle = FindFirstFile(filename, data_p) - if handle == INVALID_HANDLE_VALUE: - error = ctypes.GetLastError() - if error == ERROR_FILE_NOT_FOUND: - # No files, don't yield anything - return - raise win_error(error, path) - - # Call FindNextFile in a loop, stopping when no more files - try: - while True: - # Skip '.' and '..' (current and parent directory), but - # otherwise yield (filename, stat_result) tuple - name = data.cFileName - if name not in ('.', '..'): - if is_bytes: - name = name.encode('mbcs', 'replace') - yield Win32DirEntryPython(path, name, data) - - data = wintypes.WIN32_FIND_DATAW() - data_p = ctypes.byref(data) - success = FindNextFile(handle, data_p) - if not success: - error = ctypes.GetLastError() - if error == ERROR_NO_MORE_FILES: - break - raise win_error(error, path) - finally: - if not FindClose(handle): - raise win_error(ctypes.GetLastError(), path) - - if IS_PY3: - def scandir_python(path=unicode('.')): - if isinstance(path, bytes): - raise TypeError("os.scandir() doesn't support bytes path on Windows, use Unicode instead") - return _scandir_python(path) - scandir_python.__doc__ = _scandir_python.__doc__ - else: - scandir_python = _scandir_python - - if _scandir is not None: - scandir_c = _scandir.scandir - DirEntry_c = _scandir.DirEntry - - if _scandir is not None: - scandir = scandir_c - DirEntry = DirEntry_c - elif ctypes is not None: - scandir = scandir_python - DirEntry = Win32DirEntryPython - else: - scandir = scandir_generic - DirEntry = GenericDirEntry - - -# Linux, OS X, and BSD implementation -elif sys.platform.startswith(('linux', 'darwin', 'sunos5')) or 'bsd' in sys.platform: - have_dirent_d_type = (sys.platform != 'sunos5') - - if ctypes is not None and have_dirent_d_type: - import ctypes.util - - DIR_p = ctypes.c_void_p - - # Rather annoying how the dirent struct is slightly different on each - # platform. The only fields we care about are d_name and d_type. - class Dirent(ctypes.Structure): - if sys.platform.startswith('linux'): - _fields_ = ( - ('d_ino', ctypes.c_ulong), - ('d_off', ctypes.c_long), - ('d_reclen', ctypes.c_ushort), - ('d_type', ctypes.c_byte), - ('d_name', ctypes.c_char * 256), - ) - elif 'openbsd' in sys.platform: - _fields_ = ( - ('d_ino', ctypes.c_uint64), - ('d_off', ctypes.c_uint64), - ('d_reclen', ctypes.c_uint16), - ('d_type', ctypes.c_uint8), - ('d_namlen', ctypes.c_uint8), - ('__d_padding', ctypes.c_uint8 * 4), - ('d_name', ctypes.c_char * 256), - ) - else: - _fields_ = ( - ('d_ino', ctypes.c_uint32), # must be uint32, not ulong - ('d_reclen', ctypes.c_ushort), - ('d_type', ctypes.c_byte), - ('d_namlen', ctypes.c_byte), - ('d_name', ctypes.c_char * 256), - ) - - DT_UNKNOWN = 0 - DT_DIR = 4 - DT_REG = 8 - DT_LNK = 10 - - Dirent_p = ctypes.POINTER(Dirent) - Dirent_pp = ctypes.POINTER(Dirent_p) - - libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True) - opendir = libc.opendir - opendir.argtypes = [ctypes.c_char_p] - opendir.restype = DIR_p - - readdir_r = libc.readdir_r - readdir_r.argtypes = [DIR_p, Dirent_p, Dirent_pp] - readdir_r.restype = ctypes.c_int - - closedir = libc.closedir - closedir.argtypes = [DIR_p] - closedir.restype = ctypes.c_int - - file_system_encoding = sys.getfilesystemencoding() - - class PosixDirEntry(object): - __slots__ = ('name', '_d_type', '_stat', '_lstat', '_scandir_path', '_path', '_inode') - - def __init__(self, scandir_path, name, d_type, inode): - self._scandir_path = scandir_path - self.name = name - self._d_type = d_type - self._inode = inode - self._stat = None - self._lstat = None - self._path = None - - @property - def path(self): - if self._path is None: - self._path = join(self._scandir_path, self.name) - return self._path - - def stat(self, follow_symlinks=True): - if follow_symlinks: - if self._stat is None: - if self.is_symlink(): - self._stat = stat(self.path) - else: - if self._lstat is None: - self._lstat = lstat(self.path) - self._stat = self._lstat - return self._stat - else: - if self._lstat is None: - self._lstat = lstat(self.path) - return self._lstat - - def is_dir(self, follow_symlinks=True): - if (self._d_type == DT_UNKNOWN or - (follow_symlinks and self.is_symlink())): - try: - st = self.stat(follow_symlinks=follow_symlinks) - except OSError as e: - if e.errno != ENOENT: - raise - return False - return st.st_mode & 0o170000 == S_IFDIR - else: - return self._d_type == DT_DIR - - def is_file(self, follow_symlinks=True): - if (self._d_type == DT_UNKNOWN or - (follow_symlinks and self.is_symlink())): - try: - st = self.stat(follow_symlinks=follow_symlinks) - except OSError as e: - if e.errno != ENOENT: - raise - return False - return st.st_mode & 0o170000 == S_IFREG - else: - return self._d_type == DT_REG - - def is_symlink(self): - if self._d_type == DT_UNKNOWN: - try: - st = self.stat(follow_symlinks=False) - except OSError as e: - if e.errno != ENOENT: - raise - return False - return st.st_mode & 0o170000 == S_IFLNK - else: - return self._d_type == DT_LNK - - def inode(self): - return self._inode - - def __str__(self): - return '<{0}: {1!r}>'.format(self.__class__.__name__, self.name) - - __repr__ = __str__ - - def posix_error(filename): - errno = ctypes.get_errno() - exc = OSError(errno, strerror(errno)) - exc.filename = filename - return exc - - def scandir_python(path=unicode('.')): - """Like os.listdir(), but yield DirEntry objects instead of returning - a list of names. - """ - if isinstance(path, bytes): - opendir_path = path - is_bytes = True - else: - opendir_path = path.encode(file_system_encoding) - is_bytes = False - dir_p = opendir(opendir_path) - if not dir_p: - raise posix_error(path) - try: - result = Dirent_p() - while True: - entry = Dirent() - if readdir_r(dir_p, entry, result): - raise posix_error(path) - if not result: - break - name = entry.d_name - if name not in (b'.', b'..'): - if not is_bytes: - name = name.decode(file_system_encoding) - yield PosixDirEntry(path, name, entry.d_type, entry.d_ino) - finally: - if closedir(dir_p): - raise posix_error(path) - - if _scandir is not None: - scandir_c = _scandir.scandir - DirEntry_c = _scandir.DirEntry - - if _scandir is not None: - scandir = scandir_c - DirEntry = DirEntry_c - elif ctypes is not None and have_dirent_d_type: - scandir = scandir_python - DirEntry = PosixDirEntry - else: - scandir = scandir_generic - DirEntry = GenericDirEntry - - -# Some other system -- no d_type or stat information -else: - scandir = scandir_generic - DirEntry = GenericDirEntry - - -def _walk(top, topdown=True, onerror=None, followlinks=False): - """Like Python 3.5's implementation of os.walk() -- faster than - the pre-Python 3.5 version as it uses scandir() internally. - """ - dirs = [] - nondirs = [] - - # We may not have read permission for top, in which case we can't - # get a list of the files the directory contains. os.walk - # always suppressed the exception then, rather than blow up for a - # minor reason when (say) a thousand readable directories are still - # left to visit. That logic is copied here. - try: - scandir_it = scandir(top) - except OSError as error: - if onerror is not None: - onerror(error) - return - - while True: - try: - try: - entry = next(scandir_it) - except StopIteration: - break - except OSError as error: - if onerror is not None: - onerror(error) - return - - try: - is_dir = entry.is_dir() - except OSError: - # If is_dir() raises an OSError, consider that the entry is not - # a directory, same behaviour than os.path.isdir(). - is_dir = False - - if is_dir: - dirs.append(entry.name) - else: - nondirs.append(entry.name) - - if not topdown and is_dir: - # Bottom-up: recurse into sub-directory, but exclude symlinks to - # directories if followlinks is False - if followlinks: - walk_into = True - else: - try: - is_symlink = entry.is_symlink() - except OSError: - # If is_symlink() raises an OSError, consider that the - # entry is not a symbolic link, same behaviour than - # os.path.islink(). - is_symlink = False - walk_into = not is_symlink - - if walk_into: - for entry in walk(entry.path, topdown, onerror, followlinks): - yield entry - - # Yield before recursion if going top down - if topdown: - yield top, dirs, nondirs - - # Recurse into sub-directories - for name in dirs: - new_path = join(top, name) - # Issue #23605: os.path.islink() is used instead of caching - # entry.is_symlink() result during the loop on os.scandir() because - # the caller can replace the directory entry during the "yield" - # above. - if followlinks or not islink(new_path): - for entry in walk(new_path, topdown, onerror, followlinks): - yield entry - else: - # Yield after recursion if going bottom up - yield top, dirs, nondirs - - -if IS_PY3 or sys.platform != 'win32': - walk = _walk -else: - # Fix for broken unicode handling on Windows on Python 2.x, see: - # https://github.com/benhoyt/scandir/issues/54 - file_system_encoding = sys.getfilesystemencoding() - - def walk(top, topdown=True, onerror=None, followlinks=False): - if isinstance(top, bytes): - top = top.decode(file_system_encoding) - return _walk(top, topdown, onerror, followlinks) diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_console_utils.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_console_utils.py index 4fe06f38..5c87ac82 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_console_utils.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_console_utils.py @@ -545,7 +545,7 @@ class BaseInterpreterInterface: try: # Try to import the packages needed to attach the debugger import pydevd - from _pydev_imps._pydev_saved_modules import threading + from _pydev_bundle._pydev_saved_modules import threading except: # This happens on Jython embedded in host eclipse traceback.print_exc() diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_import_hook.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_import_hook.py index 0c290447..519d8d76 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_import_hook.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_import_hook.py @@ -4,10 +4,7 @@ import traceback from types import ModuleType from _pydevd_bundle.pydevd_constants import DebugInfoHolder -if sys.version_info[0] >= 3: - import builtins # py3 -else: - import __builtin__ as builtins +import builtins class ImportHookManager(ModuleType): diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_imports.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_imports.py index fb912ead..edc24290 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_imports.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_imports.py @@ -1,24 +1,11 @@ -from _pydevd_bundle.pydevd_constants import USE_LIB_COPY, izip +from _pydev_bundle._pydev_saved_modules import xmlrpclib +from _pydev_bundle._pydev_saved_modules import xmlrpcserver -try: - if USE_LIB_COPY: - from _pydev_imps._pydev_saved_modules import xmlrpclib - else: - import xmlrpclib -except ImportError: - import xmlrpc.client as xmlrpclib +SimpleXMLRPCServer = xmlrpcserver.SimpleXMLRPCServer -if USE_LIB_COPY: - from _pydev_imps._pydev_saved_modules import xmlrpcserver - SimpleXMLRPCServer = xmlrpcserver.SimpleXMLRPCServer -else: - from xmlrpc.server import SimpleXMLRPCServer +from _pydev_bundle._pydev_execfile import execfile -from io import StringIO - -from _pydev_imps._pydev_execfile import execfile - -from _pydev_imps._pydev_saved_modules import _queue +from _pydev_bundle._pydev_saved_modules import _queue from _pydevd_bundle.pydevd_exec2 import Exec diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_ipython_console_011.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_ipython_console_011.py index f60a2d25..eaf4738b 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_ipython_console_011.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_ipython_console_011.py @@ -70,10 +70,7 @@ def create_editor_hook(pydev_host, pydev_client_port): server.IPythonEditor(filename, str(line)) if wait: - try: - raw_input("Press Enter when done editing:") - except NameError: - input("Press Enter when done editing:") + input("Press Enter when done editing:") return call_editor diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_is_thread_alive.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_is_thread_alive.py index f1bff3b6..d949ba25 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_is_thread_alive.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_is_thread_alive.py @@ -1,4 +1,4 @@ -from _pydev_imps._pydev_saved_modules import threading +from _pydev_bundle._pydev_saved_modules import threading # Hack for https://www.brainwy.com/tracker/PyDev/363 (i.e.: calling is_alive() can throw AssertionError under some # circumstances). diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_localhost.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_localhost.py index db134d8c..0d2838de 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_localhost.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_localhost.py @@ -1,4 +1,4 @@ -from _pydev_imps._pydev_saved_modules import socket +from _pydev_bundle._pydev_saved_modules import socket import sys IS_JYTHON = sys.platform.find('java') != -1 diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_log.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_log.py index 43935215..981b54bd 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_log.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_log.py @@ -224,5 +224,5 @@ def show_compile_cython_command_line(): if SHOW_COMPILE_CYTHON_COMMAND_LINE: dirname = os.path.dirname(os.path.dirname(__file__)) error_once("warning: Debugger speedups using cython not found. Run '\"%s\" \"%s\" build_ext --inplace' to build.", - sys.executable, os.path.join(dirname, 'setup_cython.py')) + sys.executable, os.path.join(dirname, 'setup_pydevd_cython.py')) diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py index 11b3747c..1f2fd500 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py @@ -2,7 +2,7 @@ import os import re import sys -from _pydev_imps._pydev_saved_modules import threading +from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \ sorted_dict_repr from _pydev_bundle import pydev_log @@ -11,11 +11,6 @@ from _pydevd_bundle import pydevd_constants from _pydevd_bundle.pydevd_defaults import PydevdCustomization import ast -try: - xrange -except: - xrange = range - try: from pathlib import Path except ImportError: @@ -584,7 +579,7 @@ def str_to_args_windows(args): buf = '' args_len = len(args) - for i in xrange(args_len): + for i in range(args_len): ch = args[i] if (ch == '\\'): backslashes += 1 @@ -1041,7 +1036,7 @@ class _NewThreadStartupWithTrace: if getattr(py_db, 'thread_analyser', None) is not None: try: - from pydevd_concurrency_analyser.pydevd_concurrency_logger import log_new_thread + from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import log_new_thread log_new_thread(py_db, t) except: sys.stderr.write("Failed to detect new thread for visualization") diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey_qt.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey_qt.py index 9a4a18e4..e348b842 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey_qt.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey_qt.py @@ -1,6 +1,6 @@ from __future__ import nested_scopes -from _pydev_imps._pydev_saved_modules import threading +from _pydev_bundle._pydev_saved_modules import threading import os from _pydev_bundle import pydev_log @@ -111,7 +111,7 @@ def _patch_import_to_patch_pyqt_on_import(patch_qt_on_import, get_qt_core_module dotted = patch_qt_on_import + '.' original_import = __import__ - from _pydev_imps._pydev_sys_patch import patch_sys_module, patch_reload, cancel_patches_in_sys_module + from _pydev_bundle._pydev_sys_patch import patch_sys_module, patch_reload, cancel_patches_in_sys_module patch_sys_module() patch_reload() @@ -123,11 +123,7 @@ def _patch_import_to_patch_pyqt_on_import(patch_qt_on_import, get_qt_core_module _internal_patch_qt(get_qt_core_module()) # Patch it only when the user would import the qt module return original_import(name, *args, **kwargs) - import sys - if sys.version_info[0] >= 3: - import builtins # Py3 - else: - import __builtin__ as builtins + import builtins # Py3 builtins.__import__ = patched_import diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_umd.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_umd.py index ac2d1b61..134ce4c5 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_umd.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_umd.py @@ -32,6 +32,8 @@ OTHER DEALINGS IN THE SOFTWARE. import sys import os +from _pydev_bundle._pydev_execfile import execfile + # The following classes and functions are mainly intended to be used from # an interactive Python session @@ -43,6 +45,7 @@ class UserModuleDeleter: pathlist [list]: ignore list in terms of module path namelist [list]: ignore list in terms of module name """ + def __init__(self, namelist=None, pathlist=None): if namelist is None: namelist = [] @@ -93,12 +96,17 @@ class UserModuleDeleter: print("\x1b[4;33m%s\x1b[24m%s\x1b[0m" % ("UMD has deleted", ": " + ", ".join(log))) + __umd__ = None _get_globals_callback = None + + def _set_globals_function(get_globals): global _get_globals_callback _get_globals_callback = get_globals + + def _get_globals(): """Return current Python interpreter globals namespace""" if _get_globals_callback is not None: @@ -144,7 +152,7 @@ def runfile(filename, args=None, wdir=None, namespace=None): else: verbose = os.environ.get("PYDEV_UMD_VERBOSE", "").lower() == "true" __umd__.run(verbose=verbose) - if args is not None and not isinstance(args, basestring): + if args is not None and not isinstance(args, (bytes, str)): raise TypeError("expected a character buffer object") if namespace is None: namespace = _get_globals() diff --git a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles.py b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles.py index 66e646d3..436cfad5 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles.py +++ b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles.py @@ -3,7 +3,7 @@ from __future__ import nested_scopes import fnmatch import os.path from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support -from _pydevd_bundle.pydevd_constants import * #@UnusedWildImport +from _pydevd_bundle.pydevd_constants import * # @UnusedWildImport import re import time @@ -237,7 +237,7 @@ def parse_cmdline(argv=None): ret_dirs = [] for d in dirs: if '|' in d: - #paths may come from the ide separated by | + # paths may come from the ide separated by | ret_dirs.extend(d.split('|')) else: ret_dirs.append(d) @@ -280,18 +280,18 @@ class PydevTestRunner(object): __py_extensions = ["*.py", "*.pyw"] __exclude_files = ["__init__.*"] - #Just to check that only this attributes will be written to this file + # Just to check that only this attributes will be written to this file __slots__ = [ - 'verbosity', #Always used + 'verbosity', # Always used - 'files_to_tests', #If this one is given, the ones below are not used + 'files_to_tests', # If this one is given, the ones below are not used - 'files_or_dirs', #Files or directories received in the command line - 'include_tests', #The filter used to collect the tests - 'tests', #Strings with the tests to be run + 'files_or_dirs', # Files or directories received in the command line + 'include_tests', # The filter used to collect the tests + 'tests', # Strings with the tests to be run - 'jobs', #Integer with the number of jobs that should be used to run the test cases - 'split_jobs', #String with 'tests' or 'module' (how should the jobs be split) + 'jobs', # Integer with the number of jobs that should be used to run the test cases + 'split_jobs', # String with 'tests' or 'module' (how should the jobs be split) 'configuration', 'coverage', @@ -316,11 +316,10 @@ class PydevTestRunner(object): self.configuration = configuration self.__adjust_path() - def __adjust_path(self): """ add the current file or directory to the python path """ path_to_append = None - for n in xrange(len(self.files_or_dirs)): + for n in range(len(self.files_or_dirs)): dir_name = self.__unixify(self.files_or_dirs[n]) if os.path.isdir(dir_name): if not dir_name.endswith("/"): @@ -336,8 +335,8 @@ class PydevTestRunner(object): msg = ("unknown type. \n%s\nshould be file or a directory.\n" % (dir_name)) raise RuntimeError(msg) if path_to_append is not None: - #Add it as the last one (so, first things are resolved against the default dirs and - #if none resolves, then we try a relative import). + # Add it as the last one (so, first things are resolved against the default dirs and + # if none resolves, then we try a relative import). sys.path.append(path_to_append) def __is_valid_py_file(self, fname): @@ -362,7 +361,7 @@ class PydevTestRunner(object): dirname, fname = os.path.split(s) if fname.count('.') > 1: - #if there's a file named xxx.xx.py, it is not a valid module, so, let's not load it... + # if there's a file named xxx.xx.py, it is not a valid module, so, let's not load it... return imp_stmt_pieces = [dirname.replace("\\", "/").replace("/", "."), os.path.splitext(fname)[0]] @@ -372,7 +371,7 @@ class PydevTestRunner(object): return ".".join(imp_stmt_pieces) - else: #handle dir + else: # handle dir return s.replace("\\", "/").replace("/", ".") def __add_files(self, pyfiles, root, files): @@ -382,7 +381,6 @@ class PydevTestRunner(object): name_without_base_dir = self.__unixify(os.path.join(root, fname)) pyfiles.append(name_without_base_dir) - def find_import_files(self): """ return a list of files to import """ if self.files_to_tests: @@ -392,31 +390,26 @@ class PydevTestRunner(object): for base_dir in self.files_or_dirs: if os.path.isdir(base_dir): - if hasattr(os, 'walk'): - for root, dirs, files in os.walk(base_dir): + for root, dirs, files in os.walk(base_dir): + # Note: handling directories that should be excluded from the search because + # they don't have __init__.py + exclude = {} + for d in dirs: + for init in ['__init__.py', '__init__.pyo', '__init__.pyc', '__init__.pyw', '__init__$py.class']: + if os.path.exists(os.path.join(root, d, init).replace('\\', '/')): + break + else: + exclude[d] = 1 - #Note: handling directories that should be excluded from the search because - #they don't have __init__.py - exclude = {} + if exclude: + new = [] for d in dirs: - for init in ['__init__.py', '__init__.pyo', '__init__.pyc', '__init__.pyw', '__init__$py.class']: - if os.path.exists(os.path.join(root, d, init).replace('\\', '/')): - break - else: - exclude[d] = 1 + if d not in exclude: + new.append(d) - if exclude: - new = [] - for d in dirs: - if d not in exclude: - new.append(d) + dirs[:] = new - dirs[:] = new - - self.__add_files(pyfiles, root, files) - else: - # jython2.1 is too old for os.walk! - os.path.walk(base_dir, self.__add_files, pyfiles) + self.__add_files(pyfiles, root, files) elif os.path.isfile(base_dir): pyfiles.append(base_dir) @@ -457,7 +450,6 @@ class PydevTestRunner(object): pyfiles = ret - return pyfiles def __get_module_from_str(self, modname, print_exception, pyfile): @@ -494,7 +486,7 @@ class PydevTestRunner(object): def find_modules_from_files(self, pyfiles): """ returns a list of modules given a list of files """ - #let's make sure that the paths we want are in the pythonpath... + # let's make sure that the paths we want are in the pythonpath... imports = [(s, self.__importify(s)) for s in pyfiles] sys_path = [os.path.normpath(path) for path in sys.path] @@ -507,14 +499,14 @@ class PydevTestRunner(object): ret = [] for pyfile, imp in imports: if imp is None: - continue #can happen if a file is not a valid module + continue # can happen if a file is not a valid module choices = [] for s in system_paths: if imp.startswith(s): add = imp[len(s) + 1:] if add: choices.append(add) - #sys.stdout.write(' ' + add + ' ') + # sys.stdout.write(' ' + add + ' ') if not choices: sys.stdout.write('PYTHONPATH not found for file: %s\n' % imp) @@ -526,7 +518,6 @@ class PydevTestRunner(object): ret.append((pyfile, mod, import_str)) break - return ret #=================================================================================================================== @@ -546,22 +537,21 @@ class PydevTestRunner(object): if className in self.accepted_classes: for attrname in dir(testCaseClass): - #If a class is chosen, we select all the 'test' methods' + # If a class is chosen, we select all the 'test' methods' if attrname.startswith('test') and hasattr(getattr(testCaseClass, attrname), '__call__'): testFnNames.append(attrname) else: for attrname in dir(testCaseClass): - #If we have the class+method name, we must do a full check and have an exact match. + # If we have the class+method name, we must do a full check and have an exact match. if className + '.' + attrname in self.accepted_methods: if hasattr(getattr(testCaseClass, attrname), '__call__'): testFnNames.append(attrname) - #sorted() is not available in jython 2.1 + # sorted() is not available in jython 2.1 testFnNames.sort() return testFnNames - def _decorate_test_suite(self, suite, pyfile, module_name): import unittest if isinstance(suite, unittest.TestSuite): @@ -583,11 +573,9 @@ class PydevTestRunner(object): else: return False - - def find_tests_from_modules(self, file_and_modules_and_module_name): """ returns the unittests given a list of modules """ - #Use our own suite! + # Use our own suite! from _pydev_runfiles import pydev_runfiles_unittest import unittest unittest.TestLoader.suiteClass = pydev_runfiles_unittest.PydevTestSuite @@ -609,7 +597,6 @@ class PydevTestRunner(object): ret.append(suite) return ret - if self.tests: accepted_classes = {} accepted_methods = {} @@ -624,7 +611,6 @@ class PydevTestRunner(object): loader.getTestCaseNames = self.GetTestCaseNames(accepted_classes, accepted_methods) - for pyfile, m, module_name in file_and_modules_and_module_name: suite = loader.loadTestsFromModule(m) if self._decorate_test_suite(suite, pyfile, module_name): @@ -632,14 +618,13 @@ class PydevTestRunner(object): return ret - def filter_tests(self, test_objs, internal_call=False): """ based on a filter name, only return those tests that have the test case names that match """ import unittest if not internal_call: if not self.configuration.include_tests and not self.tests and not self.configuration.exclude_tests: - #No need to filter if we have nothing to filter! + # No need to filter if we have nothing to filter! return test_objs if self.verbosity > 1: @@ -656,17 +641,17 @@ class PydevTestRunner(object): for test_obj in test_objs: if isinstance(test_obj, unittest.TestSuite): - #Note: keep the suites as they are and just 'fix' the tests (so, don't use the iter_tests). + # Note: keep the suites as they are and just 'fix' the tests (so, don't use the iter_tests). if test_obj._tests: test_obj._tests = self.filter_tests(test_obj._tests, True) - if test_obj._tests: #Only add the suite if we still have tests there. + if test_obj._tests: # Only add the suite if we still have tests there. test_suite.append(test_obj) elif isinstance(test_obj, unittest.TestCase): try: testMethodName = test_obj._TestCase__testMethodName except AttributeError: - #changed in python 2.5 + # changed in python 2.5 testMethodName = test_obj._testMethodName add = True @@ -699,9 +684,8 @@ class PydevTestRunner(object): testMethodName, self.configuration.include_tests,)) return test_suite - def iter_tests(self, test_objs): - #Note: not using yield because of Jython 2.1. + # Note: not using yield because of Jython 2.1. import unittest tests = [] for test_obj in test_objs: @@ -712,19 +696,17 @@ class PydevTestRunner(object): tests.append(test_obj) return tests - def list_test_names(self, test_objs): names = [] for tc in self.iter_tests(test_objs): try: testMethodName = tc._TestCase__testMethodName except AttributeError: - #changed in python 2.5 + # changed in python 2.5 testMethodName = tc._testMethodName names.append(testMethodName) return names - def __match_tests(self, tests, test_case, test_method_name): if not tests: return 1 @@ -732,7 +714,7 @@ class PydevTestRunner(object): for t in tests: class_and_method = t.split('.') if len(class_and_method) == 1: - #only class name + # only class name if class_and_method[0] == test_case.__class__.__name__: return 1 @@ -742,7 +724,6 @@ class PydevTestRunner(object): return 0 - def __match(self, filter_list, name): """ returns whether a test name matches the test filter """ if filter_list is None: @@ -752,7 +733,6 @@ class PydevTestRunner(object): return 1 return 0 - def run_tests(self, handle_coverage=True): """ runs all tests """ sys.stdout.write("Finding files... ") @@ -763,7 +743,6 @@ class PydevTestRunner(object): sys.stdout.write('done.\n') sys.stdout.write("Importing test modules ... ") - if handle_coverage: coverage_files, coverage = start_coverage_support(self.configuration) @@ -785,14 +764,14 @@ class PydevTestRunner(object): if self.jobs > 1: from _pydev_runfiles import pydev_runfiles_parallel - #What may happen is that the number of jobs needed is lower than the number of jobs requested - #(e.g.: 2 jobs were requested for running 1 test) -- in which case execute_tests_in_parallel will - #return False and won't run any tests. + # What may happen is that the number of jobs needed is lower than the number of jobs requested + # (e.g.: 2 jobs were requested for running 1 test) -- in which case execute_tests_in_parallel will + # return False and won't run any tests. executed_in_parallel = pydev_runfiles_parallel.execute_tests_in_parallel( all_tests, self.jobs, self.split_jobs, self.verbosity, coverage_files, self.configuration.coverage_include) if not executed_in_parallel: - #If in coverage, we don't need to pass anything here (coverage is already enabled for this execution). + # If in coverage, we don't need to pass anything here (coverage is already enabled for this execution). runner = pydev_runfiles_unittest.PydevTextTestRunner(stream=sys.stdout, descriptions=1, verbosity=self.verbosity) sys.stdout.write('\n') runner.run(test_suite) @@ -812,6 +791,7 @@ class PydevTestRunner(object): DJANGO_TEST_SUITE_RUNNER = None + def get_django_test_suite_runner(): global DJANGO_TEST_SUITE_RUNNER if DJANGO_TEST_SUITE_RUNNER: @@ -836,12 +816,15 @@ def get_django_test_suite_runner(): def run_suite(self, *args, **kwargs): self.on_run_suite() + except: # django < 1.8 try: from django.test.simple import DjangoTestSuiteRunner except: + class DjangoTestSuiteRunner: + def __init__(self): pass diff --git a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_parallel.py b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_parallel.py index 15d188e3..b34c45e9 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_parallel.py +++ b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_parallel.py @@ -1,15 +1,13 @@ import unittest -from _pydev_imps._pydev_saved_modules import thread -try: - import Queue -except: - import queue as Queue #@UnresolvedImport +from _pydev_bundle._pydev_saved_modules import thread +import queue as Queue from _pydev_runfiles import pydev_runfiles_xml_rpc import time import os import threading import sys + #======================================================================================================================= # flatten_test_suite #======================================================================================================================= @@ -52,11 +50,11 @@ def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, cov if get_global_debugger() is not None: return False except: - pass #Ignore any error here. + pass # Ignore any error here. - #This queue will receive the tests to be run. Each entry in a queue is a list with the tests to be run together When - #split == 'tests', each list will have a single element, when split == 'module', each list will have all the tests - #from a given module. + # This queue will receive the tests to be run. Each entry in a queue is a list with the tests to be run together When + # split == 'tests', each list will have a single element, when split == 'module', each list will have all the tests + # from a given module. tests_queue = [] queue_elements = [] @@ -73,7 +71,7 @@ def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, cov queue_elements.append(tests) if len(queue_elements) < jobs: - #Don't create jobs we will never use. + # Don't create jobs we will never use. jobs = len(queue_elements) elif split == 'tests': @@ -84,7 +82,7 @@ def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, cov queue_elements.append([test]) if len(queue_elements) < jobs: - #Don't create jobs we will never use. + # Don't create jobs we will never use. jobs = len(queue_elements) else: @@ -94,26 +92,24 @@ def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, cov test_queue_elements = [] for test_case in test_cases: try: - test_name = test_case.__class__.__name__+"."+test_case._testMethodName + test_name = test_case.__class__.__name__ + "." + test_case._testMethodName except AttributeError: - #Support for jython 2.1 (__testMethodName is pseudo-private in the test case) - test_name = test_case.__class__.__name__+"."+test_case._TestCase__testMethodName + # Support for jython 2.1 (__testMethodName is pseudo-private in the test case) + test_name = test_case.__class__.__name__ + "." + test_case._TestCase__testMethodName - test_queue_elements.append(test_case.__pydev_pyfile__+'|'+test_name) + test_queue_elements.append(test_case.__pydev_pyfile__ + '|' + test_name) tests_queue.append(test_queue_elements) if jobs < 2: return False - sys.stdout.write('Running tests in parallel with: %s jobs.\n' %(jobs,)) - + sys.stdout.write('Running tests in parallel with: %s jobs.\n' % (jobs,)) queue = Queue.Queue() for item in tests_queue: queue.put(item, block=False) - providers = [] clients = [] for i in range(jobs): @@ -135,7 +131,7 @@ def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, cov while client_alive: client_alive = False for client in clients: - #Wait for all the clients to exit. + # Wait for all the clients to exit. if not client.finished: client_alive = True time.sleep(.2) @@ -147,7 +143,6 @@ def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, cov return True - #======================================================================================================================= # CommunicationThread #======================================================================================================================= @@ -159,27 +154,9 @@ class CommunicationThread(threading.Thread): self.queue = tests_queue self.finished = False from _pydev_bundle.pydev_imports import SimpleXMLRPCServer - - - # This is a hack to patch slow socket.getfqdn calls that - # BaseHTTPServer (and its subclasses) make. - # See: http://bugs.python.org/issue6085 - # See: http://www.answermysearches.com/xmlrpc-server-slow-in-python-how-to-fix/2140/ - try: - import BaseHTTPServer - def _bare_address_string(self): - host, port = self.client_address[:2] - return '%s' % host - BaseHTTPServer.BaseHTTPRequestHandler.address_string = _bare_address_string - - except: - pass - # End hack. - + from _pydev_bundle import pydev_localhost # Create server - - from _pydev_bundle import pydev_localhost server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), 0), logRequests=False) server.register_function(self.GetTestsToRun) server.register_function(self.notifyStartTest) @@ -188,7 +165,6 @@ class CommunicationThread(threading.Thread): self.port = server.socket.getsockname()[1] self.server = server - def GetTestsToRun(self, job_id): ''' @param job_id: @@ -199,13 +175,12 @@ class CommunicationThread(threading.Thread): try: ret = self.queue.get(block=False) return ret - except: #Any exception getting from the queue (empty or not) means we finished our work on providing the tests. + except: # Any exception getting from the queue (empty or not) means we finished our work on providing the tests. self.finished = True return [] - def notifyCommands(self, job_id, commands): - #Batch notification. + # Batch notification. for command in commands: getattr(self, command[0])(job_id, *command[1], **command[2]) @@ -215,7 +190,6 @@ class CommunicationThread(threading.Thread): pydev_runfiles_xml_rpc.notifyStartTest(*args, **kwargs) return True - def notifyTest(self, job_id, *args, **kwargs): pydev_runfiles_xml_rpc.notifyTest(*args, **kwargs) return True @@ -235,7 +209,6 @@ class CommunicationThread(threading.Thread): self.server.handle_request() - #======================================================================================================================= # Client #======================================================================================================================= @@ -251,22 +224,20 @@ class ClientThread(threading.Thread): self.coverage_output_file = coverage_output_file self.coverage_include = coverage_include - def _reader_thread(self, pipe, target): while True: target.write(pipe.read(1)) - def run(self): try: from _pydev_runfiles import pydev_runfiles_parallel_client - #TODO: Support Jython: + # TODO: Support Jython: # - #For jython, instead of using sys.executable, we should use: - #r'D:\bin\jdk_1_5_09\bin\java.exe', - #'-classpath', - #'D:/bin/jython-2.2.1/jython.jar', - #'org.python.util.jython', + # For jython, instead of using sys.executable, we should use: + # r'D:\bin\jdk_1_5_09\bin\java.exe', + # '-classpath', + # 'D:/bin/jython-2.2.1/jython.jar', + # 'org.python.util.jython', args = [ sys.executable, @@ -284,9 +255,9 @@ class ClientThread(threading.Thread): if False: proc = subprocess.Popen(args, env=os.environ, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - thread.start_new_thread(self._reader_thread,(proc.stdout, sys.stdout)) + thread.start_new_thread(self._reader_thread, (proc.stdout, sys.stdout)) - thread.start_new_thread(target=self._reader_thread,args=(proc.stderr, sys.stderr)) + thread.start_new_thread(target=self._reader_thread, args=(proc.stderr, sys.stderr)) else: proc = subprocess.Popen(args, env=os.environ, shell=False) proc.wait() diff --git a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_pytest2.py b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_pytest2.py index d70399fa..793097da 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_pytest2.py +++ b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_pytest2.py @@ -7,11 +7,7 @@ from pydevd_file_utils import canonical_normalized_path import pytest import sys import time - -try: - from pathlib import Path -except: - Path = None +from pathlib import Path #========================================================================= # Load filters with tests we should skip @@ -27,14 +23,13 @@ def _load_filters(): py_test_accept_filter = pickle.loads( zlib.decompress(base64.b64decode(py_test_accept_filter))) - if Path is not None: - # Newer versions of pytest resolve symlinks, so, we - # may need to filter with a resolved path too. - new_dct = {} - for filename, value in py_test_accept_filter.items(): - new_dct[canonical_normalized_path(str(Path(filename).resolve()))] = value + # Newer versions of pytest resolve symlinks, so, we + # may need to filter with a resolved path too. + new_dct = {} + for filename, value in py_test_accept_filter.items(): + new_dct[canonical_normalized_path(str(Path(filename).resolve()))] = value - py_test_accept_filter.update(new_dct) + py_test_accept_filter.update(new_dct) else: py_test_accept_filter = {} @@ -203,30 +198,14 @@ def append_strings(s1, s2): if s1.__class__ == s2.__class__: return s1 + s2 - if sys.version_info[0] == 2: - if not isinstance(s1, basestring): - s1 = str(s1) + # Prefer str + if isinstance(s1, bytes): + s1 = s1.decode('utf-8', 'replace') - if not isinstance(s2, basestring): - s2 = str(s2) + if isinstance(s2, bytes): + s2 = s2.decode('utf-8', 'replace') - # Prefer bytes - if isinstance(s1, unicode): - s1 = s1.encode('utf-8') - - if isinstance(s2, unicode): - s2 = s2.encode('utf-8') - - return s1 + s2 - else: - # Prefer str - if isinstance(s1, bytes): - s1 = s1.decode('utf-8', 'replace') - - if isinstance(s2, bytes): - s2 = s2.decode('utf-8', 'replace') - - return s1 + s2 + return s1 + s2 def pytest_runtest_logreport(report): diff --git a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_unittest.py b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_unittest.py index d24c5e6e..fff1ef9c 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_unittest.py +++ b/src/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_unittest.py @@ -1,13 +1,10 @@ -try: - import unittest2 as python_unittest # @UnresolvedImport -except: - import unittest as python_unittest - +import unittest as python_unittest from _pydev_runfiles import pydev_runfiles_xml_rpc import time from _pydevd_bundle import pydevd_io import traceback -from _pydevd_bundle.pydevd_constants import * #@UnusedWildImport +from _pydevd_bundle.pydevd_constants import * # @UnusedWildImport +from io import StringIO #======================================================================================================================= @@ -21,6 +18,7 @@ class PydevTextTestRunner(python_unittest.TextTestRunner): _PythonTextTestResult = python_unittest.TextTestRunner()._makeResult().__class__ + #======================================================================================================================= # PydevTestResult #======================================================================================================================= @@ -37,7 +35,6 @@ class PydevTestResult(_PythonTextTestResult): error = (test, self._exc_info_to_string(err, test)) self._reportErrors([error], [], '', '%s %s' % (self.get_test_name(test), subdesc)) - def startTest(self, test): _PythonTextTestResult.startTest(self, test) self.buf = pydevd_io.start_redirect(keep_original_redirection=True, std='both') @@ -46,26 +43,23 @@ class PydevTestResult(_PythonTextTestResult): self._current_failures_stack = [] try: - test_name = test.__class__.__name__+"."+test._testMethodName + test_name = test.__class__.__name__ + "." + test._testMethodName except AttributeError: - #Support for jython 2.1 (__testMethodName is pseudo-private in the test case) - test_name = test.__class__.__name__+"."+test._TestCase__testMethodName + # Support for jython 2.1 (__testMethodName is pseudo-private in the test case) + test_name = test.__class__.__name__ + "." + test._TestCase__testMethodName pydev_runfiles_xml_rpc.notifyStartTest( test.__pydev_pyfile__, test_name) - - - def get_test_name(self, test): try: try: test_name = test.__class__.__name__ + "." + test._testMethodName except AttributeError: - #Support for jython 2.1 (__testMethodName is pseudo-private in the test case) + # Support for jython 2.1 (__testMethodName is pseudo-private in the test case) try: test_name = test.__class__.__name__ + "." + test._TestCase__testMethodName - #Support for class/module exceptions (test is instance of _ErrorHolder) + # Support for class/module exceptions (test is instance of _ErrorHolder) except: test_name = test.description.split()[1][1:-1] + ' <' + test.description.split()[0] + '>' except: @@ -73,7 +67,6 @@ class PydevTestResult(_PythonTextTestResult): return '' return test_name - def stopTest(self, test): end_time = time.time() pydevd_io.end_redirect(std='both') @@ -94,24 +87,23 @@ class PydevTestResult(_PythonTextTestResult): if skipped: pydev_runfiles_xml_rpc.notifyTest( - 'skip', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) + 'skip', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) elif not self._current_errors_stack and not self._current_failures_stack: pydev_runfiles_xml_rpc.notifyTest( 'ok', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) else: self._reportErrors(self._current_errors_stack, self._current_failures_stack, captured_output, test_name) - def _reportErrors(self, errors, failures, captured_output, test_name, diff_time=''): error_contents = [] - for test, s in errors+failures: - if type(s) == type((1,)): #If it's a tuple (for jython 2.1) + for test, s in errors + failures: + if type(s) == type((1,)): # If it's a tuple (for jython 2.1) sio = StringIO() traceback.print_exception(s[0], s[1], s[2], file=sio) s = sio.getvalue() error_contents.append(s) - sep = '\n'+self.separator1 + sep = '\n' + self.separator1 error_contents = sep.join(error_contents) if errors and not failures: @@ -122,7 +114,7 @@ class PydevTestResult(_PythonTextTestResult): file_start = error_contents.find('File "') file_end = error_contents.find('", ', file_start) if file_start != -1 and file_end != -1: - file = error_contents[file_start+6:file_end] + file = error_contents[file_start + 6:file_end] else: file = '' pydev_runfiles_xml_rpc.notifyTest( @@ -132,62 +124,27 @@ class PydevTestResult(_PythonTextTestResult): pydev_runfiles_xml_rpc.notifyTest( 'fail', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) - else: #Ok, we got both, errors and failures. Let's mark it as an error in the end. + else: # Ok, we got both, errors and failures. Let's mark it as an error in the end. pydev_runfiles_xml_rpc.notifyTest( 'error', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) - - def addError(self, test, err): _PythonTextTestResult.addError(self, test, err) - #Support for class/module exceptions (test is instance of _ErrorHolder) + # Support for class/module exceptions (test is instance of _ErrorHolder) if not hasattr(self, '_current_errors_stack') or test.__class__.__name__ == '_ErrorHolder': - #Not in start...end, so, report error now (i.e.: django pre/post-setup) + # Not in start...end, so, report error now (i.e.: django pre/post-setup) self._reportErrors([self.errors[-1]], [], '', self.get_test_name(test)) else: self._current_errors_stack.append(self.errors[-1]) - def addFailure(self, test, err): _PythonTextTestResult.addFailure(self, test, err) if not hasattr(self, '_current_failures_stack'): - #Not in start...end, so, report error now (i.e.: django pre/post-setup) + # Not in start...end, so, report error now (i.e.: django pre/post-setup) self._reportErrors([], [self.failures[-1]], '', self.get_test_name(test)) else: self._current_failures_stack.append(self.failures[-1]) -try: - #Version 2.7 onwards has a different structure... Let's not make any changes in it for now - #(waiting for bug: http://bugs.python.org/issue11798) - try: - from unittest2 import suite - except ImportError: - from unittest import suite - #=================================================================================================================== - # PydevTestSuite - #=================================================================================================================== - class PydevTestSuite(python_unittest.TestSuite): - pass - - -except ImportError: - - #=================================================================================================================== - # PydevTestSuite - #=================================================================================================================== - class PydevTestSuite(python_unittest.TestSuite): - - - def run(self, result): - for index, test in enumerate(self._tests): - if result.shouldStop: - break - test(result) - - # Let the memory be released! - self._tests[index] = None - - return result - - +class PydevTestSuite(python_unittest.TestSuite): + pass diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevconsole_code_for_ironpython.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevconsole_code_for_ironpython.py index 0b24780a..229f9f15 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevconsole_code_for_ironpython.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevconsole_code_for_ironpython.py @@ -4,22 +4,14 @@ # Inspired by similar code by Jeff Epler and Fredrik Lundh. - import sys import traceback - - - - - - - -#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 +# 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 @@ -85,44 +77,47 @@ _features = [getattr(__future__, fname) __all__ = ["compile_command", "Compile", "CommandCompiler"] -PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h +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 + break # Leave it alone else: if symbol != "eval": - source = "pass" # Replace it with a 'pass' statement + source = "pass" # Replace it with a 'pass' statement err = err1 = err2 = None code = code1 = code2 = None try: code = compiler(source, filename, symbol) - except SyntaxError, err: + except SyntaxError as err: pass try: code1 = compiler(source + "\n", filename, symbol) - except SyntaxError, err1: + except SyntaxError as err1: pass try: code2 = compiler(source + "\n\n", filename, symbol) - except SyntaxError, err2: + except SyntaxError as err2: pass if code: return code if not code1 and repr(err1) == repr(err2): - raise SyntaxError, err1 + raise SyntaxError(err1) + def _compile(source, filename, symbol): return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT) + def compile_command(source, filename="", symbol="single"): r"""Compile a command and determine whether it is incomplete. @@ -143,11 +138,13 @@ def compile_command(source, filename="", symbol="single"): """ 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 @@ -158,6 +155,7 @@ class Compile: 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 @@ -189,31 +187,17 @@ class CommandCompiler: """ 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 - - - - - - - - - - - - - - - +# 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"] + def softspace(file, newvalue): oldvalue = 0 try: @@ -227,6 +211,7 @@ def softspace(file, newvalue): pass return oldvalue + class InteractiveInterpreter: """Base class for InteractiveConsole. @@ -302,7 +287,7 @@ class InteractiveInterpreter: """ try: - exec code in self.locals + exec(code, self.locals) except SystemExit: raise except: @@ -411,11 +396,11 @@ class InteractiveConsole(InteractiveInterpreter): """ try: - sys.ps1 #@UndefinedVariable + sys.ps1 # @UndefinedVariable except AttributeError: sys.ps1 = ">>> " try: - sys.ps2 #@UndefinedVariable + sys.ps2 # @UndefinedVariable except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' @@ -429,14 +414,14 @@ class InteractiveConsole(InteractiveInterpreter): while 1: try: if more: - prompt = sys.ps2 #@UndefinedVariable + prompt = sys.ps2 # @UndefinedVariable else: - prompt = sys.ps1 #@UndefinedVariable + prompt = sys.ps1 # @UndefinedVariable try: line = self.raw_input(prompt) # Can be None if sys.stdin was redefined encoding = getattr(sys.stdin, "encoding", None) - if encoding and not isinstance(line, unicode): + if encoding and not isinstance(line, str): line = line.decode(encoding) except EOFError: self.write("\n") @@ -480,7 +465,7 @@ class InteractiveConsole(InteractiveInterpreter): implementation. """ - return raw_input(prompt) + return input(prompt) def interact(banner=None, readfunc=None, local=None): diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_api.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_api.py index cdd484c7..bdfce727 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_api.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_api.py @@ -2,7 +2,7 @@ import sys import bisect import types -from _pydev_imps._pydev_saved_modules import threading +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, @@ -325,7 +325,6 @@ class PyDevdAPI(object): def to_str(self, s): ''' - In py2 converts a unicode to str (bytes) using utf-8. -- in py3 raises an error if it's not str already. ''' if s.__class__ != str: @@ -334,7 +333,6 @@ class PyDevdAPI(object): def filename_to_str(self, filename): ''' - In py2 converts a unicode to str (bytes) using the file system encoding. -- in py3 raises an error if it's not str already. ''' if filename.__class__ != str: @@ -844,7 +842,7 @@ class PyDevdAPI(object): def set_project_roots(self, py_db, project_roots): ''' - :param unicode project_roots: + :param str project_roots: ''' py_db.set_project_roots(project_roots) diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_breakpoints.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_breakpoints.py index 1f14aae1..d92fccf5 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_breakpoints.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_breakpoints.py @@ -1,7 +1,7 @@ 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_imps._pydev_saved_modules import threading +from _pydev_bundle._pydev_saved_modules import threading class ExceptionBreakpoint(object): diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_code_to_source.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_code_to_source.py index a505d876..40feb767 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_code_to_source.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_code_to_source.py @@ -13,8 +13,6 @@ import sys import inspect from io import StringIO -xrange = range - class _Stack(object): @@ -317,7 +315,7 @@ class _CallFunction(_BaseHandler): def _handle(self): args = [] - for _i in xrange(self.instruction.argval + 1): + for _i in range(self.instruction.argval + 1): arg = self.stack.pop() args.append(arg) it = reversed(args) diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_collect_bytecode_info.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_collect_bytecode_info.py index 48f90efa..5dec3722 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_collect_bytecode_info.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_collect_bytecode_info.py @@ -4,11 +4,9 @@ import sys from collections import namedtuple from _pydev_bundle import pydev_log -from _pydevd_bundle.pydevd_constants import IS_PY38_OR_GREATER from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst, hasfree, hasjrel, haslocal, hasname, opname) -xrange = range from io import StringIO @@ -173,83 +171,7 @@ def collect_return_info(co, use_func_first_line=False): return lst -if sys.version_info[:2] < (3, 5): - - def collect_try_except_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 - - try_except_info_lst = [] - stack_in_setup = [] - - op_offset_to_line = dict(dis.findlinestarts(co)) - - for instruction in iter_instructions(co): - curr_op_name = instruction.opname - - if curr_op_name in ('SETUP_EXCEPT', 'SETUP_FINALLY'): - # We need to collect try..finally blocks too to make sure that - # the stack_in_setup we're using to collect info is correct. - # Note: On Py3.8 both except and finally statements use 'SETUP_FINALLY'. - try_except_info = TryExceptInfo( - _get_line(op_offset_to_line, instruction.offset, firstlineno, search=True), - ignore=curr_op_name == 'SETUP_FINALLY' - ) - 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, - ) - - try_except_info.except_end_bytecode_offset = instruction.argval - try_except_info.except_end_line = _get_line(op_offset_to_line, instruction.argval, firstlineno, search=True) - - stack_in_setup.append(try_except_info) - - elif curr_op_name == 'POP_EXCEPT': - # On Python 3.8 there's no SETUP_EXCEPT (both except and finally start with SETUP_FINALLY), - # so, we differentiate by a POP_EXCEPT. - if IS_PY38_OR_GREATER: - stack_in_setup[-1].ignore = False - - elif curr_op_name in ('WITH_CLEANUP_START', 'WITH_CLEANUP'): # WITH_CLEANUP is Python 2.7, WITH_CLEANUP_START Python 3. - stack_in_setup.append(TryExceptInfo(-1, ignore=True)) # Just there to be removed at END_FINALLY. - - elif curr_op_name == 'RAISE_VARARGS': - # We want to know about reraises and returns inside of except blocks (unfortunately - # a raise appears to the debugger as a return, so, we may need to differentiate). - if instruction.argval == 0: - for info in stack_in_setup: - info.raise_lines_in_except.append( - _get_line(op_offset_to_line, instruction.offset, firstlineno, search=True)) - - elif curr_op_name == 'END_FINALLY': # The except block also ends with 'END_FINALLY'. - stack_in_setup[-1].except_end_bytecode_offset = instruction.offset - stack_in_setup[-1].except_end_line = _get_line(op_offset_to_line, instruction.offset, firstlineno, search=True) - if not stack_in_setup[-1].ignore: - # Don't add try..finally blocks. - try_except_info_lst.append(stack_in_setup[-1]) - del stack_in_setup[-1] - - while stack_in_setup: - # On Py3 the END_FINALLY may not be there (so, the end of the function is also the end - # of the stack). - stack_in_setup[-1].except_end_bytecode_offset = instruction.offset - stack_in_setup[-1].except_end_line = _get_line(op_offset_to_line, instruction.offset, firstlineno, search=True) - if not stack_in_setup[-1].ignore: - # Don't add try..finally blocks. - try_except_info_lst.append(stack_in_setup[-1]) - del stack_in_setup[-1] - - return try_except_info_lst - -if (3, 5) <= sys.version_info[:2] <= (3, 9): +if sys.version_info[:2] <= (3, 9): class _TargetInfo(object): diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_comm.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_comm.py index 395544c6..97ec9556 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_comm.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_comm.py @@ -67,9 +67,9 @@ import linecache import os from _pydev_bundle.pydev_imports import _queue -from _pydev_imps._pydev_saved_modules import time -from _pydev_imps._pydev_saved_modules import threading -from _pydev_imps._pydev_saved_modules import socket as socket_module +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, silence_warnings_decorator) # Keep for backward compatibility @UnusedImport @@ -267,7 +267,7 @@ class ReaderThread(PyDBDaemonThread): 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 unicode + # 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'): diff --git a/src/debugpy/_vendored/pydevd/_pydev_imps/__init__.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/__init__.py similarity index 100% rename from src/debugpy/_vendored/pydevd/_pydev_imps/__init__.py rename to src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/__init__.py diff --git a/src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/pydevd_concurrency_logger.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_concurrency_logger.py similarity index 99% rename from src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/pydevd_concurrency_logger.py rename to src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_concurrency_logger.py index 8b500e26..95fc0543 100644 --- a/src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/pydevd_concurrency_logger.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_concurrency_logger.py @@ -1,12 +1,12 @@ import time from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding -from _pydev_imps._pydev_saved_modules import threading +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_concurrency_analyser.pydevd_thread_wrappers import ObjectWrapper, wrap_attr +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 diff --git a/src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/pydevd_thread_wrappers.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_thread_wrappers.py similarity index 84% rename from src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/pydevd_thread_wrappers.py rename to src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_thread_wrappers.py index 435e2879..526bb0c1 100644 --- a/src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/pydevd_thread_wrappers.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_thread_wrappers.py @@ -1,13 +1,15 @@ -from _pydev_imps._pydev_saved_modules import threading +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 @@ -18,6 +20,7 @@ def wrap_attr(obj, attr): class ObjectWrapper(object): + def __init__(self, obj): self.wrapped_object = obj try: @@ -27,8 +30,9 @@ class ObjectWrapper(object): pass def __getattr__(self, attr): - orig_attr = getattr(self.wrapped_object, attr) #.__getattribute__(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) @@ -36,6 +40,7 @@ class ObjectWrapper(object): if result == self.wrapped_object: return self return result + return patched_attr else: return orig_attr @@ -57,9 +62,11 @@ class ObjectWrapper(object): def factory_wrapper(fun): + def inner(*args, **kwargs): obj = fun(*args, **kwargs) return ObjectWrapper(obj) + return inner @@ -68,15 +75,9 @@ def wrap_threads(): # import _thread as mod # print("Thread imported") # mod.start_new_thread = wrapper(mod.start_new_thread) - import threading threading.Lock = factory_wrapper(threading.Lock) threading.RLock = factory_wrapper(threading.RLock) # queue patching - try: - import queue # @UnresolvedImport - queue.Queue = factory_wrapper(queue.Queue) - except: - import Queue - Queue.Queue = factory_wrapper(Queue.Queue) - + import queue # @UnresolvedImport + queue.Queue = factory_wrapper(queue.Queue) diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_constants.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_constants.py index 61705b7c..2ae93c6b 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_constants.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_constants.py @@ -15,10 +15,7 @@ PYTHON_SUSPEND = 1 DJANGO_SUSPEND = 2 JINJA2_SUSPEND = 3 -try: - int_types = (int, long) -except NameError: - int_types = (int,) +int_types = (int,) # types does not include a MethodWrapperType try: @@ -336,7 +333,7 @@ def protect_libraries_from_patching(): `_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', 'queue', 'select', + patched = ['threading', 'thread', '_thread', 'time', 'socket', 'queue', 'select', 'xmlrpclib', 'SimpleXMLRPCServer', 'BaseHTTPServer', 'SocketServer', 'xmlrpc.client', 'xmlrpc.server', 'http.server', 'socketserver'] @@ -353,7 +350,7 @@ def protect_libraries_from_patching(): del sys.modules[name] # import for side effects - import _pydev_imps._pydev_saved_modules + import _pydev_bundle._pydev_saved_modules for name in patched_modules: sys.modules[name] = patched_modules[name] @@ -362,7 +359,7 @@ def protect_libraries_from_patching(): if USE_LIB_COPY: protect_libraries_from_patching() -from _pydev_imps._pydev_saved_modules import thread, threading +from _pydev_bundle._pydev_saved_modules import thread, threading _fork_safe_locks = [] @@ -463,7 +460,7 @@ def sorted_dict_repr(d): def iter_chars(b): - # In Python 2, we can iterate bytes or unicode with individual characters, but Python 3 onwards + # 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) @@ -471,10 +468,6 @@ def iter_chars(b): return iter(b) -# Python 3k does not have it -xrange = range -izip = zip - if IS_JYTHON: def NO_FTRACE(frame, event, arg): diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_custom_frames.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_custom_frames.py index 94cabd74..66e400fb 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_custom_frames.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_custom_frames.py @@ -1,6 +1,6 @@ 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_imps._pydev_saved_modules import thread, threading +from _pydev_bundle._pydev_saved_modules import thread, threading import sys from _pydev_bundle import pydev_log diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.c b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.c index 40640a5a..a012fe76 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.c +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.c @@ -2034,8 +2034,8 @@ static const char __pyx_k_TopLevelThreadTracerNoBackFrame[] = "TopLevelThreadTra static const char __pyx_k_Unable_to_get_topmost_frame_for[] = "Unable to get topmost frame for thread: %s, thread.ident: %s, id(thread): %s\nCurrent frames: %s.\nGEVENT_SUPPORT: %s"; static const char __pyx_k_get_abs_path_real_path_and_base[] = "get_abs_path_real_path_and_base_from_frame"; static const char __pyx_k_global_notify_skipped_step_in_l[] = "_global_notify_skipped_step_in_lock"; +static const char __pyx_k_pydev_bundle__pydev_saved_modul[] = "_pydev_bundle._pydev_saved_modules"; static const char __pyx_k_pydev_bundle_pydev_is_thread_al[] = "_pydev_bundle.pydev_is_thread_alive"; -static const char __pyx_k_pydev_imps__pydev_saved_modules[] = "_pydev_imps._pydev_saved_modules"; static const char __pyx_k_pydevd_bundle_pydevd_bytecode_u[] = "_pydevd_bundle.pydevd_bytecode_utils"; static const char __pyx_k_pydevd_bundle_pydevd_comm_const[] = "_pydevd_bundle.pydevd_comm_constants"; static const char __pyx_k_pydevd_bundle_pydevd_cython_pyx[] = "_pydevd_bundle/pydevd_cython.pyx"; @@ -2255,11 +2255,11 @@ static PyObject *__pyx_n_s_pop; static PyObject *__pyx_n_s_py_db; static PyObject *__pyx_n_s_pydb_disposed; static PyObject *__pyx_n_s_pydev_bundle; +static PyObject *__pyx_n_s_pydev_bundle__pydev_saved_modul; static PyObject *__pyx_n_s_pydev_bundle_pydev_is_thread_al; static PyObject *__pyx_n_s_pydev_bundle_pydev_log; static PyObject *__pyx_n_s_pydev_do_not_trace; static PyObject *__pyx_kp_s_pydev_execfile_py; -static PyObject *__pyx_n_s_pydev_imps__pydev_saved_modules; static PyObject *__pyx_n_s_pydev_log; static PyObject *__pyx_n_s_pydev_log_exception; static PyObject *__pyx_n_s_pydev_monkey; @@ -36407,11 +36407,11 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_py_db, __pyx_k_py_db, sizeof(__pyx_k_py_db), 0, 0, 1, 1}, {&__pyx_n_s_pydb_disposed, __pyx_k_pydb_disposed, sizeof(__pyx_k_pydb_disposed), 0, 0, 1, 1}, {&__pyx_n_s_pydev_bundle, __pyx_k_pydev_bundle, sizeof(__pyx_k_pydev_bundle), 0, 0, 1, 1}, + {&__pyx_n_s_pydev_bundle__pydev_saved_modul, __pyx_k_pydev_bundle__pydev_saved_modul, sizeof(__pyx_k_pydev_bundle__pydev_saved_modul), 0, 0, 1, 1}, {&__pyx_n_s_pydev_bundle_pydev_is_thread_al, __pyx_k_pydev_bundle_pydev_is_thread_al, sizeof(__pyx_k_pydev_bundle_pydev_is_thread_al), 0, 0, 1, 1}, {&__pyx_n_s_pydev_bundle_pydev_log, __pyx_k_pydev_bundle_pydev_log, sizeof(__pyx_k_pydev_bundle_pydev_log), 0, 0, 1, 1}, {&__pyx_n_s_pydev_do_not_trace, __pyx_k_pydev_do_not_trace, sizeof(__pyx_k_pydev_do_not_trace), 0, 0, 1, 1}, {&__pyx_kp_s_pydev_execfile_py, __pyx_k_pydev_execfile_py, sizeof(__pyx_k_pydev_execfile_py), 0, 0, 1, 0}, - {&__pyx_n_s_pydev_imps__pydev_saved_modules, __pyx_k_pydev_imps__pydev_saved_modules, sizeof(__pyx_k_pydev_imps__pydev_saved_modules), 0, 0, 1, 1}, {&__pyx_n_s_pydev_log, __pyx_k_pydev_log, sizeof(__pyx_k_pydev_log), 0, 0, 1, 1}, {&__pyx_n_s_pydev_log_exception, __pyx_k_pydev_log_exception, sizeof(__pyx_k_pydev_log_exception), 0, 0, 1, 1}, {&__pyx_n_s_pydev_monkey, __pyx_k_pydev_monkey, sizeof(__pyx_k_pydev_monkey), 0, 0, 1, 1}, @@ -37781,7 +37781,7 @@ if (!__Pyx_RefNanny) { * # end trace_dispatch * from _pydev_bundle.pydev_is_thread_alive import is_thread_alive # <<<<<<<<<<<<<< * from _pydev_bundle.pydev_log import exception as pydev_log_exception - * from _pydev_imps._pydev_saved_modules import threading + * from _pydev_bundle._pydev_saved_modules import threading */ __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1310, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); @@ -37801,7 +37801,7 @@ if (!__Pyx_RefNanny) { * # end trace_dispatch * from _pydev_bundle.pydev_is_thread_alive import is_thread_alive * from _pydev_bundle.pydev_log import exception as pydev_log_exception # <<<<<<<<<<<<<< - * from _pydev_imps._pydev_saved_modules import threading + * from _pydev_bundle._pydev_saved_modules import threading * from _pydevd_bundle.pydevd_constants import (get_current_thread_id, NO_FTRACE, */ __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1311, __pyx_L1_error) @@ -37821,7 +37821,7 @@ if (!__Pyx_RefNanny) { /* "_pydevd_bundle/pydevd_cython.pyx":1312 * from _pydev_bundle.pydev_is_thread_alive import is_thread_alive * from _pydev_bundle.pydev_log import exception as pydev_log_exception - * from _pydev_imps._pydev_saved_modules import threading # <<<<<<<<<<<<<< + * 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) */ @@ -37830,7 +37830,7 @@ if (!__Pyx_RefNanny) { __Pyx_INCREF(__pyx_n_s_threading); __Pyx_GIVEREF(__pyx_n_s_threading); PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_threading); - __pyx_t_1 = __Pyx_Import(__pyx_n_s_pydev_imps__pydev_saved_modules, __pyx_t_2, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1312, __pyx_L1_error) + __pyx_t_1 = __Pyx_Import(__pyx_n_s_pydev_bundle__pydev_saved_modul, __pyx_t_2, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1312, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_threading); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1312, __pyx_L1_error) @@ -37841,7 +37841,7 @@ if (!__Pyx_RefNanny) { /* "_pydevd_bundle/pydevd_cython.pyx":1313 * from _pydev_bundle.pydev_log import exception as pydev_log_exception - * from _pydev_imps._pydev_saved_modules import threading + * 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 diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.pyx b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.pyx index 2a999dad..1d34632f 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.pyx +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython.pyx @@ -1309,7 +1309,7 @@ cdef class PyDBFrame: # end trace_dispatch from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_bundle.pydev_log import exception as pydev_log_exception -from _pydev_imps._pydev_saved_modules import threading +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 diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_daemon_thread.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_daemon_thread.py index 6599836a..f17e2600 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_daemon_thread.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_daemon_thread.py @@ -1,5 +1,5 @@ -from _pydev_imps._pydev_saved_modules import threading -from _pydev_imps import _pydev_saved_modules +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, \ diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_dont_trace_files.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_dont_trace_files.py index 4222daea..e95446d5 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_dont_trace_files.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_dont_trace_files.py @@ -8,7 +8,6 @@ PYDEV_FILE = 2 DONT_TRACE_DIRS = { '_pydev_bundle': PYDEV_FILE, - '_pydev_imps': PYDEV_FILE, '_pydev_runfiles': PYDEV_FILE, '_pydevd_bundle': PYDEV_FILE, '_pydevd_frame_eval': PYDEV_FILE, @@ -32,7 +31,6 @@ DONT_TRACE = { 'dis.py':LIB_FILE, # things from pydev that we don't want to trace - '_pydev_execfile.py':PYDEV_FILE, '__main__pydevd_gen_debug_adapter_protocol.py': PYDEV_FILE, '_pydev_calltip_util.py': PYDEV_FILE, '_pydev_completer.py': PYDEV_FILE, @@ -143,7 +141,6 @@ DONT_TRACE = { 'pydevd_vars.py': PYDEV_FILE, 'pydevd_vm_type.py': PYDEV_FILE, 'pydevd_xml.py': PYDEV_FILE, - 'scandir_vendored.py': PYDEV_FILE, } # if we try to trace io.py it seems it can get halted (see http://bugs.python.org/issue4716) diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_filtering.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_filtering.py index b103ac66..67fd6cfd 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_filtering.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_filtering.py @@ -7,28 +7,16 @@ from _pydev_bundle import pydev_log import pydevd_file_utils import json from collections import namedtuple -from _pydev_imps._pydev_saved_modules import threading +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 -try: - xrange # noqa -except NameError: - xrange = range # noqa - ExcludeFilter = namedtuple('ExcludeFilter', 'name, exclude, is_path') def _convert_to_str_and_clear_empty(roots): - if sys.version_info[0] <= 2: - # In py2 we need bytes for the files. - roots = [ - root if not isinstance(root, unicode) else root.encode(sys.getfilesystemencoding()) - for root in roots - ] - new_roots = [] for root in roots: assert isinstance(root, str), '%s not str (found: %s)' % (root, type(root)) @@ -57,7 +45,7 @@ def _check_matches(patterns, paths): if len(patterns) == 1: return True # if ** is the last one it matches anything to the right. - for i in xrange(len(paths)): + 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:]): diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_gevent_integration.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_gevent_integration.py index 605c717e..ca404ba2 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_gevent_integration.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_gevent_integration.py @@ -1,7 +1,7 @@ import pydevd_tracing import greenlet import gevent -from _pydev_imps._pydev_saved_modules import threading +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 diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_json_debug_options.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_json_debug_options.py index 96ed582b..49232684 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_json_debug_options.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_json_debug_options.py @@ -1,11 +1,5 @@ -import sys import json -from _pydev_bundle import pydev_log -try: - import urllib - urllib.unquote # noqa -except Exception: - import urllib.parse as urllib +import urllib.parse as urllib_parse class DebugOptions(object): @@ -97,6 +91,7 @@ class DebugOptions(object): if 'guiEventLoop' in args: self.gui_event_loop = str(args['guiEventLoop']) + def int_parser(s, default_value=0): try: return int(s) @@ -108,24 +103,9 @@ def bool_parser(s): return s in ("True", "true", "1", True, 1) -if sys.version_info >= (3,): +def unquote(s): + return None if s is None else urllib_parse.unquote(s) - def unquote(s): - return None if s is None else urllib.unquote(s) - -else: - - # In Python 2, urllib.unquote doesn't handle Unicode strings correctly, - # so we need to convert to ASCII first, unquote, and then decode. - def unquote(s): - if s is None: - return None - if not isinstance(s, bytes): - s = bytes(s) - s = urllib.unquote(s) - if isinstance(s, bytes): - s = s.decode('utf-8') - return s DEBUG_OPTIONS_PARSER = { 'WAIT_ON_ABNORMAL_EXIT': bool_parser, diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_net_command_factory_xml.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_net_command_factory_xml.py index c0a8915a..2836575d 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_net_command_factory_xml.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_net_command_factory_xml.py @@ -1,7 +1,7 @@ import json from _pydev_bundle.pydev_is_thread_alive import is_thread_alive -from _pydev_imps._pydev_saved_modules import thread +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, @@ -17,7 +17,7 @@ from _pydevd_bundle.pydevd_comm_constants import ( 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, IS_IRONPYTHON, +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 @@ -29,12 +29,6 @@ from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_frame_utils import FramesList from io import StringIO -if IS_IRONPYTHON: - - # redefine `unquote` for IronPython, since we use it only for logging messages, but it leads to SOF with IronPython - def unquote(s): - return s - #======================================================================================================================= # NetCommandFactory diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_process_net_command.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_process_net_command.py index 332439ee..e3afdcd8 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_process_net_command.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_process_net_command.py @@ -14,7 +14,7 @@ from _pydevd_bundle.pydevd_comm import ( 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 _pydev_bundle.pydev_imports import StringIO +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 diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_referrers.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_referrers.py index d8dd6bd6..f7c135b8 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_referrers.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_referrers.py @@ -1,12 +1,8 @@ import sys from _pydevd_bundle import pydevd_xml from os.path import basename -import traceback from _pydev_bundle import pydev_log -try: - from urllib import quote, quote_plus, unquote, unquote_plus -except: - from urllib.parse import quote, quote_plus, unquote, unquote_plus # @Reimport @UnresolvedImport +from urllib.parse import unquote_plus #=================================================================================================== diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_resolver.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_resolver.py index d981500e..ac7aa100 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_resolver.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_resolver.py @@ -5,7 +5,7 @@ import traceback from os.path import basename from functools import partial -from _pydevd_bundle.pydevd_constants import xrange, IS_PY36_OR_GREATER, \ +from _pydevd_bundle.pydevd_constants import IS_PY36_OR_GREATER, \ MethodWrapperType, RETURN_VALUES_DICT, DebugInfoHolder, IS_PYPY, GENERATED_LEN_ATTR_NAME from _pydevd_bundle.pydevd_safe_repr import SafeRepr @@ -117,12 +117,12 @@ class DefaultResolver: declaredMethods = obj.getDeclaredMethods() declaredFields = obj.getDeclaredFields() - for i in xrange(len(declaredMethods)): + for i in range(len(declaredMethods)): name = declaredMethods[i].getName() ret[name] = declaredMethods[i].toString() found.put(name, 1) - for i in xrange(len(declaredFields)): + for i in range(len(declaredFields)): name = declaredFields[i].getName() found.put(name, 1) # if declaredFields[i].isAccessible(): @@ -218,10 +218,6 @@ class DAPGrouperResolver: _basic_immutable_types = (int, float, complex, str, bytes, type(None), bool, frozenset) -try: - _basic_immutable_types += (long, unicode) # Py2 types -except NameError: - pass def _does_obj_repr_evaluate_to_obj(obj): @@ -514,7 +510,7 @@ class InstanceResolver: ret = {} declaredFields = obj.__class__.getDeclaredFields() - for i in xrange(len(declaredFields)): + for i in range(len(declaredFields)): name = declaredFields[i].getName() try: declaredFields[i].setAccessible(True) @@ -541,7 +537,7 @@ class JyArrayResolver: def get_dictionary(self, obj): ret = {} - for i in xrange(len(obj)): + for i in range(len(obj)): ret[ i ] = obj[i] ret[GENERATED_LEN_ATTR_NAME] = len(obj) diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_safe_repr.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_safe_repr.py index 8b255c31..f1b64b75 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_safe_repr.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_safe_repr.py @@ -8,16 +8,6 @@ from _pydevd_bundle.pydevd_constants import IS_PY36_OR_GREATER import locale from _pydev_bundle import pydev_log -# Py3 compat - alias unicode to str, and xrange to range -try: - unicode # noqa -except NameError: - unicode = str -try: - xrange # noqa -except NameError: - xrange = range - class SafeRepr(object): # Can be used to override the encoding from locale.getpreferredencoding() @@ -31,22 +21,13 @@ class SafeRepr(object): # collections. maxstring_outer = 2 ** 16 maxstring_inner = 30 - if sys.version_info >= (3, 0): - 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) - else: - string_types = (str, unicode) - bytes = str - set_info = (set, 'set([', '])', False) - frozenset_info = (frozenset, 'frozenset([', '])', False) - int_types = (int, long) # noqa - long_iter_types = (list, tuple, bytearray, xrange, - dict, set, frozenset, buffer) # noqa + 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. @@ -160,8 +141,8 @@ class SafeRepr(object): if obj is iter(obj): return False - # xrange reprs fine regardless of length. - if isinstance(obj, xrange): + # range reprs fine regardless of length. + if isinstance(obj, range): return False # numpy and scipy collections (ndarray etc) have diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_signature.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_signature.py index bf990f9c..3877e622 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_signature.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_signature.py @@ -10,7 +10,6 @@ else: import os from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand from _pydevd_bundle import pydevd_xml -from _pydevd_bundle.pydevd_constants import xrange from _pydevd_bundle.pydevd_utils import get_clsname_for_code @@ -33,7 +32,7 @@ class Signature(object): code = frame.f_code locals = frame.f_locals - for i in xrange(0, code.co_argcount): + for i in range(0, code.co_argcount): name = code.co_varnames[i] class_name = get_type_of_value(locals[name], recursive=recursive) diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_stackless.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_stackless.py index 83ea8ff0..44bb768a 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_stackless.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_stackless.py @@ -5,7 +5,7 @@ import sys from _pydevd_bundle.pydevd_comm import get_global_debugger from _pydevd_bundle.pydevd_constants import call_only_once -from _pydev_imps._pydev_saved_modules import threading +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 diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_suspended_frames.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_suspended_frames.py index 53337025..955ba9a1 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_suspended_frames.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_suspended_frames.py @@ -51,7 +51,7 @@ class _AbstractVariable(object): 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', 'unicode', 'bytes', 'bytearray') + is_raw_string = type_name in ('str', 'bytes', 'bytearray') attributes = [] diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_thread_lifecycle.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_thread_lifecycle.py index 3f3a4e14..069b6b6a 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_thread_lifecycle.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_thread_lifecycle.py @@ -2,8 +2,7 @@ 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_imps._pydev_saved_modules import threading -import sys +from _pydev_bundle._pydev_saved_modules import threading from _pydev_bundle import pydev_log diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_timeout.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_timeout.py index 17560ee6..4a18cafc 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_timeout.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_timeout.py @@ -1,4 +1,4 @@ -from _pydev_imps._pydev_saved_modules import threading +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 diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_trace_dispatch_regular.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_trace_dispatch_regular.py index 552ec6b2..88a3f083 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_trace_dispatch_regular.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_trace_dispatch_regular.py @@ -1,6 +1,6 @@ from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_bundle.pydev_log import exception as pydev_log_exception -from _pydev_imps._pydev_saved_modules import threading +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 diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_utils.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_utils.py index 5a5ae8af..a45caa1b 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_utils.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_utils.py @@ -2,22 +2,19 @@ from __future__ import nested_scopes import traceback import warnings from _pydev_bundle import pydev_log -from _pydev_imps._pydev_saved_modules import thread -from _pydev_imps import _pydev_saved_modules +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 -from _pydev_imps._pydev_saved_modules import threading def save_main_module(file, module_name): diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_vars.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_vars.py index 12d35d46..f214fa7c 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_vars.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_vars.py @@ -2,7 +2,7 @@ resolution/conversion to XML. """ import pickle -from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, xrange, \ +from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \ iter_chars, silence_warnings_decorator from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml @@ -13,7 +13,7 @@ from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK import sys # @Reimport -from _pydev_imps._pydev_saved_modules import threading +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 @@ -95,7 +95,7 @@ def getVariable(dbg, thread_id, frame_id, scope, attrs): attr.replace("@_@TAB_CHAR@_@", '\t') if scope == 'EXPRESSION': - for count in xrange(len(attrList)): + 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) @@ -577,9 +577,9 @@ def array_to_xml(array, roffset, coffset, rows, cols, format): rows = min(rows, len(array)) xml += "" % (rows, cols) - for row in xrange(rows): + for row in range(rows): xml += "" % to_string(row) - for col in xrange(cols): + for col in range(cols): value = array if rows == 1 or cols == 1: if rows == 1 and cols == 1: @@ -608,7 +608,7 @@ def array_to_meta_xml(array, name, format): if format == '%': if l > 2: slice += '[0]' * (l - 2) - for r in xrange(l - 2): + for r in range(l - 2): array = array[0] if type == 'f': format = '.5f' @@ -691,7 +691,7 @@ def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format): cols = min(min(cols, MAXIMUM_ARRAY_SIZE), num_cols) # need to precompute column bounds here before slicing! col_bounds = [None] * cols - for col in xrange(cols): + for col in range(cols): dtype = df.dtypes.iloc[coffset + col].kind if dtype in "biufc": cvalues = df.iloc[:, coffset + col] @@ -709,7 +709,7 @@ def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format): get_label = lambda label: str(label) if not isinstance(label, tuple) else '/'.join(map(str, label)) - for col in xrange(cols): + for col in range(cols): dtype = df.dtypes.iloc[col].kind if dtype == 'f' and format: fmt = format @@ -729,9 +729,9 @@ def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format): (str(row), get_label(label)) xml += "\n" xml += "\n" % (rows, cols) - for row in xrange(rows): + for row in range(rows): xml += "\n" % str(row) - for col in xrange(cols): + for col in range(cols): value = df.iat[row, col] value = col_formats[col] % value xml += var_to_xml(value, '') diff --git a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_xml.py b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_xml.py index 85c51a61..dcd1cdce 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_xml.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_xml.py @@ -59,11 +59,6 @@ def _create_default_type_map(): except: pass # not available on all python versions - try: - default_type_map.append((unicode, None)) # @UndefinedVariable - except: - pass # not available on all python versions - default_type_map.append((DAPGrouper, pydevd_resolver.dapGrouperResolver)) try: diff --git a/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.c b/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.c index ab5e8b06..be67d2f5 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.c +++ b/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.c @@ -1794,7 +1794,7 @@ static const char __pyx_k_pydevd_bundle_pydevd_constants[] = "_pydevd_bundle.pyd static const char __pyx_k_pydevd_frame_eval_pydevd_frame[] = "_pydevd_frame_eval.pydevd_frame_tracing"; static const char __pyx_k_If_a_code_object_is_cached_that[] = "If a code object is cached, that same code object must be reused."; static const char __pyx_k_get_abs_path_real_path_and_base[] = "get_abs_path_real_path_and_base_from_frame"; -static const char __pyx_k_pydev_imps__pydev_saved_modules[] = "_pydev_imps._pydev_saved_modules"; +static const char __pyx_k_pydev_bundle__pydev_saved_modul[] = "_pydev_bundle._pydev_saved_modules"; static const char __pyx_k_pydevd_bundle_pydevd_additional[] = "_pydevd_bundle.pydevd_additional_thread_info"; static const char __pyx_k_pydevd_bundle_pydevd_trace_disp[] = "_pydevd_bundle.pydevd_trace_dispatch"; static const char __pyx_k_pydevd_frame_eval_pydevd_modify[] = "_pydevd_frame_eval.pydevd_modify_bytecode"; @@ -1903,7 +1903,7 @@ static PyObject *__pyx_n_s_obj; static PyObject *__pyx_n_s_offset; static PyObject *__pyx_n_s_pickle; static PyObject *__pyx_n_s_plugin; -static PyObject *__pyx_n_s_pydev_imps__pydev_saved_modules; +static PyObject *__pyx_n_s_pydev_bundle__pydev_saved_modul; static PyObject *__pyx_n_s_pydev_monkey; static PyObject *__pyx_n_s_pydevd; static PyObject *__pyx_n_s_pydevd_bundle_pydevd_additional; @@ -15989,7 +15989,7 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_offset, __pyx_k_offset, sizeof(__pyx_k_offset), 0, 0, 1, 1}, {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, {&__pyx_n_s_plugin, __pyx_k_plugin, sizeof(__pyx_k_plugin), 0, 0, 1, 1}, - {&__pyx_n_s_pydev_imps__pydev_saved_modules, __pyx_k_pydev_imps__pydev_saved_modules, sizeof(__pyx_k_pydev_imps__pydev_saved_modules), 0, 0, 1, 1}, + {&__pyx_n_s_pydev_bundle__pydev_saved_modul, __pyx_k_pydev_bundle__pydev_saved_modul, sizeof(__pyx_k_pydev_bundle__pydev_saved_modul), 0, 0, 1, 1}, {&__pyx_n_s_pydev_monkey, __pyx_k_pydev_monkey, sizeof(__pyx_k_pydev_monkey), 0, 0, 1, 1}, {&__pyx_n_s_pydevd, __pyx_k_pydevd, sizeof(__pyx_k_pydevd), 0, 0, 1, 1}, {&__pyx_n_s_pydevd_bundle_pydevd_additional, __pyx_k_pydevd_bundle_pydevd_additional, sizeof(__pyx_k_pydevd_bundle_pydevd_additional), 0, 0, 1, 1}, @@ -16578,7 +16578,7 @@ if (!__Pyx_RefNanny) { /* "_pydevd_frame_eval/pydevd_frame_evaluator.pyx":2 * from __future__ import print_function - * from _pydev_imps._pydev_saved_modules import threading, thread # <<<<<<<<<<<<<< + * from _pydev_bundle._pydev_saved_modules import threading, thread # <<<<<<<<<<<<<< * from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder * import dis */ @@ -16590,7 +16590,7 @@ if (!__Pyx_RefNanny) { __Pyx_INCREF(__pyx_n_s_thread); __Pyx_GIVEREF(__pyx_n_s_thread); PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_thread); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_pydev_imps__pydev_saved_modules, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) + __pyx_t_2 = __Pyx_Import(__pyx_n_s_pydev_bundle__pydev_saved_modul, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_threading); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error) @@ -16605,7 +16605,7 @@ if (!__Pyx_RefNanny) { /* "_pydevd_frame_eval/pydevd_frame_evaluator.pyx":3 * from __future__ import print_function - * from _pydev_imps._pydev_saved_modules import threading, thread + * from _pydev_bundle._pydev_saved_modules import threading, thread * from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder # <<<<<<<<<<<<<< * import dis * import sys @@ -16625,7 +16625,7 @@ if (!__Pyx_RefNanny) { __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "_pydevd_frame_eval/pydevd_frame_evaluator.pyx":4 - * from _pydev_imps._pydev_saved_modules import threading, thread + * from _pydev_bundle._pydev_saved_modules import threading, thread * from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder * import dis # <<<<<<<<<<<<<< * import sys @@ -17063,7 +17063,7 @@ if (!__Pyx_RefNanny) { /* "_pydevd_frame_eval/pydevd_frame_evaluator.pyx":1 * from __future__ import print_function # <<<<<<<<<<<<<< - * from _pydev_imps._pydev_saved_modules import threading, thread + * from _pydev_bundle._pydev_saved_modules import threading, thread * from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder */ __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) diff --git a/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.template.pyx b/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.template.pyx index 1031e075..1bbf9f8a 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.template.pyx +++ b/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_evaluator.template.pyx @@ -1,5 +1,5 @@ from __future__ import print_function -from _pydev_imps._pydev_saved_modules import threading, thread +from _pydev_bundle._pydev_saved_modules import threading, thread from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder import dis import sys diff --git a/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_tracing.py b/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_tracing.py index 377737bf..7b34cd50 100644 --- a/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_tracing.py +++ b/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/pydevd_frame_tracing.py @@ -1,7 +1,7 @@ import sys from _pydev_bundle import pydev_log -from _pydev_imps._pydev_saved_modules import threading +from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_comm import get_global_debugger from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info diff --git a/src/debugpy/_vendored/pydevd/build_tools/build.py b/src/debugpy/_vendored/pydevd/build_tools/build.py index aeb69e6a..1d809ca1 100644 --- a/src/debugpy/_vendored/pydevd/build_tools/build.py +++ b/src/debugpy/_vendored/pydevd/build_tools/build.py @@ -151,7 +151,7 @@ def build(): additional_args.append('--force-cython') # Build always forces cython! args = [ - sys.executable, os.path.join(os.path.dirname(__file__), '..', 'setup_cython.py'), 'build_ext', '--inplace', + sys.executable, os.path.join(os.path.dirname(__file__), '..', 'setup_pydevd_cython.py'), 'build_ext', '--inplace', ] + additional_args print('Calling args: %s' % (args,)) subprocess.check_call(args, env=env,) diff --git a/src/debugpy/_vendored/pydevd/build_tools/generate_code.py b/src/debugpy/_vendored/pydevd/build_tools/generate_code.py index 44c8ead2..98842155 100644 --- a/src/debugpy/_vendored/pydevd/build_tools/generate_code.py +++ b/src/debugpy/_vendored/pydevd/build_tools/generate_code.py @@ -122,7 +122,6 @@ DONT_TRACE = { 'dis.py':LIB_FILE, # things from pydev that we don't want to trace - '_pydev_execfile.py':PYDEV_FILE, %(pydev_files)s } @@ -182,7 +181,7 @@ DONT_TRACE['codecs.py'] = LIB_FILE 'pydev_coverage.py', 'pydev_pysrc.py', 'setup.py', - 'setup_cython.py', + 'setup_pydevd_cython.py', 'interpreterInfo.py', 'conftest.py', ): diff --git a/src/debugpy/_vendored/pydevd/pycompletionserver.py b/src/debugpy/_vendored/pydevd/pycompletionserver.py index 97868bac..2fb04f8d 100644 --- a/src/debugpy/_vendored/pydevd/pycompletionserver.py +++ b/src/debugpy/_vendored/pydevd/pycompletionserver.py @@ -16,7 +16,7 @@ else: SERVER_NAME = 'pycompletionserver' from _pydev_bundle import _pydev_imports_tipper -from _pydev_imps._pydev_saved_modules import socket +from _pydev_bundle._pydev_saved_modules import socket import sys if sys.platform == "darwin": @@ -170,7 +170,7 @@ class CompletionServer: self.processor = Processor() def connect_to_server(self): - from _pydev_imps._pydev_saved_modules import socket + from _pydev_bundle._pydev_saved_modules import socket self.socket = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: diff --git a/src/debugpy/_vendored/pydevd/pydev_coverage.py b/src/debugpy/_vendored/pydevd/pydev_coverage.py index b98731cd..665e87ba 100644 --- a/src/debugpy/_vendored/pydevd/pydev_coverage.py +++ b/src/debugpy/_vendored/pydevd/pydev_coverage.py @@ -30,15 +30,12 @@ def execute(): if '--pydev-analyze' in sys.argv: - #Ok, what we want here is having the files passed through stdin (because - #there may be too many files for passing in the command line -- we could - #just pass a dir and make the find files here, but as that's already - #given in the java side, let's just gather that info here). + # Ok, what we want here is having the files passed through stdin (because + # there may be too many files for passing in the command line -- we could + # just pass a dir and make the find files here, but as that's already + # given in the java side, let's just gather that info here). sys.argv.remove('--pydev-analyze') - try: - s = raw_input() # @UndefinedVariable - except: - s = input() + s = input() s = s.replace('\r', '') s = s.replace('\n', '') @@ -53,17 +50,17 @@ def execute(): sys.stderr.write('Invalid files not passed to coverage: %s\n' % ', '.join(invalid_files)) - # Note that in this case we'll already be in the working dir with the coverage files, + # Note that in this case we'll already be in the working dir with the coverage files, # so, the coverage file location is not passed. else: - # For all commands, the coverage file is configured in pydev, and passed as the first + # For all commands, the coverage file is configured in pydev, and passed as the first # argument in the command line, so, let's make sure this gets to the coverage module. os.environ['COVERAGE_FILE'] = sys.argv[1] del sys.argv[1] try: - import coverage #@UnresolvedImport + import coverage # @UnresolvedImport except: sys.stderr.write('Error: coverage module could not be imported\n') sys.stderr.write('Please make sure that the coverage module ' @@ -77,14 +74,14 @@ def execute(): version = tuple(map(int, coverage.__version__.split('.')[:2])) if version < (4, 3): sys.stderr.write('Error: minimum supported coverage version is 4.3.' - '\nFound: %s\nLocation: %s\n' + '\nFound: %s\nLocation: %s\n' % ('.'.join(str(x) for x in version), coverage.__file__)) sys.exit(1) else: sys.stderr.write('Warning: Could not determine version of python module coverage.' '\nEnsure coverage version is >= 4.3\n') - from coverage.cmdline import main #@UnresolvedImport + from coverage.cmdline import main # @UnresolvedImport if files is not None: sys.argv.append('xml') @@ -92,5 +89,6 @@ def execute(): main() + if __name__ == '__main__': execute() diff --git a/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookglut.py b/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookglut.py index 9514b94d..d65add9b 100644 --- a/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookglut.py +++ b/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookglut.py @@ -31,7 +31,7 @@ GLUT Inputhook support functions #----------------------------------------------------------------------------- import os import sys -from _pydev_imps._pydev_saved_modules import time +from _pydev_bundle._pydev_saved_modules import time import signal import OpenGL.GLUT as glut # @UnresolvedImport import OpenGL.platform as platform # @UnresolvedImport diff --git a/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookpyglet.py b/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookpyglet.py index bf08afdc..55293079 100644 --- a/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookpyglet.py +++ b/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookpyglet.py @@ -22,7 +22,7 @@ Authors import os import sys -from _pydev_imps._pydev_saved_modules import time +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 diff --git a/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookwx.py b/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookwx.py index 75d8a62b..c2e4b91d 100644 --- a/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookwx.py +++ b/src/debugpy/_vendored/pydevd/pydev_ipython/inputhookwx.py @@ -18,7 +18,7 @@ Authors: Robin Dunn, Brian Granger, Ondrej Certik import sys import signal -from _pydev_imps._pydev_saved_modules import time +from _pydev_bundle._pydev_saved_modules import time from timeit import default_timer as clock import wx diff --git a/src/debugpy/_vendored/pydevd/pydev_run_in_console.py b/src/debugpy/_vendored/pydevd/pydev_run_in_console.py index d6b2f723..cf9aa7b1 100644 --- a/src/debugpy/_vendored/pydevd/pydev_run_in_console.py +++ b/src/debugpy/_vendored/pydevd/pydev_run_in_console.py @@ -5,7 +5,7 @@ import os import sys import traceback from pydevconsole import InterpreterInterface, process_exec_queue, start_console_server, init_mpl_in_console -from _pydev_imps._pydev_saved_modules import threading, _queue +from _pydev_bundle._pydev_saved_modules import threading, _queue from _pydev_bundle import pydev_imports from _pydevd_bundle.pydevd_utils import save_main_module diff --git a/src/debugpy/_vendored/pydevd/pydevconsole.py b/src/debugpy/_vendored/pydevd/pydevconsole.py index 5302e90b..c118b8f2 100644 --- a/src/debugpy/_vendored/pydevd/pydevconsole.py +++ b/src/debugpy/_vendored/pydevd/pydevconsole.py @@ -1,7 +1,7 @@ ''' Entry point module to start the interactive console. ''' -from _pydev_imps._pydev_saved_modules import thread, _code +from _pydev_bundle._pydev_saved_modules import thread, _code from _pydevd_bundle.pydevd_constants import IS_JYTHON start_new_thread = thread.start_new_thread @@ -16,7 +16,7 @@ InteractiveInterpreter = _code.InteractiveInterpreter import os import sys -from _pydev_imps._pydev_saved_modules import threading +from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_constants import INTERACTIVE_MODE_AVAILABLE import traceback @@ -31,8 +31,6 @@ import builtins as __builtin__ from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn # @UnusedImport from _pydev_bundle.pydev_console_utils import CodeFragment -IS_PYTHON_3_ONWARDS = sys.version_info[0] >= 3 - class Command: @@ -65,12 +63,9 @@ class Command: try: - try: - execfile # Not in Py3k - except NameError: - from _pydev_bundle.pydev_imports import execfile + from _pydev_bundle.pydev_imports import execfile - __builtin__.execfile = execfile + __builtin__.execfile = execfile except: pass diff --git a/src/debugpy/_vendored/pydevd/pydevd.py b/src/debugpy/_vendored/pydevd/pydevd.py index 45d5bf7c..63e7f81c 100644 --- a/src/debugpy/_vendored/pydevd/pydevd.py +++ b/src/debugpy/_vendored/pydevd/pydevd.py @@ -4,19 +4,17 @@ Entry point module (keep at root): This module starts the debugger. ''' import sys # @NoMove -if sys.version_info[:2] < (2, 6): - raise RuntimeError('The PyDev.Debugger requires Python 2.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.') +if sys.version_info[:2] < (3, 6): + raise RuntimeError('The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.') import os try: # Just empty packages to check if they're in the PYTHONPATH. - import _pydev_imps import _pydev_bundle except ImportError: # On the first import of a pydevd module, add pydevd itself to the PYTHONPATH # if its dependencies cannot be imported. sys.path.append(os.path.dirname(os.path.abspath(__file__))) - import _pydev_imps import _pydev_bundle # Import this first as it'll check for shadowed modules and will make sure that we import @@ -39,7 +37,7 @@ from _pydev_bundle import pydev_imports, pydev_log from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_bundle.pydev_override import overrides -from _pydev_imps._pydev_saved_modules import threading, time, thread +from _pydev_bundle._pydev_saved_modules import threading, time, thread from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path from _pydevd_bundle import pydevd_io, pydevd_vm_type @@ -70,8 +68,8 @@ from _pydevd_frame_eval.pydevd_frame_eval_main import ( frame_eval_func, dummy_trace_dispatch) import pydev_ipython # @UnusedImport from _pydevd_bundle.pydevd_source_mapping import SourceMapping -from pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time -from pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads +from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time +from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER from pydevd_file_utils import get_fullname, get_package_dir from os.path import abspath as os_path_abspath diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py index 82f8e122..2dbeafe3 100644 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py +++ b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py @@ -1,2 +1,2 @@ import add_code_to_python_process -print add_code_to_python_process.run_python_code(3736, "print(20)", connect_debugger_tracing=False) \ No newline at end of file +print(add_code_to_python_process.run_python_code(3736, "print(20)", connect_debugger_tracing=False)) diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py index f14883a2..b9d842f6 100644 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py +++ b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py @@ -74,6 +74,7 @@ readline = None #============================================================================== + class DummyEvent (NoEvent): "Dummy event object used internally by L{ConsoleDebugger}." @@ -91,6 +92,7 @@ class DummyEvent (NoEvent): #============================================================================== + class CmdError (Exception): """ Exception raised when a command parsing error occurs. @@ -99,6 +101,7 @@ class CmdError (Exception): #============================================================================== + class ConsoleDebugger (Cmd, EventHandler): """ Interactive console debugger. @@ -128,17 +131,17 @@ class ConsoleDebugger (Cmd, EventHandler): '_' # Names of the registers. - segment_names = ( 'cs', 'ds', 'es', 'fs', 'gs' ) + segment_names = ('cs', 'ds', 'es', 'fs', 'gs') - register_alias_64_to_32 = { + 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_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_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) @@ -161,8 +164,8 @@ class ConsoleDebugger (Cmd, EventHandler): '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' ) + call_instructions = ('call', 'ret', 'retn') + loop_instructions = ('loop', 'loopz', 'loopnz', 'loope', 'loopne') control_flow_instructions = call_instructions + loop_instructions + \ jump_instructions @@ -214,7 +217,7 @@ class ConsoleDebugger (Cmd, EventHandler): return None # Destroy the Debug object. - def destroy_debugger(self, autodetach = True): + def destroy_debugger(self, autodetach=True): debug = self.stop_using_debugger() if debug is not None: if not autodetach: @@ -252,7 +255,7 @@ class ConsoleDebugger (Cmd, EventHandler): 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): + 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.") @@ -262,7 +265,7 @@ class ConsoleDebugger (Cmd, EventHandler): # Token is a thread ID or name. def input_thread(self, token): - targets = self.input_thread_list( [token] ) + targets = self.input_thread_list([token]) if len(targets) == 0: raise CmdError("missing thread name or ID") if len(targets) > 1: @@ -276,7 +279,7 @@ class ConsoleDebugger (Cmd, EventHandler): # Token list is a list of thread IDs or names. def input_thread_list(self, token_list): targets = set() - system = self.debug.system + system = self.debug.system for token in token_list: try: tid = self.input_integer(token) @@ -286,18 +289,18 @@ class ConsoleDebugger (Cmd, EventHandler): except ValueError: found = set() for process in system.iter_processes(): - found.update( system.find_threads_by_name(token) ) + 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.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] ) + targets = self.input_process_list([token]) if len(targets) == 0: raise CmdError("missing process name or ID") if len(targets) > 1: @@ -311,7 +314,7 @@ class ConsoleDebugger (Cmd, EventHandler): # Token list is a list of process IDs or names. def input_process_list(self, token_list): targets = set() - system = self.debug.system + system = self.debug.system for token in token_list: try: pid = self.input_integer(token) @@ -323,14 +326,14 @@ class ConsoleDebugger (Cmd, EventHandler): if not found: raise CmdError("process not found (%s)" % token) for (process, _) in found: - targets.add( process.get_pid() ) + 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) + argv = self.debug.system.cmdline_to_argv(command_line) if not argv: raise CmdError("missing command line to execute") fname = argv[0] @@ -352,11 +355,11 @@ class ConsoleDebugger (Cmd, EventHandler): # It can be in any supported format. def input_integer(self, token): return HexInput.integer(token) -## input_integer = input_hexadecimal_integer +# # 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): + def input_address(self, token, pid=None, tid=None): address = None if self.is_register(token): if tid is None: @@ -388,7 +391,7 @@ class ConsoleDebugger (Cmd, EventHandler): # 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): + 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) @@ -404,10 +407,10 @@ class ConsoleDebugger (Cmd, EventHandler): 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 + size = self.input_address(token_2, pid, tid) - address else: address = self.input_address(token, pid, tid) - size = None + size = None return address, size # XXX TODO @@ -431,7 +434,7 @@ class ConsoleDebugger (Cmd, EventHandler): # The token is a register name. # Returns None if no register name is matched. - def input_register(self, token, tid = None): + def input_register(self, token, tid=None): if tid is None: if self.lastEvent is None: raise CmdError("no current process set") @@ -444,45 +447,45 @@ class ConsoleDebugger (Cmd, EventHandler): title = token.title() if title in ctx: - return ctx.get(title) # eax -> Eax + return ctx.get(title) # eax -> Eax if ctx.arch == 'i386': if token in self.segment_names: - return ctx.get( 'Seg%s' % title ) # cs -> SegCs + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 (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() + 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 @@ -495,7 +498,7 @@ class ConsoleDebugger (Cmd, EventHandler): # 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): + 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 @@ -508,7 +511,7 @@ class ConsoleDebugger (Cmd, EventHandler): # Tell the user a module was loaded. def print_module_load(self, event): - mod = event.get_module() + mod = event.get_module() base = mod.get_base() name = mod.get_filename() if not name: @@ -519,7 +522,7 @@ class ConsoleDebugger (Cmd, EventHandler): # Tell the user a module was unloaded. def print_module_unload(self, event): - mod = event.get_module() + mod = event.get_module() base = mod.get_base() name = mod.get_filename() if not name: @@ -530,7 +533,7 @@ class ConsoleDebugger (Cmd, EventHandler): # Tell the user a process was started. def print_process_start(self, event): - pid = event.get_pid() + pid = event.get_pid() start = event.get_start_address() if start: start = HexOutput.address(start) @@ -540,7 +543,7 @@ class ConsoleDebugger (Cmd, EventHandler): # Tell the user a thread was started. def print_thread_start(self, event): - tid = event.get_tid() + tid = event.get_tid() start = event.get_start_address() if start: with warnings.catch_warnings(): @@ -552,25 +555,25 @@ class ConsoleDebugger (Cmd, EventHandler): # Tell the user a process has finished. def print_process_end(self, event): - pid = event.get_pid() + 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() + 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() + 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() ) + code = HexDump.integer(event.get_event_code()) name = event.get_event_name() desc = event.get_event_description() if code in desc: @@ -583,9 +586,9 @@ class ConsoleDebugger (Cmd, EventHandler): # 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() + 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: @@ -601,18 +604,18 @@ class ConsoleDebugger (Cmd, EventHandler): # Show the current location in the code. def print_event_location(self, event): process = event.get_process() - thread = event.get_thread() + 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() + 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): + 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") @@ -620,7 +623,7 @@ class ConsoleDebugger (Cmd, EventHandler): if not thread: if self.lastEvent is None: raise CmdError("no current process set") - thread = self.lastEvent.get_thread() + thread = self.lastEvent.get_thread() thread.suspend() try: if pc is None: @@ -639,7 +642,7 @@ class ConsoleDebugger (Cmd, EventHandler): print(CrashDump.dump_registers(ctx),) print("%s:" % label) if disasm: - print(CrashDump.dump_code_line(disasm[0], pc, bShowDump = True)) + print(CrashDump.dump_code_line(disasm[0], pc, bShowDump=True)) else: try: data = process.peek(pc, 15) @@ -654,10 +657,10 @@ class ConsoleDebugger (Cmd, EventHandler): def print_memory_display(self, arg, method): if not arg: arg = self.default_display_target - token_list = self.split_tokens(arg, 1, 2) + 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) + 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),) @@ -718,12 +721,12 @@ class ConsoleDebugger (Cmd, EventHandler): # 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) + process = self.get_process(pid) + thread = self.get_thread(tid) return process, thread # Get the process object. - def get_process(self, pid = None): + def get_process(self, pid=None): if pid is None: if self.lastEvent is None: raise CmdError("no current process set") @@ -738,7 +741,7 @@ class ConsoleDebugger (Cmd, EventHandler): return process # Get the thread object. - def get_thread(self, tid = None): + def get_thread(self, tid=None): if tid is None: if self.lastEvent is None: raise CmdError("no current process set") @@ -753,7 +756,7 @@ class ConsoleDebugger (Cmd, EventHandler): return thread # Read the process memory. - def read_memory(self, address, size, pid = None): + def read_memory(self, address, size, pid=None): process = self.get_process(pid) try: data = process.peek(address, size) @@ -766,7 +769,7 @@ class ConsoleDebugger (Cmd, EventHandler): return data # Write the process memory. - def write_memory(self, address, data, pid = None): + def write_memory(self, address, data, pid=None): process = self.get_process(pid) try: process.write(address, data) @@ -779,7 +782,7 @@ class ConsoleDebugger (Cmd, EventHandler): raise CmdError(msg) # Change a register value. - def change_register(self, register, value, tid = None): + def change_register(self, register, value, tid=None): # Get the thread. if tid is None: @@ -796,7 +799,7 @@ class ConsoleDebugger (Cmd, EventHandler): try: value = self.input_integer(value) except ValueError: - pid = thread.get_pid() + pid = thread.get_pid() value = self.input_address(value, pid, tid) # Suspend the thread. @@ -812,30 +815,30 @@ class ConsoleDebugger (Cmd, EventHandler): # Integer 32 bits registers. if register in self.register_names: - register = register.title() # eax -> Eax + 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 + 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 + 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 + 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 + value = ((value & 0x000000FF) << 8) | previous # Set the new context. ctx.__setitem__(register, value) @@ -852,7 +855,7 @@ class ConsoleDebugger (Cmd, EventHandler): if mbi.State != win32.MEM_COMMIT or mbi.Protect & win32.PAGE_GUARD: continue address = mbi.BaseAddress - size = mbi.RegionSize + size = mbi.RegionSize try: data = process.read(address, size) except WindowsError: @@ -863,8 +866,8 @@ class ConsoleDebugger (Cmd, EventHandler): p = data.find(query) while p >= 0: q = p + len(query) - d = data[ p : min(q, p + width) ] - h = HexDump.hexline(d, width = width) + 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) @@ -907,10 +910,10 @@ class ConsoleDebugger (Cmd, EventHandler): print("*** Error: %s" % str(e)) except Exception: traceback.print_exc() -## self.debuggerExit = True +# # self.debuggerExit = True # Prompt the user for a YES/NO kind of question. - def ask_user(self, msg, prompt = "Are you sure? (y/N): "): + def ask_user(self, msg, prompt="Are you sure? (y/N): "): print(msg) answer = raw_input(prompt) answer = answer.strip()[:1].lower() @@ -937,8 +940,8 @@ class ConsoleDebugger (Cmd, EventHandler): try: doc = getattr(self, name).__doc__.split('\n') except Exception: - return ( "No help available when Python" - " is run with the -OO switch." ) + return ("No help available when Python" + " is run with the -OO switch.") for x in doc: x = x.strip() if x: @@ -952,12 +955,12 @@ class ConsoleDebugger (Cmd, EventHandler): def split_prefix(self, line): prefix = None if line.startswith('~'): - pos = line.find(' ') + pos = line.find(' ') if pos == 1: - pos = line.find(' ', pos + 1) + pos = line.find(' ', pos + 1) if not pos < 0: - prefix = line[ 1 : pos ].strip() - line = line[ pos : ].strip() + prefix = line[ 1: pos ].strip() + line = line[ pos: ].strip() return prefix, line #------------------------------------------------------------------------------ @@ -966,9 +969,9 @@ class ConsoleDebugger (Cmd, EventHandler): # Header for help page. doc_header = 'Available commands (type help * or help )' -## # Read and write directly to stdin and stdout. -## # This prevents the use of raw_input and print. -## use_rawinput = False +# # # Read and write directly to stdin and stdout. +# # # This prevents the use of raw_input and print. +# # use_rawinput = False @property def prompt(self): @@ -976,7 +979,7 @@ class ConsoleDebugger (Cmd, EventHandler): pid = self.lastEvent.get_pid() tid = self.lastEvent.get_tid() if self.debug.is_debugee(pid): -## return '~%d(%d)> ' % (tid, pid) +# # return '~%d(%d)> ' % (tid, pid) return '%d:%d> ' % (pid, tid) return '> ' @@ -1004,23 +1007,25 @@ class ConsoleDebugger (Cmd, EventHandler): cmd = self.autocomplete(cmd) return cmd, arg, line -## # Don't repeat the last executed command. -## def emptyline(self): -## pass +# # # 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_disasm_target = 'eip' self.default_display_target = 'eip' - self.last_display_command = self.do_db + 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. @@ -1066,7 +1071,7 @@ class ConsoleDebugger (Cmd, EventHandler): x = x.strip() if x: for n in self.completenames(x): - commands.add( 'do_%s' % n ) + commands.add('do_%s' % n) commands = list(commands) commands.sort() print(self.get_help(commands)) @@ -1093,16 +1098,19 @@ class ConsoleDebugger (Cmd, EventHandler): arg = '%s /c %s' % (shell, arg) else: arg = shell - process = self.debug.system.start_process(arg, bConsole = True) + 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 @@ -1117,12 +1125,12 @@ class ConsoleDebugger (Cmd, EventHandler): local = {} local.update(__builtins__) local.update({ - '__name__' : '__console__', - '__doc__' : None, - 'exit' : self._python_exit, - 'self' : self, - 'arg' : arg, - 'winappdbg' : winappdbg, + '__name__': '__console__', + '__doc__': None, + 'exit': self._python_exit, + 'self': self, + 'arg': arg, + 'winappdbg': winappdbg, }) try: code.interact(banner=banner, local=local) @@ -1156,53 +1164,6 @@ class ConsoleDebugger (Cmd, EventHandler): raise CmdError( "unhandled exception when running Python console: %s" % e) - # The plugins interface is quite simple. - # - # Just place a .py file with the plugin name in the "plugins" folder, - # for example "do_example.py" would implement the "example" command. - # - # The plugin must have a function named "do", which implements the - # command functionality exactly like the do_* methods of Cmd instances. - # - # The docstring for the "do" function will be parsed exactly like - # one of the debugger's commands - that is, each line is treated - # independently. - # - def do_plugin(self, arg): - """ - [~prefix] . [arguments] - run a plugin command - [~prefix] plugin [arguments] - run a plugin command - """ - pos = arg.find(' ') - if pos < 0: - name = arg - arg = '' - else: - name = arg[:pos] - arg = arg[pos:].strip() - if not name: - raise CmdError("missing plugin name") - for c in name: - if c not in self.valid_plugin_name_chars: - raise CmdError("invalid plugin name: %r" % name) - name = 'winappdbg.plugins.do_%s' % name - try: - plugin = __import__(name) - components = name.split('.') - for comp in components[1:]: - plugin = getattr(plugin, comp) - reload(plugin) - except ImportError: - raise CmdError("plugin not found: %s" % name) - try: - return plugin.do(self, arg) - except CmdError: - raise - except Exception: - e = sys.exc_info()[1] -## traceback.print_exc(e) # XXX DEBUG - raise CmdError("unhandled exception in plugin: %s" % e) - def do_quit(self, arg): """ quit - close the debugging session @@ -1232,7 +1193,7 @@ class ConsoleDebugger (Cmd, EventHandler): """ if self.cmdprefix: raise CmdError("prefix not allowed") - targets = self.input_process_list( self.split_tokens(arg, 1) ) + targets = self.input_process_list(self.split_tokens(arg, 1)) if not targets: print("Error: missing parameters") else: @@ -1250,7 +1211,7 @@ class ConsoleDebugger (Cmd, EventHandler): detach - detach from the current process detach [target...] - detach from the given process(es) """ - debug = self.debug + debug = self.debug token_list = self.split_tokens(arg) if self.cmdprefix: token_list.insert(0, self.cmdprefix) @@ -1275,8 +1236,8 @@ class ConsoleDebugger (Cmd, EventHandler): cmdline = self.input_command_line(arg) try: process = self.debug.execl(arg, - bConsole = False, - bFollow = self.options.follow) + bConsole=False, + bFollow=self.options.follow) print("Spawned process (%d)" % process.get_pid()) except Exception: raise CmdError("can't execute") @@ -1291,8 +1252,8 @@ class ConsoleDebugger (Cmd, EventHandler): cmdline = self.input_command_line(arg) try: process = self.debug.execl(arg, - bConsole = True, - bFollow = self.options.follow) + bConsole=True, + bFollow=self.options.follow) print("Spawned process (%d)" % process.get_pid()) except Exception: raise CmdError("can't execute") @@ -1311,7 +1272,7 @@ class ConsoleDebugger (Cmd, EventHandler): if self.debug.get_debugee_count() > 0: return True - do_g = do_continue + do_g = do_continue do_go = do_continue def do_gh(self, arg): @@ -1360,7 +1321,7 @@ class ConsoleDebugger (Cmd, EventHandler): raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") - system = self.debug.system + system = self.debug.system pid_list = self.debug.get_debugee_pids() if pid_list: print("Process ID File name") @@ -1386,18 +1347,18 @@ class ConsoleDebugger (Cmd, EventHandler): if self.cmdprefix: process = self.get_process_from_prefix() for thread in process.iter_threads(): - tid = thread.get_tid() + tid = thread.get_tid() name = thread.get_name() print("%-12d %s" % (tid, name)) else: - system = self.debug.system + 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() + tid = thread.get_tid() name = thread.get_name() print("%-12d %s" % (tid, name)) @@ -1440,7 +1401,7 @@ class ConsoleDebugger (Cmd, EventHandler): 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) ) + msg = msg % (len(target_pids), len(target_tids)) if self.ask_user(msg): for pid in target_pids: self.kill_process(pid) @@ -1476,7 +1437,7 @@ class ConsoleDebugger (Cmd, EventHandler): [~process] modload - load a DLL module """ filename = self.split_tokens(arg, 1, 1)[0] - process = self.get_process_from_prefix() + process = self.get_process_from_prefix() try: process.inject_dll(filename, bWait=False) except RuntimeError: @@ -1489,11 +1450,11 @@ class ConsoleDebugger (Cmd, EventHandler): [~thread] k - show the stack trace [~thread] stack - show the stack trace """ - if arg: # XXX TODO add depth parameter + 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) + 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: @@ -1510,9 +1471,9 @@ class ConsoleDebugger (Cmd, EventHandler): break - force a debug break in all debugees break [process...] - force a debug break """ - debug = self.debug - system = debug.system - targets = self.input_process_list( self.split_tokens(arg) ) + 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() @@ -1538,20 +1499,20 @@ class ConsoleDebugger (Cmd, EventHandler): 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 + 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() + 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(' ') ] + 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 +# # print(hex(pc), hex(address), size # XXX DEBUG self.debug.stalk_at(pid, address) return True @@ -1563,7 +1524,7 @@ class ConsoleDebugger (Cmd, EventHandler): t - trace at the current assembly instruction trace - trace at the current assembly instruction """ - if arg: # XXX this check is to be removed + 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") @@ -1579,8 +1540,8 @@ class ConsoleDebugger (Cmd, EventHandler): 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) + process = self.get_process(pid) + token_list = self.split_tokens(arg, 1, 1) try: address = self.input_address(token_list[0], pid) deferred = False @@ -1600,16 +1561,16 @@ class ConsoleDebugger (Cmd, EventHandler): """ [~thread] ba <1|2|4|8>
- set hardware breakpoint """ - debug = self.debug - thread = self.get_thread_from_prefix() - pid = thread.get_pid() - tid = thread.get_tid() + 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] + 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': @@ -1628,9 +1589,9 @@ class ConsoleDebugger (Cmd, EventHandler): 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() + 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) @@ -1646,8 +1607,8 @@ class ConsoleDebugger (Cmd, EventHandler): 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) + 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) @@ -1664,7 +1625,7 @@ class ConsoleDebugger (Cmd, EventHandler): raise CmdError("prefix not supported") breakpoints = debug.get_debugee_pids() else: - targets = self.input_process_list( self.split_tokens(arg) ) + targets = self.input_process_list(self.split_tokens(arg)) if self.cmdprefix: targets.insert(0, self.input_process(self.cmdprefix)) if not targets: @@ -1679,7 +1640,7 @@ class ConsoleDebugger (Cmd, EventHandler): print("Process %d:" % pid) printed_process_banner = True for bp in bplist: - address = repr(bp)[1:-1].replace('remote address ','') + address = repr(bp)[1:-1].replace('remote address ', '') print(" %s" % address) dbplist = debug.get_process_deferred_code_breakpoints(pid) if dbplist: @@ -1701,14 +1662,14 @@ class ConsoleDebugger (Cmd, EventHandler): print("Process %d:" % pid) printed_process_banner = True for bp in bplist: - address = repr(bp)[1:-1].replace('remote address ','') + 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 ','') + address = repr(bp)[1:-1].replace('remote address ', '') print(" %s" % address) def do_bo(self, arg): @@ -1828,26 +1789,26 @@ class ConsoleDebugger (Cmd, EventHandler): """ 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) + 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] + 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] + 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)) +# # print(CrashDump.dump_code(code)) for line in code: - print(CrashDump.dump_code_line(line, bShowDump = False)) + print(CrashDump.dump_code_line(line, bShowDump=False)) do_u = do_disassemble @@ -1857,8 +1818,8 @@ class ConsoleDebugger (Cmd, EventHandler): [~process] search [address-address] """ token_list = self.split_tokens(arg, 1, 3) - pid, tid = self.get_process_and_thread_ids_from_prefix() - process = self.get_process(pid) + 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 @@ -1885,8 +1846,8 @@ class ConsoleDebugger (Cmd, EventHandler): [~process] searchhex [address-address] """ token_list = self.split_tokens(arg, 1, 3) - pid, tid = self.get_process_and_thread_ids_from_prefix() - process = self.get_process(pid) + 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 @@ -1906,16 +1867,16 @@ class ConsoleDebugger (Cmd, EventHandler): 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_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): """ @@ -1986,10 +1947,10 @@ class ConsoleDebugger (Cmd, EventHandler): """ if not arg: arg = self.default_display_target - token_list = self.split_tokens(arg, 1, 1) + 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) + process = self.get_process(pid) + data = process.peek_string(address, False, size) if data: print(repr(data)) self.last_display_command = self.do_ds @@ -2001,10 +1962,10 @@ class ConsoleDebugger (Cmd, EventHandler): """ if not arg: arg = self.default_display_target - token_list = self.split_tokens(arg, 1, 2) + 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) + process = self.get_process(pid) + data = process.peek_string(address, True, size) if data: print(repr(data)) self.last_display_command = self.do_du @@ -2025,7 +1986,7 @@ class ConsoleDebugger (Cmd, EventHandler): equ = arg.find('=') if equ >= 0: register = arg[:equ].strip() - value = arg[equ+1:].strip() + value = arg[equ + 1:].strip() if not value: value = '0' self.change_register(register, value) @@ -2034,10 +1995,10 @@ class ConsoleDebugger (Cmd, EventHandler): if value is None: raise CmdError("unknown register: %s" % arg) try: - label = None - thread = self.get_thread_from_prefix() + label = None + thread = self.get_thread_from_prefix() process = thread.get_process() - module = process.get_module_at_address(value) + module = process.get_module_at_address(value) if module: label = module.get_label_at_address(value) except RuntimeError: @@ -2057,10 +2018,10 @@ class ConsoleDebugger (Cmd, EventHandler): """ # TODO # data parameter should be optional, use a child Cmd here - pid = self.get_process_id_from_prefix() + 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:])) + address = self.input_address(token_list[0], pid) + data = HexInput.hexadecimal(' '.join(token_list[1:])) self.write_memory(address, data, pid) # XXX TODO @@ -2083,11 +2044,11 @@ class ConsoleDebugger (Cmd, EventHandler): [~process] m - show the process memory map [~process] memory - show the process memory map """ - if arg: # TODO: take min and max addresses + 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() + memoryMap = process.get_memory_map() mappedFilenames = process.get_mapped_filenames() print('') print(CrashDump.dump_memory_map(memoryMap, mappedFilenames)) @@ -2278,4 +2239,4 @@ class ConsoleDebugger (Cmd, EventHandler): except: traceback.print_exc() if not success: - raise # This should never happen! + raise # This should never happen! diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/README b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/README deleted file mode 100644 index 9d0fea9f..00000000 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/README +++ /dev/null @@ -1 +0,0 @@ -Here go the plugins for the interactive debugger. \ No newline at end of file diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/__init__.py b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/__init__.py deleted file mode 100644 index 3836e09d..00000000 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python -# -*- 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. - -""" -Plugins folder for the WinAppDbg interactive debugger. -""" - -__revision__ = "$Id: __init__.py 1125 2012-10-22 14:54:39Z qvasimodo $" diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_example.py b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_example.py deleted file mode 100644 index 591ce68b..00000000 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_example.py +++ /dev/null @@ -1,41 +0,0 @@ -#!~/.wine/drive_c/Python25/python.exe -# -*- coding: utf-8 -*- - -# Command line debugger using WinAppDbg -# Example command -# 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. - -__revision__ = "$Id$" - -def do(self, arg): - ".example - This is an example plugin for the command line debugger" - print "This is an example command." - print "%s.do(%r, %r):" % (__name__, self, arg) - print " last event", self.lastEvent - print " prefix", self.cmdprefix - print " arguments", self.split_tokens(arg) diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exchain.py b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exchain.py deleted file mode 100644 index aa97fec7..00000000 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exchain.py +++ /dev/null @@ -1,51 +0,0 @@ -#!~/.wine/drive_c/Python25/python.exe -# -*- coding: utf-8 -*- - -# Command line debugger using WinAppDbg -# Show exception handlers list -# 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. - -__revision__ = "$Id$" - -from winappdbg import HexDump, Table - -def do(self, arg): - ".exchain - Show the SEH chain" - thread = self.get_thread_from_prefix() - print "Exception handlers for thread %d" % thread.get_tid() - print - table = Table() - table.addRow("Block", "Function") - bits = thread.get_bits() - for (seh, seh_func) in thread.get_seh_chain(): - if seh is not None: - seh = HexDump.address(seh, bits) - if seh_func is not None: - seh_func = HexDump.address(seh_func, bits) - table.addRow(seh, seh_func) - print table.getOutput() diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exploitable.py b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exploitable.py deleted file mode 100644 index 64e93f6f..00000000 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_exploitable.py +++ /dev/null @@ -1,50 +0,0 @@ -#!~/.wine/drive_c/Python25/python.exe -# -*- coding: utf-8 -*- - -# Command line debugger using WinAppDbg -# Determine the approximate exploitability rating -# 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. - -__revision__ = "$Id$" - -def do(self, arg): - ".exploitable - Determine the approximate exploitability rating" - - from winappdbg import Crash - - event = self.debug.lastEvent - crash = Crash(event) - crash.fetch_extra_data(event) - - status, rule, description = crash.isExploitable() - - print "-" * 79 - print "Exploitability: %s" % status - print "Matched rule: %s" % rule - print "Description: %s" % description - print "-" * 79 diff --git a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_symfix.py b/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_symfix.py deleted file mode 100644 index cccfbe96..00000000 --- a/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/plugins/do_symfix.py +++ /dev/null @@ -1,37 +0,0 @@ -#!~/.wine/drive_c/Python25/python.exe -# -*- coding: utf-8 -*- - -# Command line debugger using WinAppDbg -# Fix the symbol store path -# 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. - -__revision__ = "$Id$" - -def do(self, arg): - ".symfix - Set the default Microsoft Symbol Store settings if missing" - self.debug.system.fix_symbol_store_path(remote = True, force = False) diff --git a/src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/__init__.py b/src/debugpy/_vendored/pydevd/pydevd_concurrency_analyser/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/debugpy/_vendored/pydevd/pydevd_tracing.py b/src/debugpy/_vendored/pydevd/pydevd_tracing.py index 5ed7b0ce..561d7f71 100644 --- a/src/debugpy/_vendored/pydevd/pydevd_tracing.py +++ b/src/debugpy/_vendored/pydevd/pydevd_tracing.py @@ -1,15 +1,11 @@ from _pydevd_bundle.pydevd_constants import get_frame, IS_CPYTHON, IS_64BIT_PROCESS, IS_WINDOWS, \ IS_LINUX, IS_MAC, DebugInfoHolder, LOAD_NATIVE_LIB_FLAG, \ ENV_FALSE_LOWER_VALUES, ForkSafeLock -from _pydev_imps._pydev_saved_modules import thread, threading +from _pydev_bundle._pydev_saved_modules import thread, threading from _pydev_bundle import pydev_log, pydev_monkey import os.path import platform -try: - import ctypes -except ImportError: - ctypes = None - +import ctypes from io import StringIO import sys import traceback @@ -244,7 +240,7 @@ def get_python_helper_lib_filename(): def _load_python_helper_lib_uncached(): - if (not IS_CPYTHON or ctypes is None or sys.version_info[:2] > (3, 10) + if (not IS_CPYTHON or sys.version_info[:2] > (3, 10) or hasattr(sys, 'gettotalrefcount') or LOAD_NATIVE_LIB_FLAG in ENV_FALSE_LOWER_VALUES): pydev_log.info('Helper lib to set tracing to all threads not loaded.') return None diff --git a/src/debugpy/_vendored/pydevd/runfiles.py b/src/debugpy/_vendored/pydevd/runfiles.py index b3ecdf92..15b9f3aa 100644 --- a/src/debugpy/_vendored/pydevd/runfiles.py +++ b/src/debugpy/_vendored/pydevd/runfiles.py @@ -6,11 +6,6 @@ Used to run with tests with unittest/pytest/nose. import os -try: - xrange -except: - xrange = range - def main(): import sys @@ -215,7 +210,7 @@ def main(): break remove = [] - for i in xrange(len(argv)): + for i in range(len(argv)): arg = argv[i] # Workaround bug in py.test: if we pass the full path it ends up importing conftest # more than once (so, always work with relative paths). diff --git a/src/debugpy/_vendored/pydevd/setup.py b/src/debugpy/_vendored/pydevd/setup.py index a0efc6c4..26aeb134 100644 --- a/src/debugpy/_vendored/pydevd/setup.py +++ b/src/debugpy/_vendored/pydevd/setup.py @@ -63,10 +63,10 @@ args = dict( packages=[ '_pydev_bundle', '_pydev_bundle.fsnotify', - '_pydev_imps', '_pydev_runfiles', '_pydevd_bundle', '_pydevd_bundle._debug_adapter', + '_pydevd_bundle.pydevd_concurrency_analyser', '_pydevd_frame_eval', '_pydevd_frame_eval.vendored', '_pydevd_frame_eval.vendored.bytecode', @@ -76,7 +76,6 @@ args = dict( 'pydevd_attach_to_process', - 'pydevd_concurrency_analyser', 'pydevd_plugins', 'pydevd_plugins.extensions', 'pydevd_plugins.extensions.types', @@ -93,7 +92,7 @@ args = dict( 'pydevd', 'pydevd_tracing', # 'runfiles', -- Not needed for debugger - 'setup_cython', # Distributed to clients. See: https://github.com/fabioz/PyDev.Debugger/issues/102 + 'setup_pydevd_cython', # Distributed to clients. See: https://github.com/fabioz/PyDev.Debugger/issues/102 # 'setup', -- Should not be included as a module ], classifiers=[ @@ -170,7 +169,7 @@ try: Extension( '_pydevd_bundle.pydevd_cython', ["_pydevd_bundle/pydevd_cython.c", ], - define_macros = [('Py_BUILD_CORE_MODULE', '1')], + define_macros=[('Py_BUILD_CORE_MODULE', '1')], **kwargs ) ] diff --git a/src/debugpy/_vendored/pydevd/setup_cython.py b/src/debugpy/_vendored/pydevd/setup_pydevd_cython.py similarity index 99% rename from src/debugpy/_vendored/pydevd/setup_cython.py rename to src/debugpy/_vendored/pydevd/setup_pydevd_cython.py index 85a4aa80..ffc1003f 100644 --- a/src/debugpy/_vendored/pydevd/setup_cython.py +++ b/src/debugpy/_vendored/pydevd/setup_pydevd_cython.py @@ -3,7 +3,7 @@ A simpler setup version just to compile the speedup module. It should be used as: -python setup_cython build_ext --inplace +python setup_pydevd_cython build_ext --inplace Note: the .c file and other generated files are regenerated from the .pyx file by running "python build_tools/build.py" diff --git a/src/debugpy/_vendored/pydevd/tests/test_get_referrers.py b/src/debugpy/_vendored/pydevd/tests/test_get_referrers.py index c1b49dbb..c4f7c149 100644 --- a/src/debugpy/_vendored/pydevd/tests/test_get_referrers.py +++ b/src/debugpy/_vendored/pydevd/tests/test_get_referrers.py @@ -4,7 +4,7 @@ import time import unittest import pytest from _pydevd_bundle import pydevd_referrers -from _pydev_bundle.pydev_imports import StringIO +from io import StringIO from tests_python.debugger_unittest import IS_PYPY try: diff --git a/src/debugpy/_vendored/pydevd/tests/test_pydev_ipython_011.py b/src/debugpy/_vendored/pydevd/tests/test_pydev_ipython_011.py index 40c51eab..030dc4a9 100644 --- a/src/debugpy/_vendored/pydevd/tests/test_pydev_ipython_011.py +++ b/src/debugpy/_vendored/pydevd/tests/test_pydev_ipython_011.py @@ -10,25 +10,22 @@ import time from _pydevd_bundle import pydevd_io import pytest -try: - xrange -except: - xrange = range def eq_(a, b): if a != b: raise AssertionError('%s != %s' % (a, b)) - + + try: from IPython import core has_ipython = True except: has_ipython = False + @pytest.mark.skipif(not has_ipython, reason='IPython not available') class TestBase(unittest.TestCase): - def setUp(self): from _pydev_bundle.pydev_ipython_console_011 import get_pydev_frontend @@ -65,32 +62,27 @@ class TestPyDevFrontEnd(TestBase): def testAddExec_1(self): self.add_exec('if True:', True) - def testAddExec_2(self): - #Change: 'more' must now be controlled in the client side after the initial 'True' returned. + # Change: 'more' must now be controlled in the client side after the initial 'True' returned. self.add_exec('if True:\n testAddExec_a = 10\n', False) assert 'testAddExec_a' in self.front_end.get_namespace() - def testAddExec_3(self): assert 'testAddExec_x' not in self.front_end.get_namespace() self.add_exec('if True:\n testAddExec_x = 10\n\n') assert 'testAddExec_x' in self.front_end.get_namespace() eq_(self.front_end.get_namespace()['testAddExec_x'], 10) - def test_get_namespace(self): assert 'testGetNamespace_a' not in self.front_end.get_namespace() self.add_exec('testGetNamespace_a = 10') assert 'testGetNamespace_a' in self.front_end.get_namespace() eq_(self.front_end.get_namespace()['testGetNamespace_a'], 10) - def test_complete(self): unused_text, matches = self.front_end.complete('%') assert len(matches) > 1, 'at least one magic should appear in completions' - def test_complete_does_not_do_python_matches(self): # Test that IPython's completions do not do the things that # PyDev's completions will handle @@ -100,7 +92,6 @@ class TestPyDevFrontEnd(TestBase): unused_text, matches = self.front_end.complete('testComplete_') assert len(matches) == 0 - def testGetCompletions_1(self): # Test the merged completions include the standard completions self.add_exec('testComplete_a = 5') @@ -111,7 +102,6 @@ class TestPyDevFrontEnd(TestBase): assert len(matches) == 3 eq_(set(['testComplete_a', 'testComplete_b', 'testComplete_c']), set(matches)) - def testGetCompletions_2(self): # Test that we get IPython completions in results # we do this by checking kw completion which PyDev does @@ -121,7 +111,6 @@ class TestPyDevFrontEnd(TestBase): matches = [f[0] for f in res] assert 'ABC=' in matches - def testGetCompletions_3(self): # Test that magics return IPYTHON magic as type res = self.front_end.getCompletions('%cd', '%cd') @@ -129,9 +118,10 @@ class TestPyDevFrontEnd(TestBase): eq_(res[0][3], '12') # '12' == IToken.TYPE_IPYTHON_MAGIC assert len(res[0][1]) > 100, 'docstring for %cd should be a reasonably long string' + @pytest.mark.skipif(not has_ipython, reason='IPython not available') class TestRunningCode(TestBase): - + def test_print(self): self.redirect_stdout() try: @@ -140,7 +130,6 @@ class TestRunningCode(TestBase): finally: self.restore_stdout() - def testQuestionMark_1(self): self.redirect_stdout() try: @@ -151,7 +140,6 @@ class TestRunningCode(TestBase): finally: self.restore_stdout() - def testQuestionMark_2(self): self.redirect_stdout() try: @@ -162,8 +150,6 @@ class TestRunningCode(TestBase): finally: self.restore_stdout() - - def test_gui(self): try: import Tkinter @@ -179,7 +165,6 @@ class TestRunningCode(TestBase): self.add_exec('%gui none') assert get_inputhook() is None - def test_history(self): ''' Make sure commands are added to IPython's history ''' self.redirect_stdout() @@ -199,7 +184,6 @@ class TestRunningCode(TestBase): finally: self.restore_stdout() - def test_edit(self): ''' Make sure we can issue an edit command''' if os.environ.get('TRAVIS') == 'true': @@ -210,16 +194,23 @@ class TestRunningCode(TestBase): called_RequestInput = [False] called_IPythonEditor = [False] + def start_client_thread(client_port): + class ClientThread(threading.Thread): + def __init__(self, client_port): threading.Thread.__init__(self) self.client_port = client_port + def run(self): + class HandleRequestInput: + def RequestInput(self): called_RequestInput[0] = True return '\n' + def IPythonEditor(self, name, line): called_IPythonEditor[0] = (name, line) return True @@ -258,7 +249,7 @@ class TestRunningCode(TestBase): filename = 'made_up_file.py' self.add_exec('%edit ' + filename) - for i in xrange(10): + for i in range(10): if called_IPythonEditor[0] == (os.path.abspath(filename), '0'): break time.sleep(.1) diff --git a/src/debugpy/_vendored/pydevd/tests/test_pyserver.py b/src/debugpy/_vendored/pydevd/tests/test_pyserver.py index 011ae6e5..c71b5fd0 100644 --- a/src/debugpy/_vendored/pydevd/tests/test_pyserver.py +++ b/src/debugpy/_vendored/pydevd/tests/test_pyserver.py @@ -1,40 +1,21 @@ -''' -@author Fabio Zadrozny -''' import sys -import pytest -from _pydev_imps._pydev_saved_modules import thread +from _pydev_bundle._pydev_saved_modules import thread +import pycompletionserver +import socket +from urllib.parse import quote_plus start_new_thread = thread.start_new_thread -IS_PYTHON_3_ONWARDS = sys.version_info[0] >= 3 -IS_JYTHON = sys.platform.find('java') != -1 +BUILTIN_MOD = 'builtins' -try: - import __builtin__ # @UnusedImport - BUILTIN_MOD = '__builtin__' -except ImportError: - BUILTIN_MOD = 'builtins' -if not IS_JYTHON: - import pycompletionserver - import socket - if not IS_PYTHON_3_ONWARDS: - from urllib import quote_plus, unquote_plus +def send(s, msg): + s.send(bytearray(msg, 'utf-8')) - def send(s, msg): - s.send(msg) - - else: - from urllib.parse import quote_plus, unquote_plus # Python 3.0 - - def send(s, msg): - s.send(bytearray(msg, 'utf-8')) import unittest -@pytest.mark.skipif(IS_JYTHON, reason='Not applicable to Jython') class TestCPython(unittest.TestCase): def test_message(self): @@ -77,8 +58,7 @@ class TestCPython(unittest.TestCase): msg = '' while finish == False: m = self.socket.recv(1024 * 4) - if IS_PYTHON_3_ONWARDS: - m = m.decode('utf-8') + m = m.decode('utf-8') if m.startswith('@@PROCESSING'): sys.stdout.write('Status msg: %s\n' % (msg,)) else: diff --git a/src/debugpy/_vendored/pydevd/tests_python/debugger_unittest.py b/src/debugpy/_vendored/pydevd/tests_python/debugger_unittest.py index 1fb2a645..4432cf35 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/debugger_unittest.py +++ b/src/debugpy/_vendored/pydevd/tests_python/debugger_unittest.py @@ -1,10 +1,7 @@ from collections import namedtuple from contextlib import contextmanager import json -try: - from urllib import quote, quote_plus, unquote_plus -except ImportError: - from urllib.parse import quote, quote_plus, unquote_plus # @UnresolvedImport +from urllib.parse import quote, quote_plus, unquote_plus import re import socket @@ -127,11 +124,6 @@ try: except ImportError: from _thread import start_new_thread # @UnresolvedImport -try: - xrange -except: - xrange = range - Hit = namedtuple('Hit', 'thread_id, frame_id, line, suspend_type, name, file') diff --git a/src/debugpy/_vendored/pydevd/tests_python/resources/_debugger_case_redirect.py b/src/debugpy/_vendored/pydevd/tests_python/resources/_debugger_case_redirect.py index bb11d3d8..3f545478 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/resources/_debugger_case_redirect.py +++ b/src/debugpy/_vendored/pydevd/tests_python/resources/_debugger_case_redirect.py @@ -3,10 +3,7 @@ if __name__ == '__main__': import sys for stream_name in ('stdout', 'stderr'): stream = getattr(sys, stream_name) - if sys.version_info[0] == 2 and sys.version_info[1] == 6: - stream.write('text\n') - else: - stream.write(u'text\n') # Can't write unicode on py 2.6 + stream.write('text\n') stream.write('binary or text\n') stream.write('ação1\n') diff --git a/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_1.py b/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_1.py index 8820d5a1..0aaa5f5c 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_1.py +++ b/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_1.py @@ -1,33 +1,34 @@ import time -try: - xrange -except: - xrange = range def method2(): i = 1 + def method(): - for i in xrange(200000): + for i in range(200000): method2() if False: # Unreachable breakpoint here pass + def caller(): start_time = time.time() method() - print('TotalTime>>%s<<' % (time.time()-start_time,)) + print('TotalTime>>%s<<' % (time.time() - start_time,)) + if __name__ == '__main__': import sys if '--regular-trace' in sys.argv: + def trace_dispatch(frame, event, arg): return trace_dispatch + sys.settrace(trace_dispatch) - caller() # Initial breakpoint for a step-over here + caller() # Initial breakpoint for a step-over here print('TEST SUCEEDED') diff --git a/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_2.py b/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_2.py index 90484cdf..574fcb05 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_2.py +++ b/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_2.py @@ -2,27 +2,24 @@ import time import sys import itertools -try: - xrange # @UndefinedVariable -except NameError: - xrange = range - from itertools import groupby count = itertools.count(0) + + def next_val(): return next(count) % 25 + start_time = time.time() letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # create an array of random strings of 40 characters each -l = sorted([''.join([letters[next_val()] for _ in range(40)]) for _ in xrange(10000)]) +l = sorted([''.join([letters[next_val()] for _ in range(40)]) for _ in range(10000)]) # group by the first two characters g = {k: list(v) for k, v in groupby(l, lambda x: x[:2])} - if False: pass # Breakpoint here -print('TotalTime>>%s<<' % (time.time()-start_time,)) -print('TEST SUCEEDED') \ No newline at end of file +print('TotalTime>>%s<<' % (time.time() - start_time,)) +print('TEST SUCEEDED') diff --git a/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_3.py b/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_3.py index 4ac1eced..7903bcf8 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_3.py +++ b/src/debugpy/_vendored/pydevd/tests_python/resources/_performance_3.py @@ -1,20 +1,15 @@ import time start_time = time.time() -try: - xrange # @UndefinedVariable -except NameError: - xrange = range - # do some busy work in parallel print("Started main task") x = 0 -for i in xrange(1000000): +for i in range(1000000): x += 1 print("Completed main task") if False: pass # Breakpoint here -print('TotalTime>>%s<<' % (time.time()-start_time,)) -print('TEST SUCEEDED') \ No newline at end of file +print('TotalTime>>%s<<' % (time.time() - start_time,)) +print('TEST SUCEEDED') diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_additional_thread_info.py b/src/debugpy/_vendored/pydevd/tests_python/test_additional_thread_info.py index bb69c6b5..7852b8fe 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_additional_thread_info.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_additional_thread_info.py @@ -10,10 +10,6 @@ try: except: import _thread as thread # @UnresolvedImport -try: - xrange -except: - xrange = range #======================================================================================================================= # TestCase @@ -24,14 +20,16 @@ class TestCase(unittest.TestCase): pydev_monkey.patch_thread_modules() try: found = {} + def function(a, b, *args, **kwargs): found['a'] = a found['b'] = b found['args'] = args found['kwargs'] = kwargs - thread.start_new_thread(function, (1,2,3,4), {'d':1, 'e':2}) + + thread.start_new_thread(function, (1, 2, 3, 4), {'d':1, 'e':2}) import time - for _i in xrange(20): + for _i in range(20): if len(found) == 4: break time.sleep(.1) @@ -42,7 +40,6 @@ class TestCase(unittest.TestCase): finally: pydev_monkey.undo_patch_thread_modules() - def test_start_new_thread2(self): pydev_monkey.patch_thread_modules() try: @@ -53,7 +50,7 @@ class TestCase(unittest.TestCase): def start_it(self): try: - self.start_new_thread(self.function, (1,2,3,4), {'d':1, 'e':2}) + self.start_new_thread(self.function, (1, 2, 3, 4), {'d':1, 'e':2}) except: import traceback;traceback.print_exc() @@ -66,7 +63,7 @@ class TestCase(unittest.TestCase): f = F() f.start_it() import time - for _i in xrange(20): + for _i in range(20): if len(found) == 4: break time.sleep(.1) diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_convert_utilities.py b/src/debugpy/_vendored/pydevd/tests_python/test_convert_utilities.py index af27e74f..54e664d7 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_convert_utilities.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_convert_utilities.py @@ -1,7 +1,6 @@ # coding: utf-8 import os.path from _pydevd_bundle.pydevd_constants import IS_WINDOWS -from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding import io from _pydev_bundle.pydev_log import log_context import pytest @@ -22,7 +21,7 @@ def test_convert_utilities(tmpdir): if IS_WINDOWS: normalized = pydevd_file_utils.normcase(test_dir) - assert isinstance(normalized, str) # bytes on py2, unicode on py3 + assert isinstance(normalized, str) assert normalized.lower() == normalized upper_version = os.path.join(test_dir, 'ÁÉÍÓÚ') @@ -44,7 +43,7 @@ def test_convert_utilities(tmpdir): assert pydevd_file_utils.get_path_with_real_case('') == '' real_case = pydevd_file_utils.get_path_with_real_case(normalized) - assert isinstance(real_case, str) # bytes on py2, unicode on py3 + assert isinstance(real_case, str) # Note test_dir itself cannot be compared with because pytest may # have passed the case normalized. assert real_case.endswith("Test_Convert_Utilities") @@ -110,14 +109,14 @@ def test_to_server_and_to_client(tmpdir): def check(obtained, expected): assert obtained == expected, '%s (%s) != %s (%s)' % (obtained, type(obtained), expected, type(expected)) if isinstance(obtained, tuple): - assert isinstance(obtained[0], str) # bytes on py2, unicode on py3 + assert isinstance(obtained[0], str) else: - assert isinstance(obtained, str) # bytes on py2, unicode on py3 + assert isinstance(obtained, str) if isinstance(expected, tuple): - assert isinstance(expected[0], str) # bytes on py2, unicode on py3 + assert isinstance(expected[0], str) else: - assert isinstance(expected, str) # bytes on py2, unicode on py3 + assert isinstance(expected, str) import pydevd_file_utils if IS_WINDOWS: diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_debugger.py b/src/debugpy/_vendored/pydevd/tests_python/test_debugger.py index d39f3a97..cf1806dc 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_debugger.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_debugger.py @@ -27,10 +27,7 @@ import pydevd_file_utils import subprocess import threading from _pydev_bundle import pydev_log -try: - from urllib import unquote -except ImportError: - from urllib.parse import unquote +from urllib.parse import unquote from tests_python.debug_constants import * # noqa @@ -38,8 +35,6 @@ pytest_plugins = [ str('tests_python.debugger_fixtures'), ] -xrange = range - builtin_qualifier = "builtins" @@ -2986,7 +2981,7 @@ def test_remote_debugger_multi_proc(case_setup_remote, authenticate): writer.log.append('run thread') writer.write_run_thread(hit.thread_id) - for _i in xrange(400): + for _i in range(400): if secondary_multi_proc_process_writer.finished_ok: break time.sleep(.1) diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_debugger_json.py b/src/debugpy/_vendored/pydevd/tests_python/test_debugger_json.py index 3f2c6340..b0a29e94 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_debugger_json.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_debugger_json.py @@ -2227,7 +2227,7 @@ def test_evaluate_exec_unicode(case_setup): ) messages = json_facade.mark_messages( - OutputEvent, lambda output_event: u'中' in output_event.body.output) + OutputEvent, lambda output_event: (u'中' in output_event.body.output) and ('pydevd warning' not in output_event.body.output)) assert len(messages) == 1 # Check exec @@ -2238,7 +2238,7 @@ def test_evaluate_exec_unicode(case_setup): ) messages = json_facade.mark_messages( - OutputEvent, lambda output_event: u'中' in output_event.body.output) + OutputEvent, lambda output_event: (u'中' in output_event.body.output) and ('pydevd warning' not in output_event.body.output)) assert len(messages) == 1 response = json_facade.evaluate( @@ -2249,7 +2249,7 @@ def test_evaluate_exec_unicode(case_setup): assert response.body.result in ("u'\\u4e2d'", "'\u4e2d'") # py2 or py3 messages = json_facade.mark_messages( - OutputEvent, lambda output_event: u'中' in output_event.body.output) + OutputEvent, lambda output_event: (u'中' in output_event.body.output) and ('pydevd warning' not in output_event.body.output)) assert len(messages) == 0 # i.e.: we don't print in this case. json_facade.write_continue() diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_safe_repr.py b/src/debugpy/_vendored/pydevd/tests_python/test_safe_repr.py index 37f54d16..9356e40f 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_safe_repr.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_safe_repr.py @@ -5,7 +5,7 @@ import re import pytest from _pydevd_bundle.pydevd_safe_repr import SafeRepr import json -from _pydevd_bundle.pydevd_constants import IS_JYTHON, IS_PY36_OR_GREATER +from _pydevd_bundle.pydevd_constants import IS_PY36_OR_GREATER try: import numpy as np @@ -16,10 +16,6 @@ PY_VER = sys.version_info[0] assert PY_VER <= 3 # Fix the code when Python 4 comes around. PY3K = PY_VER == 3 -if PY3K: - unicode = str - xrange = range - class SafeReprTestBase(object): @@ -449,24 +445,24 @@ class TestOtherPythonTypes(SafeReprTestBase): # raise NotImplementedError def test_range_small(self): - range_name = xrange.__name__ - value = xrange(1, 42) + range_name = range.__name__ + value = range(1, 42) self.assert_unchanged(value, '%s(1, 42)' % (range_name,)) @pytest.mark.skipif(sys.version_info < (3, 0), reason='Py3 specific test') def test_range_large_stop_only(self): - range_name = xrange.__name__ + range_name = range.__name__ stop = SafeRepr.maxcollection[0] - value = xrange(stop) + value = range(stop) self.assert_unchanged(value, '%s(0, %s)' % (range_name, stop)) def test_range_large_with_start(self): - range_name = xrange.__name__ + range_name = range.__name__ stop = SafeRepr.maxcollection[0] + 1 - value = xrange(1, stop) + value = range(1, stop) self.assert_unchanged(value, '%s(1, %s)' % (range_name, stop)) @@ -556,10 +552,10 @@ class TestUserDefinedObjects(SafeReprTestBase): def __repr__(self): return 'MyRepr' - value1 = TestClass(xrange(0, 15)) - value2 = TestClass(xrange(0, 16)) - value3 = TestClass([TestClass(xrange(0, 10))]) - value4 = TestClass([TestClass(xrange(0, 11))]) + value1 = TestClass(range(0, 15)) + value2 = TestClass(range(0, 16)) + value3 = TestClass([TestClass(range(0, 10))]) + value4 = TestClass([TestClass(range(0, 11))]) self.assert_unchanged(value1, 'MyRepr') self.assert_shortened(value2, '') @@ -614,7 +610,6 @@ class TestNumpy(SafeReprTestBase): @pytest.mark.parametrize('use_str', [True, False]) def test_py3_str_slicing(params, use_str): # Note: much simpler in python because __repr__ is required to return str - # (which is actually unicode). safe_repr = SafeRepr() safe_repr.locale_preferred_encoding = 'ascii' safe_repr.sys_stdout_encoding = params.get('sys_stdout_encoding', 'ascii')