content
stringlengths 1
103k
⌀ | path
stringlengths 8
216
| filename
stringlengths 2
179
| language
stringclasses 15
values | size_bytes
int64 2
189k
| quality_score
float64 0.5
0.95
| complexity
float64 0
1
| documentation_ratio
float64 0
1
| repository
stringclasses 5
values | stars
int64 0
1k
| created_date
stringdate 2023-07-10 19:21:08
2025-07-09 19:11:45
| license
stringclasses 4
values | is_test
bool 2
classes | file_hash
stringlengths 32
32
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
\n\n
|
.venv\Lib\site-packages\debugpy\common\__pycache__\messaging.cpython-313.pyc
|
messaging.cpython-313.pyc
|
Other
| 65,889 | 0.75 | 0.1125 | 0.009631 |
node-utils
| 634 |
2023-10-24T21:43:55.262515
|
MIT
| false |
d8202f33906fc0deb52f5cb2a41b44b7
|
\n\n
|
.venv\Lib\site-packages\debugpy\common\__pycache__\singleton.cpython-313.pyc
|
singleton.cpython-313.pyc
|
Other
| 8,016 | 0.95 | 0.171717 | 0 |
react-lib
| 872 |
2023-11-17T23:35:48.080836
|
GPL-3.0
| false |
4708a3e148ddbba179aa4043d64bbb8c
|
\n\n
|
.venv\Lib\site-packages\debugpy\common\__pycache__\sockets.cpython-313.pyc
|
sockets.cpython-313.pyc
|
Other
| 5,240 | 0.95 | 0.057143 | 0 |
python-kit
| 650 |
2024-02-03T06:14:34.897429
|
Apache-2.0
| false |
a8eb16859e698917d669a5f2e3e1cc18
|
\n\n
|
.venv\Lib\site-packages\debugpy\common\__pycache__\stacks.cpython-313.pyc
|
stacks.cpython-313.pyc
|
Other
| 2,406 | 0.8 | 0.133333 | 0.076923 |
vue-tools
| 92 |
2025-04-16T15:30:46.919369
|
GPL-3.0
| false |
da8bac3299b7fb4e7ec1da46f69911c6
|
\n\n
|
.venv\Lib\site-packages\debugpy\common\__pycache__\timestamp.cpython-313.pyc
|
timestamp.cpython-313.pyc
|
Other
| 695 | 0.7 | 0 | 0 |
node-utils
| 15 |
2023-09-11T23:13:49.737002
|
BSD-3-Clause
| false |
e8279c8bcebad653336979622b044a25
|
\n\n
|
.venv\Lib\site-packages\debugpy\common\__pycache__\util.cpython-313.pyc
|
util.cpython-313.pyc
|
Other
| 6,397 | 0.95 | 0.148649 | 0.028986 |
awesome-app
| 734 |
2023-10-13T06:36:44.150810
|
Apache-2.0
| false |
f9700689c6f7a256e4a6533266f2d0e2
|
\n\n
|
.venv\Lib\site-packages\debugpy\common\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 729 | 0.8 | 0 | 0 |
node-utils
| 652 |
2025-01-08T01:24:05.179296
|
MIT
| false |
1dd78b336578d349217a05a43925276b
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nimport os\nimport sys\n\nimport debugpy\nfrom debugpy import launcher\nfrom debugpy.common import json\nfrom debugpy.launcher import debuggee\n\n\ndef launch_request(request):\n debug_options = set(request("debugOptions", json.array(str)))\n\n # Handling of properties that can also be specified as legacy "debugOptions" flags.\n # If property is explicitly set to false, but the flag is in "debugOptions", treat\n # it as an error. Returns None if the property wasn't explicitly set either way.\n def property_or_debug_option(prop_name, flag_name):\n assert prop_name[0].islower() and flag_name[0].isupper()\n\n value = request(prop_name, bool, optional=True)\n if value == ():\n value = None\n\n if flag_name in debug_options:\n if value is False:\n raise request.isnt_valid(\n '{0}:false and "debugOptions":[{1}] are mutually exclusive',\n json.repr(prop_name),\n json.repr(flag_name),\n )\n value = True\n\n return value\n\n python = request("python", json.array(str, size=(1,)))\n cmdline = list(python)\n\n if not request("noDebug", json.default(False)):\n # see https://github.com/microsoft/debugpy/issues/861\n if sys.version_info[:2] >= (3, 11):\n cmdline += ["-X", "frozen_modules=off"]\n\n port = request("port", int)\n cmdline += [\n os.path.dirname(debugpy.__file__),\n "--connect",\n launcher.adapter_host + ":" + str(port),\n ]\n\n if not request("subProcess", True):\n cmdline += ["--configure-subProcess", "False"]\n\n qt_mode = request(\n "qt",\n json.enum(\n "none", "auto", "pyside", "pyside2", "pyqt4", "pyqt5", optional=True\n ),\n )\n cmdline += ["--configure-qt", qt_mode]\n\n adapter_access_token = request("adapterAccessToken", str, optional=True)\n if adapter_access_token != ():\n cmdline += ["--adapter-access-token", adapter_access_token]\n\n debugpy_args = request("debugpyArgs", json.array(str))\n cmdline += debugpy_args\n\n # Use the copy of arguments that was propagated via the command line rather than\n # "args" in the request itself, to allow for shell expansion.\n cmdline += sys.argv[1:]\n\n process_name = request("processName", sys.executable)\n\n env = os.environ.copy()\n env_changes = request("env", json.object((str, type(None))))\n if sys.platform == "win32":\n # Environment variables are case-insensitive on Win32, so we need to normalize\n # both dicts to make sure that env vars specified in the debug configuration\n # overwrite the global env vars correctly. If debug config has entries that\n # differ in case only, that's an error.\n env = {k.upper(): v for k, v in os.environ.items()}\n new_env_changes = {}\n for k, v in env_changes.items():\n k_upper = k.upper()\n if k_upper in new_env_changes:\n if new_env_changes[k_upper] == v:\n continue\n else:\n raise request.isnt_valid(\n 'Found duplicate in "env": {0}.'.format(k_upper)\n )\n new_env_changes[k_upper] = v\n env_changes = new_env_changes\n if "DEBUGPY_TEST" in env:\n # If we're running as part of a debugpy test, make sure that codecov is not\n # applied to the debuggee, since it will conflict with pydevd.\n env.pop("COV_CORE_SOURCE", None)\n env.update(env_changes)\n env = {k: v for k, v in env.items() if v is not None}\n\n if request("gevent", False):\n env["GEVENT_SUPPORT"] = "True"\n\n console = request(\n "console",\n json.enum(\n "internalConsole", "integratedTerminal", "externalTerminal", optional=True\n ),\n )\n\n redirect_output = property_or_debug_option("redirectOutput", "RedirectOutput")\n if redirect_output is None:\n # If neither the property nor the option were specified explicitly, choose\n # the default depending on console type - "internalConsole" needs it to\n # provide any output at all, but it's unnecessary for the terminals.\n redirect_output = console == "internalConsole"\n if redirect_output:\n # sys.stdout buffering must be disabled - otherwise we won't see the output\n # at all until the buffer fills up.\n env["PYTHONUNBUFFERED"] = "1"\n # Force UTF-8 output to minimize data loss due to re-encoding.\n env["PYTHONIOENCODING"] = "utf-8"\n\n if property_or_debug_option("waitOnNormalExit", "WaitOnNormalExit"):\n if console == "internalConsole":\n raise request.isnt_valid(\n '"waitOnNormalExit" is not supported for "console":"internalConsole"'\n )\n debuggee.wait_on_exit_predicates.append(lambda code: code == 0)\n if property_or_debug_option("waitOnAbnormalExit", "WaitOnAbnormalExit"):\n if console == "internalConsole":\n raise request.isnt_valid(\n '"waitOnAbnormalExit" is not supported for "console":"internalConsole"'\n )\n debuggee.wait_on_exit_predicates.append(lambda code: code != 0)\n\n debuggee.spawn(process_name, cmdline, env, redirect_output)\n return {}\n\n\ndef terminate_request(request):\n del debuggee.wait_on_exit_predicates[:]\n request.respond({})\n debuggee.kill()\n\n\ndef disconnect():\n del debuggee.wait_on_exit_predicates[:]\n debuggee.kill()\n
|
.venv\Lib\site-packages\debugpy\launcher\handlers.py
|
handlers.py
|
Python
| 5,880 | 0.95 | 0.210526 | 0.168 |
vue-tools
| 296 |
2023-11-16T08:46:26.662326
|
MIT
| false |
26d34e59fbd2bb2ae2c1f3ec46c40b46
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nimport codecs\nimport os\nimport threading\n\nfrom debugpy import launcher\nfrom debugpy.common import log\n\n\nclass CaptureOutput(object):\n """Captures output from the specified file descriptor, and tees it into another\n file descriptor while generating DAP "output" events for it.\n """\n\n instances = {}\n """Keys are output categories, values are CaptureOutput instances."""\n\n def __init__(self, whose, category, fd, stream):\n assert category not in self.instances\n self.instances[category] = self\n log.info("Capturing {0} of {1}.", category, whose)\n\n self.category = category\n self._whose = whose\n self._fd = fd\n self._decoder = codecs.getincrementaldecoder("utf-8")(errors="surrogateescape")\n\n if stream is None:\n # Can happen if running under pythonw.exe.\n self._stream = None\n else:\n self._stream = stream.buffer\n encoding = stream.encoding\n if encoding is None or encoding == "cp65001":\n encoding = "utf-8"\n try:\n self._encode = codecs.getencoder(encoding)\n except Exception:\n log.swallow_exception(\n "Unsupported {0} encoding {1!r}; falling back to UTF-8.",\n category,\n encoding,\n level="warning",\n )\n self._encode = codecs.getencoder("utf-8")\n else:\n log.info("Using encoding {0!r} for {1}", encoding, category)\n\n self._worker_thread = threading.Thread(target=self._worker, name=category)\n self._worker_thread.start()\n\n def __del__(self):\n fd = self._fd\n if fd is not None:\n try:\n os.close(fd)\n except Exception:\n pass\n\n def _worker(self):\n while self._fd is not None:\n try:\n s = os.read(self._fd, 0x1000)\n except Exception:\n break\n if not len(s):\n break\n self._process_chunk(s)\n\n # Flush any remaining data in the incremental decoder.\n self._process_chunk(b"", final=True)\n\n def _process_chunk(self, s, final=False):\n s = self._decoder.decode(s, final=final)\n if len(s) == 0:\n return\n\n try:\n launcher.channel.send_event(\n "output", {"category": self.category, "output": s.replace("\r\n", "\n")}\n )\n except Exception:\n pass # channel to adapter is already closed\n\n if self._stream is None:\n return\n\n try:\n s, _ = self._encode(s, "surrogateescape")\n size = len(s)\n i = 0\n while i < size:\n written = self._stream.write(s[i:])\n self._stream.flush()\n if written == 0:\n # This means that the output stream was closed from the other end.\n # Do the same to the debuggee, so that it knows as well.\n os.close(self._fd)\n self._fd = None\n break\n i += written\n except Exception:\n log.swallow_exception("Error printing {0!r} to {1}", s, self.category)\n\n\ndef wait_for_remaining_output():\n """Waits for all remaining output to be captured and propagated."""\n for category, instance in CaptureOutput.instances.items():\n log.info("Waiting for remaining {0} of {1}.", category, instance._whose)\n instance._worker_thread.join()\n
|
.venv\Lib\site-packages\debugpy\launcher\output.py
|
output.py
|
Python
| 3,861 | 0.95 | 0.247788 | 0.073684 |
vue-tools
| 444 |
2024-04-26T23:43:49.145893
|
Apache-2.0
| false |
c8be94538d890b890855280faf2563f0
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nimport ctypes\nfrom ctypes.wintypes import BOOL, DWORD, HANDLE, LARGE_INTEGER, LPCSTR, UINT\n\nfrom debugpy.common import log\n\n\nJOBOBJECTCLASS = ctypes.c_int\nLPDWORD = ctypes.POINTER(DWORD)\nLPVOID = ctypes.c_void_p\nSIZE_T = ctypes.c_size_t\nULONGLONG = ctypes.c_ulonglong\n\n\nclass IO_COUNTERS(ctypes.Structure):\n _fields_ = [\n ("ReadOperationCount", ULONGLONG),\n ("WriteOperationCount", ULONGLONG),\n ("OtherOperationCount", ULONGLONG),\n ("ReadTransferCount", ULONGLONG),\n ("WriteTransferCount", ULONGLONG),\n ("OtherTransferCount", ULONGLONG),\n ]\n\n\nclass JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):\n _fields_ = [\n ("PerProcessUserTimeLimit", LARGE_INTEGER),\n ("PerJobUserTimeLimit", LARGE_INTEGER),\n ("LimitFlags", DWORD),\n ("MinimumWorkingSetSize", SIZE_T),\n ("MaximumWorkingSetSize", SIZE_T),\n ("ActiveProcessLimit", DWORD),\n ("Affinity", SIZE_T),\n ("PriorityClass", DWORD),\n ("SchedulingClass", DWORD),\n ]\n\n\nclass JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):\n _fields_ = [\n ("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),\n ("IoInfo", IO_COUNTERS),\n ("ProcessMemoryLimit", SIZE_T),\n ("JobMemoryLimit", SIZE_T),\n ("PeakProcessMemoryUsed", SIZE_T),\n ("PeakJobMemoryUsed", SIZE_T),\n ]\n\n\nJobObjectExtendedLimitInformation = JOBOBJECTCLASS(9)\n\nJOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800\nJOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000\n\nPROCESS_TERMINATE = 0x0001\nPROCESS_SET_QUOTA = 0x0100\n\n\ndef _errcheck(is_error_result=(lambda result: not result)):\n def impl(result, func, args):\n if is_error_result(result):\n log.debug("{0} returned {1}", func.__name__, result)\n raise ctypes.WinError()\n else:\n return result\n\n return impl\n\n\nkernel32 = ctypes.windll.kernel32\n\nkernel32.AssignProcessToJobObject.errcheck = _errcheck()\nkernel32.AssignProcessToJobObject.restype = BOOL\nkernel32.AssignProcessToJobObject.argtypes = (HANDLE, HANDLE)\n\nkernel32.CreateJobObjectA.errcheck = _errcheck(lambda result: result == 0)\nkernel32.CreateJobObjectA.restype = HANDLE\nkernel32.CreateJobObjectA.argtypes = (LPVOID, LPCSTR)\n\nkernel32.OpenProcess.errcheck = _errcheck(lambda result: result == 0)\nkernel32.OpenProcess.restype = HANDLE\nkernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)\n\nkernel32.QueryInformationJobObject.errcheck = _errcheck()\nkernel32.QueryInformationJobObject.restype = BOOL\nkernel32.QueryInformationJobObject.argtypes = (\n HANDLE,\n JOBOBJECTCLASS,\n LPVOID,\n DWORD,\n LPDWORD,\n)\n\nkernel32.SetInformationJobObject.errcheck = _errcheck()\nkernel32.SetInformationJobObject.restype = BOOL\nkernel32.SetInformationJobObject.argtypes = (HANDLE, JOBOBJECTCLASS, LPVOID, DWORD)\n\nkernel32.TerminateJobObject.errcheck = _errcheck()\nkernel32.TerminateJobObject.restype = BOOL\nkernel32.TerminateJobObject.argtypes = (HANDLE, UINT)\n
|
.venv\Lib\site-packages\debugpy\launcher\winapi.py
|
winapi.py
|
Python
| 3,233 | 0.95 | 0.067308 | 0.037975 |
python-kit
| 987 |
2024-04-21T23:26:00.014071
|
MIT
| false |
587455ef1a0943d989e26674dbfc8d89
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\n__all__ = []\n\n\nadapter_host = None\n"""The host on which adapter is running and listening for incoming connections\nfrom the launcher and the servers."""\n\nchannel = None\n"""DAP message channel to the adapter."""\n\n\ndef connect(host, port):\n from debugpy.common import log, messaging, sockets\n from debugpy.launcher import handlers\n\n global channel, adapter_host\n assert channel is None\n assert adapter_host is None\n\n log.info("Connecting to adapter at {0}:{1}", host, port)\n\n sock = sockets.create_client()\n sock.connect((host, port))\n adapter_host = host\n\n stream = messaging.JsonIOStream.from_socket(sock, "Adapter")\n channel = messaging.JsonMessageChannel(stream, handlers=handlers)\n channel.start()\n
|
.venv\Lib\site-packages\debugpy\launcher\__init__.py
|
__init__.py
|
Python
| 922 | 0.95 | 0.09375 | 0.136364 |
python-kit
| 642 |
2023-09-24T17:44:39.568268
|
MIT
| false |
7d2d69c32b2614961914b055244b532c
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\n__all__ = ["main"]\n\nimport locale\nimport signal\nimport sys\n\n# WARNING: debugpy and submodules must not be imported on top level in this module,\n# and should be imported locally inside main() instead.\n\n\ndef main():\n from debugpy import launcher\n from debugpy.common import log\n from debugpy.launcher import debuggee\n\n log.to_file(prefix="debugpy.launcher")\n log.describe_environment("debugpy.launcher startup environment:")\n\n if sys.platform == "win32":\n # For windows, disable exceptions on Ctrl+C - we want to allow the debuggee\n # process to handle these, or not, as it sees fit. If the debuggee exits\n # on Ctrl+C, the launcher will also exit, so it doesn't need to observe\n # the signal directly.\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n # Everything before "--" is command line arguments for the launcher itself,\n # and everything after "--" is command line arguments for the debuggee.\n log.info("sys.argv before parsing: {0}", sys.argv)\n sep = sys.argv.index("--")\n launcher_argv = sys.argv[1:sep]\n sys.argv[:] = [sys.argv[0]] + sys.argv[sep + 1 :]\n log.info("sys.argv after patching: {0}", sys.argv)\n\n # The first argument specifies the host/port on which the adapter is waiting\n # for launcher to connect. It's either host:port, or just port.\n adapter = launcher_argv[0]\n host, sep, port = adapter.partition(":")\n if not sep:\n host = "127.0.0.1"\n port = adapter\n port = int(port)\n\n launcher.connect(host, port)\n launcher.channel.wait()\n\n if debuggee.process is not None:\n sys.exit(debuggee.process.returncode)\n\n\nif __name__ == "__main__":\n # debugpy can also be invoked directly rather than via -m. In this case, the first\n # entry on sys.path is the one added automatically by Python for the directory\n # containing this file. This means that import debugpy will not work, since we need\n # the parent directory of debugpy/ to be in sys.path, rather than debugpy/launcher/.\n #\n # The other issue is that many other absolute imports will break, because they\n # will be resolved relative to debugpy/launcher/ - e.g. `import state` will then try\n # to import debugpy/launcher/state.py.\n #\n # To fix both, we need to replace the automatically added entry such that it points\n # at parent directory of debugpy/ instead of debugpy/launcher, import debugpy with that\n # in sys.path, and then remove the first entry entry altogether, so that it doesn't\n # affect any further imports we might do. For example, suppose the user did:\n #\n # python /foo/bar/debugpy/launcher ...\n #\n # At the beginning of this script, sys.path will contain "/foo/bar/debugpy/launcher"\n # as the first entry. What we want is to replace it with "/foo/bar', then import\n # debugpy with that in effect, and then remove the replaced entry before any more\n # code runs. The imported debugpy module will remain in sys.modules, and thus all\n # future imports of it or its submodules will resolve accordingly.\n if "debugpy" not in sys.modules:\n # Do not use dirname() to walk up - this can be a relative path, e.g. ".".\n sys.path[0] = sys.path[0] + "/../../"\n __import__("debugpy")\n del sys.path[0]\n\n # Apply OS-global and user-specific locale settings.\n try:\n locale.setlocale(locale.LC_ALL, "")\n except Exception:\n # On POSIX, locale is set via environment variables, and this can fail if\n # those variables reference a non-existing locale. Ignore and continue using\n # the default "C" locale if so.\n pass\n\n main()\n
|
.venv\Lib\site-packages\debugpy\launcher\__main__.py
|
__main__.py
|
Python
| 3,903 | 0.95 | 0.164835 | 0.513158 |
vue-tools
| 885 |
2025-02-03T01:55:47.435247
|
Apache-2.0
| false |
d022c162738eef42501c007a3038a583
|
\n\n
|
.venv\Lib\site-packages\debugpy\launcher\__pycache__\debuggee.cpython-313.pyc
|
debuggee.cpython-313.pyc
|
Other
| 10,371 | 0.8 | 0.020619 | 0 |
awesome-app
| 746 |
2024-07-31T21:58:47.337980
|
BSD-3-Clause
| false |
572872b30221a5c1c794dbb04c6e68df
|
\n\n
|
.venv\Lib\site-packages\debugpy\launcher\__pycache__\handlers.cpython-313.pyc
|
handlers.cpython-313.pyc
|
Other
| 6,187 | 0.8 | 0.037037 | 0.019608 |
awesome-app
| 428 |
2024-01-06T03:16:03.219707
|
MIT
| false |
cadc486bee529a9ee050672dce7d8965
|
\n\n
|
.venv\Lib\site-packages\debugpy\launcher\__pycache__\output.cpython-313.pyc
|
output.cpython-313.pyc
|
Other
| 5,079 | 0.8 | 0.113636 | 0 |
python-kit
| 806 |
2024-05-19T06:51:47.178614
|
GPL-3.0
| false |
d54ba1db4fe1b47141cdd83eb2507e50
|
\n\n
|
.venv\Lib\site-packages\debugpy\launcher\__pycache__\winapi.cpython-313.pyc
|
winapi.cpython-313.pyc
|
Other
| 4,531 | 0.8 | 0 | 0 |
react-lib
| 718 |
2025-07-08T01:29:19.228180
|
MIT
| false |
7dd8517632ada525bb6b68c201f66b84
|
\n\n
|
.venv\Lib\site-packages\debugpy\launcher\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 1,078 | 0.8 | 0 | 0.181818 |
node-utils
| 179 |
2025-04-12T16:29:53.195963
|
Apache-2.0
| false |
1c3cbba6f3c9da80936306b3e9e083a6
|
\n\n
|
.venv\Lib\site-packages\debugpy\launcher\__pycache__\__main__.cpython-313.pyc
|
__main__.cpython-313.pyc
|
Other
| 2,524 | 0.95 | 0 | 0 |
node-utils
| 158 |
2024-06-15T21:30:37.042230
|
MIT
| false |
1c1d443d4feacb495c481996fc2326fc
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\n"""Script injected into the debuggee process during attach-to-PID."""\n\nimport os\n\n\n__file__ = os.path.abspath(__file__)\n_debugpy_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\n\ndef attach(setup):\n log = None\n try:\n import sys\n\n if "threading" not in sys.modules:\n try:\n\n def on_warn(msg):\n print(msg, file=sys.stderr)\n\n def on_exception(msg):\n print(msg, file=sys.stderr)\n\n def on_critical(msg):\n print(msg, file=sys.stderr)\n\n pydevd_attach_to_process_path = os.path.join(\n _debugpy_dir,\n "debugpy",\n "_vendored",\n "pydevd",\n "pydevd_attach_to_process",\n )\n assert os.path.exists(pydevd_attach_to_process_path)\n sys.path.insert(0, pydevd_attach_to_process_path)\n\n # NOTE: that it's not a part of the pydevd PYTHONPATH\n import attach_script\n\n attach_script.fix_main_thread_id(\n on_warn=on_warn, on_exception=on_exception, on_critical=on_critical\n )\n\n # NOTE: At this point it should be safe to remove this.\n sys.path.remove(pydevd_attach_to_process_path)\n except:\n import traceback\n\n traceback.print_exc()\n raise\n\n sys.path.insert(0, _debugpy_dir)\n try:\n import debugpy\n import debugpy.server\n from debugpy.common import json, log\n import pydevd\n finally:\n assert sys.path[0] == _debugpy_dir\n del sys.path[0]\n\n py_db = pydevd.get_global_debugger()\n if py_db is not None:\n py_db.dispose_and_kill_all_pydevd_threads(wait=False)\n\n if setup["log_to"] is not None:\n debugpy.log_to(setup["log_to"])\n log.info("Configuring injected debugpy: {0}", json.repr(setup))\n\n if setup["mode"] == "listen":\n debugpy.listen(setup["address"])\n elif setup["mode"] == "connect":\n debugpy.connect(\n setup["address"], access_token=setup["adapter_access_token"]\n )\n else:\n raise AssertionError(repr(setup))\n\n except:\n import traceback\n\n traceback.print_exc()\n if log is None:\n raise\n else:\n log.reraise_exception()\n\n log.info("debugpy injected successfully")\n
|
.venv\Lib\site-packages\debugpy\server\attach_pid_injected.py
|
attach_pid_injected.py
|
Python
| 2,826 | 0.95 | 0.141304 | 0.071429 |
node-utils
| 371 |
2023-11-18T00:35:21.411088
|
MIT
| false |
cf3b1fe5d0040a80aef5185a9e7ce4a2
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\n# "force_pydevd" must be imported first to ensure (via side effects)\n# that the debugpy-vendored copy of pydevd gets used.\nimport debugpy._vendored.force_pydevd # noqa\n
|
.venv\Lib\site-packages\debugpy\server\__init__.py
|
__init__.py
|
Python
| 330 | 0.95 | 0.142857 | 0.833333 |
node-utils
| 577 |
2025-04-01T12:29:30.044944
|
MIT
| false |
2efa713c2ba65ef80cad0407f04e3feb
|
\n\n
|
.venv\Lib\site-packages\debugpy\server\__pycache__\api.cpython-313.pyc
|
api.cpython-313.pyc
|
Other
| 14,816 | 0.8 | 0.060345 | 0 |
python-kit
| 28 |
2024-07-11T15:04:36.745404
|
GPL-3.0
| false |
cd2a29ee93a3ec27b097bed490832eeb
|
\n\n
|
.venv\Lib\site-packages\debugpy\server\__pycache__\attach_pid_injected.cpython-313.pyc
|
attach_pid_injected.cpython-313.pyc
|
Other
| 3,668 | 0.8 | 0 | 0 |
react-lib
| 674 |
2024-06-28T23:13:35.862017
|
Apache-2.0
| false |
82fc1d48b90730747d51c3865e519203
|
\n\n
|
.venv\Lib\site-packages\debugpy\server\__pycache__\cli.cpython-313.pyc
|
cli.cpython-313.pyc
|
Other
| 21,112 | 0.95 | 0.05618 | 0.005917 |
python-kit
| 385 |
2025-04-25T05:34:57.095557
|
Apache-2.0
| false |
76a072e4ce3ceb4a1384350a7d929cad
|
\n\n
|
.venv\Lib\site-packages\debugpy\server\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 245 | 0.7 | 0 | 0 |
awesome-app
| 750 |
2023-10-13T21:34:52.414215
|
Apache-2.0
| false |
785521d1218bc2886e7fee887815f645
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nfrom importlib import import_module\nimport os\nimport warnings\n\nfrom . import check_modules, prefix_matcher, preimport, vendored\n\n# Ensure that pydevd is our vendored copy.\n_unvendored, _ = check_modules('pydevd',\n prefix_matcher('pydev', '_pydev'))\nif _unvendored:\n _unvendored = sorted(_unvendored.values())\n msg = 'incompatible copy of pydevd already imported'\n # raise ImportError(msg)\n warnings.warn(msg + ':\n {}'.format('\n '.join(_unvendored)))\n\n# If debugpy logging is enabled, enable it for pydevd as well\nif "DEBUGPY_LOG_DIR" in os.environ:\n os.environ[str("PYDEVD_DEBUG")] = str("True")\n os.environ[str("PYDEVD_DEBUG_FILE")] = os.environ["DEBUGPY_LOG_DIR"] + str("/debugpy.pydevd.log")\n\n# Disable pydevd frame-eval optimizations only if unset, to allow opt-in.\nif "PYDEVD_USE_FRAME_EVAL" not in os.environ:\n os.environ[str("PYDEVD_USE_FRAME_EVAL")] = str("NO")\n\n# Constants must be set before importing any other pydevd module\n# # due to heavy use of "from" in them.\nwith warnings.catch_warnings():\n warnings.simplefilter("ignore", category=DeprecationWarning)\n with vendored('pydevd'):\n pydevd_constants = import_module('_pydevd_bundle.pydevd_constants')\n# We limit representation size in our representation provider when needed.\npydevd_constants.MAXIMUM_VARIABLE_REPRESENTATION_SIZE = 2 ** 32\n\n# Now make sure all the top-level modules and packages in pydevd are\n# loaded. Any pydevd modules that aren't loaded at this point, will\n# be loaded using their parent package's __path__ (i.e. one of the\n# following).\nwith warnings.catch_warnings():\n warnings.simplefilter("ignore", category=DeprecationWarning)\n preimport('pydevd', [\n '_pydev_bundle',\n '_pydev_runfiles',\n '_pydevd_bundle',\n '_pydevd_frame_eval',\n 'pydev_ipython',\n 'pydevd_plugins',\n 'pydevd',\n ])\n\n# When pydevd is imported it sets the breakpoint behavior, but it needs to be\n# overridden because by default pydevd will connect to the remote debugger using\n# its own custom protocol rather than DAP.\nimport pydevd # noqa\nimport debugpy # noqa\n\n\ndef debugpy_breakpointhook():\n debugpy.breakpoint()\n\n\npydevd.install_breakpointhook(debugpy_breakpointhook)\n\n# Ensure that pydevd uses JSON protocol\nfrom _pydevd_bundle import pydevd_constants\nfrom _pydevd_bundle import pydevd_defaults\npydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = pydevd_constants.HTTP_JSON_PROTOCOL\n\n# Enable some defaults related to debugpy such as sending a single notification when\n# threads pause and stopping on any exception.\npydevd_defaults.PydevdCustomization.DEBUG_MODE = 'debugpy-dap'\n\n# This is important when pydevd attaches automatically to a subprocess. In this case, we have to\n# make sure that debugpy is properly put back in the game for users to be able to use it.\npydevd_defaults.PydevdCustomization.PREIMPORT = '%s;%s' % (\n os.path.dirname(os.path.dirname(debugpy.__file__)), \n 'debugpy._vendored.force_pydevd'\n)\n
|
.venv\Lib\site-packages\debugpy\_vendored\force_pydevd.py
|
force_pydevd.py
|
Python
| 3,253 | 0.95 | 0.098765 | 0.333333 |
awesome-app
| 285 |
2024-09-10T20:12:38.575606
|
Apache-2.0
| false |
e9e5e210d7bee15e184887781be64aae
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nfrom . import VENDORED_ROOT\nfrom ._util import cwd, iter_all_files\n\n\nINCLUDES = [\n 'setup_pydevd_cython.py',\n]\n\n\ndef iter_files():\n # From the root of pydevd repo, we want only scripts and\n # subdirectories that constitute the package itself (not helper\n # scripts, tests etc). But when walking down into those\n # subdirectories, we want everything below.\n\n with cwd(VENDORED_ROOT):\n return iter_all_files('pydevd', prune_dir, exclude_file)\n\n\ndef prune_dir(dirname, basename):\n if basename == '__pycache__':\n return True\n elif dirname != 'pydevd':\n return False\n elif basename.startswith('pydev'):\n return False\n elif basename.startswith('_pydev'):\n return False\n return True\n\n\ndef exclude_file(dirname, basename):\n if dirname == 'pydevd':\n if basename in INCLUDES:\n return False\n elif not basename.endswith('.py'):\n return True\n elif 'pydev' not in basename:\n return True\n return False\n\n if basename.endswith('.pyc'):\n return True\n return False\n
|
.venv\Lib\site-packages\debugpy\_vendored\_pydevd_packaging.py
|
_pydevd_packaging.py
|
Python
| 1,293 | 0.95 | 0.166667 | 0.189189 |
python-kit
| 470 |
2024-12-13T04:07:37.890830
|
MIT
| false |
b2b33f980e88295be25f0e39bebfbbdf
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nimport contextlib\nimport os\n\n\n@contextlib.contextmanager\ndef cwd(dirname):\n """A context manager for operating in a different directory."""\n orig = os.getcwd()\n os.chdir(dirname)\n try:\n yield orig\n finally:\n os.chdir(orig)\n\n\ndef iter_all_files(root, prune_dir=None, exclude_file=None):\n """Yield (dirname, basename, filename) for each file in the tree.\n\n This is an alternative to os.walk() that flattens out the tree and\n with filtering.\n """\n pending = [root]\n while pending:\n dirname = pending.pop(0)\n for result in _iter_files(dirname, pending, prune_dir, exclude_file):\n yield result\n\n\ndef iter_tree(root, prune_dir=None, exclude_file=None):\n """Yield (dirname, files) for each directory in the tree.\n\n The list of files is actually a list of (basename, filename).\n\n This is an alternative to os.walk() with filtering."""\n pending = [root]\n while pending:\n dirname = pending.pop(0)\n files = []\n for _, b, f in _iter_files(dirname, pending, prune_dir, exclude_file):\n files.append((b, f))\n yield dirname, files\n\n\ndef _iter_files(dirname, subdirs, prune_dir, exclude_file):\n for basename in os.listdir(dirname):\n filename = os.path.join(dirname, basename)\n if os.path.isdir(filename):\n if prune_dir is not None and prune_dir(dirname, basename):\n continue\n subdirs.append(filename)\n else:\n # TODO: Use os.path.isfile() to narrow it down?\n if exclude_file is not None and exclude_file(dirname, basename):\n continue\n yield dirname, basename, filename\n
|
.venv\Lib\site-packages\debugpy\_vendored\_util.py
|
_util.py
|
Python
| 1,899 | 0.95 | 0.288136 | 0.085106 |
react-lib
| 558 |
2024-11-09T08:07:27.290389
|
GPL-3.0
| false |
8c64d7465944b877c398a3f873fd8cf1
|
# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nimport contextlib\nfrom importlib import import_module\nimport os\nimport sys\n\nfrom . import _util\n\n\nVENDORED_ROOT = os.path.dirname(os.path.abspath(__file__))\n# TODO: Move the "pydevd" git submodule to the debugpy/_vendored directory\n# and then drop the following fallback.\nif "pydevd" not in os.listdir(VENDORED_ROOT):\n VENDORED_ROOT = os.path.dirname(VENDORED_ROOT)\n\n\ndef list_all(resolve=False):\n """Return the list of vendored projects."""\n # TODO: Derive from os.listdir(VENDORED_ROOT)?\n projects = ["pydevd"]\n if not resolve:\n return projects\n return [project_root(name) for name in projects]\n\n\ndef project_root(project):\n """Return the path the root dir of the vendored project.\n\n If "project" is an empty string then the path prefix for vendored\n projects (e.g. "debugpy/_vendored/") will be returned.\n """\n if not project:\n project = ""\n return os.path.join(VENDORED_ROOT, project)\n\n\ndef iter_project_files(project, relative=False, **kwargs):\n """Yield (dirname, basename, filename) for all files in the project."""\n if relative:\n with _util.cwd(VENDORED_ROOT):\n for result in _util.iter_all_files(project, **kwargs):\n yield result\n else:\n root = project_root(project)\n for result in _util.iter_all_files(root, **kwargs):\n yield result\n\n\ndef iter_packaging_files(project):\n """Yield the filenames for all files in the project.\n\n The filenames are relative to "debugpy/_vendored". This is most\n useful for the "package data" in a setup.py.\n """\n # TODO: Use default filters? __pycache__ and .pyc?\n prune_dir = None\n exclude_file = None\n try:\n mod = import_module("._{}_packaging".format(project), __name__)\n except ImportError:\n pass\n else:\n prune_dir = getattr(mod, "prune_dir", prune_dir)\n exclude_file = getattr(mod, "exclude_file", exclude_file)\n results = iter_project_files(\n project, relative=True, prune_dir=prune_dir, exclude_file=exclude_file\n )\n for _, _, filename in results:\n yield filename\n\n\ndef prefix_matcher(*prefixes):\n """Return a module match func that matches any of the given prefixes."""\n assert prefixes\n\n def match(name, module):\n for prefix in prefixes:\n if name.startswith(prefix):\n return True\n else:\n return False\n\n return match\n\n\ndef check_modules(project, match, root=None):\n """Verify that only vendored modules have been imported."""\n if root is None:\n root = project_root(project)\n extensions = []\n unvendored = {}\n for modname, mod in list(sys.modules.items()):\n if not match(modname, mod):\n continue\n try:\n filename = getattr(mod, "__file__", None)\n except: # In theory it's possible that any error is raised when accessing __file__\n filename = None\n if not filename: # extension module\n extensions.append(modname)\n elif not filename.startswith(root):\n unvendored[modname] = filename\n return unvendored, extensions\n\n\n@contextlib.contextmanager\ndef vendored(project, root=None):\n """A context manager under which the vendored project will be imported."""\n if root is None:\n root = project_root(project)\n # Add the vendored project directory, so that it gets tried first.\n sys.path.insert(0, root)\n try:\n yield root\n finally:\n sys.path.remove(root)\n\n\ndef preimport(project, modules, **kwargs):\n """Import each of the named modules out of the vendored project."""\n with vendored(project, **kwargs):\n for name in modules:\n import_module(name)\n
|
.venv\Lib\site-packages\debugpy\_vendored\__init__.py
|
__init__.py
|
Python
| 4,004 | 0.95 | 0.261905 | 0.078431 |
react-lib
| 595 |
2025-03-22T09:16:59.856914
|
GPL-3.0
| false |
e9d7aeff93e64089e0c8dca35f667e74
|
from _pydevd_bundle.pydevd_constants import (\n get_frame,\n IS_CPYTHON,\n IS_64BIT_PROCESS,\n IS_WINDOWS,\n IS_LINUX,\n IS_MAC,\n DebugInfoHolder,\n LOAD_NATIVE_LIB_FLAG,\n ENV_FALSE_LOWER_VALUES,\n ForkSafeLock,\n PYDEVD_USE_SYS_MONITORING,\n)\nfrom _pydev_bundle._pydev_saved_modules import thread, threading\nfrom _pydev_bundle import pydev_log, pydev_monkey\nimport os.path\nimport platform\nimport ctypes\nfrom io import StringIO\nimport sys\nimport traceback\n\n_original_settrace = sys.settrace\n\n\nclass TracingFunctionHolder:\n """This class exists just to keep some variables (so that we don't keep them in the global namespace)."""\n\n _original_tracing = None\n _warn = True\n _traceback_limit = 1\n _warnings_shown = {}\n\n\ndef get_exception_traceback_str():\n exc_info = sys.exc_info()\n s = StringIO()\n traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s)\n return s.getvalue()\n\n\ndef _get_stack_str(frame):\n msg = (\n "\nIf this is needed, please check: "\n + "\nhttp://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html"\n + "\nto see how to restore the debug tracing back correctly.\n"\n )\n\n if TracingFunctionHolder._traceback_limit:\n s = StringIO()\n s.write("Call Location:\n")\n traceback.print_stack(f=frame, limit=TracingFunctionHolder._traceback_limit, file=s)\n msg = msg + s.getvalue()\n\n return msg\n\n\ndef _internal_set_trace(tracing_func):\n if PYDEVD_USE_SYS_MONITORING:\n raise RuntimeError("pydevd: Using sys.monitoring, sys.settrace should not be called.")\n if TracingFunctionHolder._warn:\n frame = get_frame()\n if frame is not None and frame.f_back is not None:\n filename = os.path.splitext(frame.f_back.f_code.co_filename.lower())[0]\n if filename.endswith("threadpool") and "gevent" in filename:\n if tracing_func is None:\n pydev_log.debug("Disabled internal sys.settrace from gevent threadpool.")\n return\n\n elif not filename.endswith(\n (\n "threading",\n "pydevd_tracing",\n )\n ):\n message = (\n "\nPYDEV DEBUGGER WARNING:"\n + "\nsys.settrace() should not be used when the debugger is being used."\n + "\nThis may cause the debugger to stop working correctly."\n + "%s" % _get_stack_str(frame.f_back)\n )\n\n if message not in TracingFunctionHolder._warnings_shown:\n # only warn about each message once...\n TracingFunctionHolder._warnings_shown[message] = 1\n sys.stderr.write("%s\n" % (message,))\n sys.stderr.flush()\n\n if TracingFunctionHolder._original_tracing:\n TracingFunctionHolder._original_tracing(tracing_func)\n\n\n_last_tracing_func_thread_local = threading.local()\n\n\ndef SetTrace(tracing_func):\n if PYDEVD_USE_SYS_MONITORING:\n raise RuntimeError("SetTrace should not be used when using sys.monitoring.")\n _last_tracing_func_thread_local.tracing_func = tracing_func\n\n if tracing_func is not None:\n if set_trace_to_threads(tracing_func, thread_idents=[thread.get_ident()], create_dummy_thread=False) == 0:\n # If we can use our own tracer instead of the one from sys.settrace, do it (the reason\n # is that this is faster than the Python version because we don't call\n # PyFrame_FastToLocalsWithError and PyFrame_LocalsToFast at each event!\n # (the difference can be huge when checking line events on frames as the\n # time increases based on the number of local variables in the scope)\n # See: InternalCallTrampoline (on the C side) for details.\n return\n\n # If it didn't work (or if it was None), use the Python version.\n set_trace = TracingFunctionHolder._original_tracing or sys.settrace\n set_trace(tracing_func)\n\n\ndef reapply_settrace():\n try:\n tracing_func = _last_tracing_func_thread_local.tracing_func\n except AttributeError:\n return\n else:\n SetTrace(tracing_func)\n\n\ndef replace_sys_set_trace_func():\n if PYDEVD_USE_SYS_MONITORING:\n return\n if TracingFunctionHolder._original_tracing is None:\n TracingFunctionHolder._original_tracing = sys.settrace\n sys.settrace = _internal_set_trace\n\n\ndef restore_sys_set_trace_func():\n if PYDEVD_USE_SYS_MONITORING:\n return\n if TracingFunctionHolder._original_tracing is not None:\n sys.settrace = TracingFunctionHolder._original_tracing\n TracingFunctionHolder._original_tracing = None\n\n\n_lock = ForkSafeLock()\n\n\ndef _load_python_helper_lib():\n try:\n # If it's already loaded, just return it.\n return _load_python_helper_lib.__lib__\n except AttributeError:\n pass\n with _lock:\n try:\n return _load_python_helper_lib.__lib__\n except AttributeError:\n pass\n\n lib = _load_python_helper_lib_uncached()\n _load_python_helper_lib.__lib__ = lib\n return lib\n\n\ndef get_python_helper_lib_filename():\n # Note: we have an independent (and similar -- but not equal) version of this method in\n # `add_code_to_python_process.py` which should be kept synchronized with this one (we do a copy\n # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the\n # debugger -- the only situation where it's imported is if the user actually does an attach to\n # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly\n # and not from the debugger).\n libdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pydevd_attach_to_process")\n\n if not os.path.exists(libdir):\n pydev_log.critical("Expected the directory: %s to exist!", libdir)\n\n arch = ""\n if IS_WINDOWS:\n # prefer not using platform.machine() when possible (it's a bit heavyweight as it may\n # spawn a subprocess).\n arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get("PROCESSOR_ARCHITECTURE", ""))\n\n if not arch:\n arch = platform.machine()\n if not arch:\n pydev_log.info("platform.machine() did not return valid value.") # This shouldn't happen...\n return None\n\n if IS_WINDOWS:\n extension = ".dll"\n suffix_64 = "amd64"\n suffix_32 = "x86"\n\n elif IS_LINUX:\n extension = ".so"\n suffix_64 = "amd64"\n suffix_32 = "x86"\n\n elif IS_MAC:\n extension = ".dylib"\n suffix_64 = "x86_64"\n suffix_32 = "x86"\n\n else:\n pydev_log.info("Unable to set trace to all threads in platform: %s", sys.platform)\n return None\n\n if arch.lower() not in ("amd64", "x86", "x86_64", "i386", "x86"):\n # We don't support this processor by default. Still, let's support the case where the\n # user manually compiled it himself with some heuristics.\n #\n # Ideally the user would provide a library in the format: "attach_<arch>.<extension>"\n # based on the way it's currently compiled -- see:\n # - windows/compile_windows.bat\n # - linux_and_mac/compile_linux.sh\n # - linux_and_mac/compile_mac.sh\n\n try:\n found = [name for name in os.listdir(libdir) if name.startswith("attach_") and name.endswith(extension)]\n except:\n if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:\n # There is no need to show this unless debug tracing is enabled.\n pydev_log.exception("Error listing dir: %s", libdir)\n return None\n\n expected_name = "attach_" + arch + extension\n expected_name_linux = "attach_linux_" + arch + extension\n\n filename = None\n if expected_name in found: # Heuristic: user compiled with "attach_<arch>.<extension>"\n filename = os.path.join(libdir, expected_name)\n\n elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_<arch>.<extension>"\n filename = os.path.join(libdir, expected_name_linux)\n\n elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib.\n filename = os.path.join(libdir, found[0])\n\n else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one.\n filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))]\n if len(filtered) == 1: # If more than one is available we can't be sure...\n filename = os.path.join(libdir, found[0])\n\n if filename is None:\n pydev_log.info("Unable to set trace to all threads in arch: %s (did not find a %s lib in %s).", arch, expected_name, libdir)\n return None\n\n pydev_log.info("Using %s lib in arch: %s.", filename, arch)\n\n else:\n # Happy path for which we have pre-compiled binaries.\n if IS_64BIT_PROCESS:\n suffix = suffix_64\n else:\n suffix = suffix_32\n\n if IS_WINDOWS or IS_MAC: # just the extension changes\n prefix = "attach_"\n elif IS_LINUX: #\n prefix = "attach_linux_" # historically it has a different name\n else:\n pydev_log.info("Unable to set trace to all threads in platform: %s", sys.platform)\n return None\n\n filename = os.path.join(libdir, "%s%s%s" % (prefix, suffix, extension))\n\n if not os.path.exists(filename):\n pydev_log.critical("Expected: %s to exist.", filename)\n return None\n\n return filename\n\n\ndef _load_python_helper_lib_uncached():\n if (\n not IS_CPYTHON\n or sys.version_info[:2] > (3, 11)\n or hasattr(sys, "gettotalrefcount")\n or LOAD_NATIVE_LIB_FLAG in ENV_FALSE_LOWER_VALUES\n ):\n pydev_log.info("Helper lib to set tracing to all threads not loaded.")\n return None\n\n try:\n filename = get_python_helper_lib_filename()\n if filename is None:\n return None\n # Load as pydll so that we don't release the gil.\n lib = ctypes.pydll.LoadLibrary(filename)\n pydev_log.info("Successfully Loaded helper lib to set tracing to all threads.")\n return lib\n except:\n if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:\n # Only show message if tracing is on (we don't have pre-compiled\n # binaries for all architectures -- i.e.: ARM).\n pydev_log.exception("Error loading: %s", filename)\n return None\n\n\ndef set_trace_to_threads(tracing_func, thread_idents=None, create_dummy_thread=True):\n if PYDEVD_USE_SYS_MONITORING:\n raise RuntimeError("Should not be called when using sys.monitoring.")\n assert tracing_func is not None\n\n ret = 0\n\n # Note: use sys._current_frames() keys to get the thread ids because it'll return\n # thread ids created in C/C++ where there's user code running, unlike the APIs\n # from the threading module which see only threads created through it (unless\n # a call for threading.current_thread() was previously done in that thread,\n # in which case a dummy thread would've been created for it).\n if thread_idents is None:\n thread_idents = set(sys._current_frames().keys())\n\n for t in threading.enumerate():\n # PY-44778: ignore pydevd threads and also add any thread that wasn't found on\n # sys._current_frames() as some existing threads may not appear in\n # sys._current_frames() but may be available through the `threading` module.\n if getattr(t, "pydev_do_not_trace", False):\n thread_idents.discard(t.ident)\n else:\n thread_idents.add(t.ident)\n\n curr_ident = thread.get_ident()\n curr_thread = threading._active.get(curr_ident)\n\n if curr_ident in thread_idents and len(thread_idents) != 1:\n # The current thread must be updated first (because we need to set\n # the reference to `curr_thread`).\n thread_idents = list(thread_idents)\n thread_idents.remove(curr_ident)\n thread_idents.insert(0, curr_ident)\n\n for thread_ident in thread_idents:\n # If that thread is not available in the threading module we also need to create a\n # dummy thread for it (otherwise it'll be invisible to the debugger).\n if create_dummy_thread:\n if thread_ident not in threading._active:\n\n class _DummyThread(threading._DummyThread):\n def _set_ident(self):\n # Note: Hack to set the thread ident that we want.\n self._ident = thread_ident\n\n t = _DummyThread()\n # Reset to the base class (don't expose our own version of the class).\n t.__class__ = threading._DummyThread\n\n if thread_ident == curr_ident:\n curr_thread = t\n\n with threading._active_limbo_lock:\n # On Py2 it'll put in active getting the current indent, not using the\n # ident that was set, so, we have to update it (should be harmless on Py3\n # so, do it always).\n threading._active[thread_ident] = t\n threading._active[curr_ident] = curr_thread\n\n if t.ident != thread_ident:\n # Check if it actually worked.\n pydev_log.critical("pydevd: creation of _DummyThread with fixed thread ident did not succeed.")\n\n # Some (ptvsd) tests failed because of this, so, leave it always disabled for now.\n # show_debug_info = 1 if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1 else 0\n show_debug_info = 0\n\n # Hack to increase _Py_TracingPossible.\n # See comments on py_custom_pyeval_settrace.hpp\n proceed = thread.allocate_lock()\n proceed.acquire()\n\n def dummy_trace(frame, event, arg):\n return dummy_trace\n\n def increase_tracing_count():\n set_trace = TracingFunctionHolder._original_tracing or sys.settrace\n set_trace(dummy_trace)\n proceed.release()\n\n start_new_thread = pydev_monkey.get_original_start_new_thread(thread)\n start_new_thread(increase_tracing_count, ())\n proceed.acquire() # Only proceed after the release() is done.\n proceed = None\n\n # Note: The set_trace_func is not really used anymore in the C side.\n set_trace_func = TracingFunctionHolder._original_tracing or sys.settrace\n\n lib = _load_python_helper_lib()\n if lib is None: # This is the case if it's not CPython.\n pydev_log.info("Unable to load helper lib to set tracing to all threads (unsupported python vm).")\n ret = -1\n else:\n try:\n result = lib.AttachDebuggerTracing(\n ctypes.c_int(show_debug_info),\n ctypes.py_object(set_trace_func),\n ctypes.py_object(tracing_func),\n ctypes.c_uint(thread_ident),\n ctypes.py_object(None),\n )\n except:\n if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:\n # There is no need to show this unless debug tracing is enabled.\n pydev_log.exception("Error attaching debugger tracing")\n ret = -1\n else:\n if result != 0:\n pydev_log.info("Unable to set tracing for existing thread. Result: %s", result)\n ret = result\n\n return ret\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_tracing.py
|
pydevd_tracing.py
|
Python
| 16,186 | 0.95 | 0.213759 | 0.164634 |
vue-tools
| 586 |
2024-01-04T03:16:20.522825
|
Apache-2.0
| false |
3395a6046902ce613481958b6034781c
|
"""\nEntry point module to run code-coverage.\n"""\n\n\ndef is_valid_py_file(path):\n """\n Checks whether the file can be read by the coverage module. This is especially\n needed for .pyx files and .py files with syntax errors.\n """\n import os\n\n is_valid = False\n if os.path.isfile(path) and not os.path.splitext(path)[1] == ".pyx":\n try:\n with open(path, "rb") as f:\n compile(f.read(), path, "exec")\n is_valid = True\n except:\n pass\n return is_valid\n\n\ndef execute():\n import os\n import sys\n\n files = None\n if "combine" not in sys.argv:\n if "--pydev-analyze" in sys.argv:\n # Ok, what we want here is having the files passed through stdin (because\n # there may be too many files for passing in the command line -- we could\n # just pass a dir and make the find files here, but as that's already\n # given in the java side, let's just gather that info here).\n sys.argv.remove("--pydev-analyze")\n s = input()\n s = s.replace("\r", "")\n s = s.replace("\n", "")\n\n files = []\n invalid_files = []\n for v in s.split("|"):\n if is_valid_py_file(v):\n files.append(v)\n else:\n invalid_files.append(v)\n if invalid_files:\n sys.stderr.write("Invalid files not passed to coverage: %s\n" % ", ".join(invalid_files))\n\n # Note that in this case we'll already be in the working dir with the coverage files,\n # so, the coverage file location is not passed.\n\n else:\n # For all commands, the coverage file is configured in pydev, and passed as the first\n # argument in the command line, so, let's make sure this gets to the coverage module.\n os.environ["COVERAGE_FILE"] = sys.argv[1]\n del sys.argv[1]\n\n try:\n import coverage # @UnresolvedImport\n except:\n sys.stderr.write("Error: coverage module could not be imported\n")\n sys.stderr.write("Please make sure that the coverage module " "(http://nedbatchelder.com/code/coverage/)\n")\n sys.stderr.write("is properly installed in your interpreter: %s\n" % (sys.executable,))\n\n import traceback\n\n traceback.print_exc()\n return\n\n if hasattr(coverage, "__version__"):\n version = tuple(map(int, coverage.__version__.split(".")[:2]))\n if version < (4, 3):\n sys.stderr.write(\n "Error: minimum supported coverage version is 4.3."\n "\nFound: %s\nLocation: %s\n" % (".".join(str(x) for x in version), coverage.__file__)\n )\n sys.exit(1)\n else:\n sys.stderr.write("Warning: Could not determine version of python module coverage." "\nEnsure coverage version is >= 4.3\n")\n\n from coverage.cmdline import main # @UnresolvedImport\n\n if files is not None:\n sys.argv.append("xml")\n sys.argv += files\n\n main()\n\n\nif __name__ == "__main__":\n execute()\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydev_coverage.py
|
pydev_coverage.py
|
Python
| 3,204 | 0.95 | 0.184783 | 0.108108 |
node-utils
| 601 |
2024-12-20T00:54:25.090528
|
Apache-2.0
| false |
c389673a00735b8fe4336146b8e5b29f
|
"""An empty file in pysrc that can be imported (from sitecustomize) to find the location of pysrc"""\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydev_pysrc.py
|
pydev_pysrc.py
|
Python
| 102 | 0.85 | 0 | 0 |
node-utils
| 473 |
2025-01-31T10:53:24.412839
|
BSD-3-Clause
| false |
ce440e2e6a21f587124f3ff035fea672
|
"""\nEntry point module to run a file in the interactive console.\n"""\nimport os\nimport sys\nimport traceback\nfrom pydevconsole import InterpreterInterface, process_exec_queue, start_console_server, init_mpl_in_console\nfrom _pydev_bundle._pydev_saved_modules import threading, _queue\n\nfrom _pydev_bundle import pydev_imports\nfrom _pydevd_bundle.pydevd_utils import save_main_module\nfrom _pydev_bundle.pydev_console_utils import StdIn\nfrom pydevd_file_utils import get_fullname\n\n\ndef run_file(file, globals=None, locals=None, is_module=False):\n module_name = None\n entry_point_fn = None\n if is_module:\n file, _, entry_point_fn = file.partition(":")\n module_name = file\n filename = get_fullname(file)\n if filename is None:\n sys.stderr.write("No module named %s\n" % file)\n return\n else:\n file = filename\n\n if os.path.isdir(file):\n new_target = os.path.join(file, "__main__.py")\n if os.path.isfile(new_target):\n file = new_target\n\n if globals is None:\n m = save_main_module(file, "pydev_run_in_console")\n\n globals = m.__dict__\n try:\n globals["__builtins__"] = __builtins__\n except NameError:\n pass # Not there on Jython...\n\n if locals is None:\n locals = globals\n\n if not is_module:\n sys.path.insert(0, os.path.split(file)[0])\n\n print("Running %s" % file)\n try:\n if not is_module:\n pydev_imports.execfile(file, globals, locals) # execute the script\n else:\n # treat ':' as a seperator between module and entry point function\n # if there is no entry point we run we same as with -m switch. Otherwise we perform\n # an import and execute the entry point\n if entry_point_fn:\n mod = __import__(module_name, level=0, fromlist=[entry_point_fn], globals=globals, locals=locals)\n func = getattr(mod, entry_point_fn)\n func()\n else:\n # Run with the -m switch\n from _pydevd_bundle import pydevd_runpy\n\n pydevd_runpy._run_module_as_main(module_name)\n except:\n traceback.print_exc()\n\n return globals\n\n\ndef skip_successful_exit(*args):\n """System exit in file shouldn't kill interpreter (i.e. in `timeit`)"""\n if len(args) == 1 and args[0] in (0, None):\n pass\n else:\n raise SystemExit(*args)\n\n\ndef process_args(argv):\n setup_args = {"file": "", "module": False}\n\n setup_args["port"] = argv[1]\n del argv[1]\n setup_args["client_port"] = argv[1]\n del argv[1]\n\n module_flag = "--module"\n if module_flag in argv:\n i = argv.index(module_flag)\n if i != -1:\n setup_args["module"] = True\n setup_args["file"] = argv[i + 1]\n del sys.argv[i]\n else:\n setup_args["file"] = argv[1]\n\n del argv[0]\n\n return setup_args\n\n\n# =======================================================================================================================\n# main\n# =======================================================================================================================\nif __name__ == "__main__":\n setup = process_args(sys.argv)\n\n port = setup["port"]\n client_port = setup["client_port"]\n file = setup["file"]\n is_module = setup["module"]\n\n from _pydev_bundle import pydev_localhost\n\n if int(port) == 0 and int(client_port) == 0:\n (h, p) = pydev_localhost.get_socket_name()\n client_port = p\n\n host = pydev_localhost.get_localhost()\n\n # replace exit (see comments on method)\n # note that this does not work in jython!!! (sys method can't be replaced).\n sys.exit = skip_successful_exit\n\n connect_status_queue = _queue.Queue()\n interpreter = InterpreterInterface(host, int(client_port), threading.current_thread(), connect_status_queue=connect_status_queue)\n\n server_thread = threading.Thread(target=start_console_server, name="ServerThread", args=(host, int(port), interpreter))\n server_thread.daemon = True\n server_thread.start()\n\n sys.stdin = StdIn(interpreter, host, client_port, sys.stdin)\n\n init_mpl_in_console(interpreter)\n\n try:\n success = connect_status_queue.get(True, 60)\n if not success:\n raise ValueError()\n except:\n sys.stderr.write("Console server didn't start\n")\n sys.stderr.flush()\n sys.exit(1)\n\n globals = run_file(file, None, None, is_module)\n\n interpreter.get_namespace().update(globals)\n\n interpreter.ShowConsole()\n\n process_exec_queue(interpreter)\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydev_run_in_console.py
|
pydev_run_in_console.py
|
Python
| 4,789 | 0.95 | 0.164474 | 0.076923 |
python-kit
| 793 |
2023-12-13T15:34:14.787093
|
GPL-3.0
| false |
119be8711a2c17e985b8ced184d2debd
|
r"""\nCopyright: Brainwy Software Ltda.\n\nLicense: EPL.\n=============\n\nWorks for Windows by using an executable that'll inject a dll to a process and call a function.\n\nNote: https://github.com/fabioz/winappdbg is used just to determine if the target process is 32 or 64 bits.\n\nWorks for Linux relying on gdb.\n\nLimitations:\n============\n\n Linux:\n ------\n\n 1. It possible that ptrace is disabled: /etc/sysctl.d/10-ptrace.conf\n\n Note that even enabling it in /etc/sysctl.d/10-ptrace.conf (i.e.: making the\n ptrace_scope=0), it's possible that we need to run the application that'll use ptrace (or\n gdb in this case) as root (so, we must sudo the python which'll run this module).\n\n 2. It currently doesn't work in debug builds (i.e.: python_d)\n\n\nOther implementations:\n- pyrasite.com:\n GPL\n Windows/linux (in Linux it also uses gdb to connect -- although specifics are different as we use a dll to execute\n code with other threads stopped). It's Windows approach is more limited because it doesn't seem to deal properly with\n Python 3 if threading is disabled.\n\n- https://github.com/google/pyringe:\n Apache v2.\n Only linux/Python 2.\n\n- http://pytools.codeplex.com:\n Apache V2\n Windows Only (but supports mixed mode debugging)\n Our own code relies heavily on a part of it: http://pytools.codeplex.com/SourceControl/latest#Python/Product/PyDebugAttach/PyDebugAttach.cpp\n to overcome some limitations of attaching and running code in the target python executable on Python 3.\n See: attach.cpp\n\nLinux: References if we wanted to use a pure-python debugger:\n https://bitbucket.org/haypo/python-ptrace/\n http://stackoverflow.com/questions/7841573/how-to-get-an-error-message-for-errno-value-in-python\n Jugaad:\n https://www.defcon.org/images/defcon-19/dc-19-presentations/Jakhar/DEFCON-19-Jakhar-Jugaad-Linux-Thread-Injection.pdf\n https://github.com/aseemjakhar/jugaad\n\nSomething else (general and not Python related):\n- http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces\n\nOther references:\n- https://github.com/haypo/faulthandler\n- http://nedbatchelder.com/text/trace-function.html\n- https://github.com/python-git/python/blob/master/Python/sysmodule.c (sys_settrace)\n- https://github.com/python-git/python/blob/master/Python/ceval.c (PyEval_SetTrace)\n- https://github.com/python-git/python/blob/master/Python/thread.c (PyThread_get_key_value)\n\n\nTo build the dlls needed on windows, visual studio express 13 was used (see compile_dll.bat)\n\nSee: attach_pydevd.py to attach the pydev debugger to a running python process.\n"""\n\n# Note: to work with nasm compiling asm to code and decompiling to see asm with shellcode:\n# x:\nasm\nasm-2.07-win32\nasm-2.07\nasm.exe\n# nasm.asm&x:\nasm\nasm-2.07-win32\nasm-2.07\ndisasm.exe -b arch nasm\nimport ctypes\nimport os\nimport struct\nimport subprocess\nimport sys\nimport time\nfrom contextlib import contextmanager\nimport platform\nimport traceback\n\ntry:\n TimeoutError = TimeoutError # @ReservedAssignment\nexcept NameError:\n\n class TimeoutError(RuntimeError): # @ReservedAssignment\n pass\n\n\n@contextmanager\ndef _create_win_event(name):\n from winappdbg.win32.kernel32 import CreateEventA, WaitForSingleObject, CloseHandle\n\n manual_reset = False # i.e.: after someone waits it, automatically set to False.\n initial_state = False\n if not isinstance(name, bytes):\n name = name.encode("utf-8")\n event = CreateEventA(None, manual_reset, initial_state, name)\n if not event:\n raise ctypes.WinError()\n\n class _WinEvent(object):\n def wait_for_event_set(self, timeout=None):\n """\n :param timeout: in seconds\n """\n if timeout is None:\n timeout = 0xFFFFFFFF\n else:\n timeout = int(timeout * 1000)\n ret = WaitForSingleObject(event, timeout)\n if ret in (0, 0x80):\n return True\n elif ret == 0x102:\n # Timed out\n return False\n else:\n raise ctypes.WinError()\n\n try:\n yield _WinEvent()\n finally:\n CloseHandle(event)\n\n\nIS_WINDOWS = sys.platform == "win32"\nIS_LINUX = sys.platform in ("linux", "linux2")\nIS_MAC = sys.platform == "darwin"\n\n\ndef is_python_64bit():\n return struct.calcsize("P") == 8\n\n\ndef get_target_filename(is_target_process_64=None, prefix=None, extension=None):\n # Note: we have an independent (and similar -- but not equal) version of this method in\n # `pydevd_tracing.py` which should be kept synchronized with this one (we do a copy\n # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the\n # debugger -- the only situation where it's imported is if the user actually does an attach to\n # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly\n # and not from the debugger).\n libdir = os.path.dirname(os.path.abspath(__file__))\n\n if is_target_process_64 is None:\n if IS_WINDOWS:\n # i.e.: On windows the target process could have a different bitness (32bit is emulated on 64bit).\n raise AssertionError("On windows it's expected that the target bitness is specified.")\n\n # For other platforms, just use the the same bitness of the process we're running in.\n is_target_process_64 = is_python_64bit()\n\n arch = ""\n if IS_WINDOWS:\n # prefer not using platform.machine() when possible (it's a bit heavyweight as it may\n # spawn a subprocess).\n arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get("PROCESSOR_ARCHITECTURE", ""))\n\n if not arch:\n arch = platform.machine()\n if not arch:\n print("platform.machine() did not return valid value.") # This shouldn't happen...\n return None\n\n if IS_WINDOWS:\n if not extension:\n extension = ".dll"\n suffix_64 = "amd64"\n suffix_32 = "x86"\n\n elif IS_LINUX:\n if not extension:\n extension = ".so"\n suffix_64 = "amd64"\n suffix_32 = "x86"\n\n elif IS_MAC:\n if not extension:\n extension = ".dylib"\n suffix_64 = "x86_64"\n suffix_32 = "x86"\n\n else:\n print("Unable to attach to process in platform: %s", sys.platform)\n return None\n\n if arch.lower() not in ("amd64", "x86", "x86_64", "i386", "x86"):\n # We don't support this processor by default. Still, let's support the case where the\n # user manually compiled it himself with some heuristics.\n #\n # Ideally the user would provide a library in the format: "attach_<arch>.<extension>"\n # based on the way it's currently compiled -- see:\n # - windows/compile_windows.bat\n # - linux_and_mac/compile_linux.sh\n # - linux_and_mac/compile_mac.sh\n\n try:\n found = [name for name in os.listdir(libdir) if name.startswith("attach_") and name.endswith(extension)]\n except:\n print("Error listing dir: %s" % (libdir,))\n traceback.print_exc()\n return None\n\n if prefix:\n expected_name = prefix + arch + extension\n expected_name_linux = prefix + "linux_" + arch + extension\n else:\n # Default is looking for the attach_ / attach_linux\n expected_name = "attach_" + arch + extension\n expected_name_linux = "attach_linux_" + arch + extension\n\n filename = None\n if expected_name in found: # Heuristic: user compiled with "attach_<arch>.<extension>"\n filename = os.path.join(libdir, expected_name)\n\n elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_<arch>.<extension>"\n filename = os.path.join(libdir, expected_name_linux)\n\n elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib.\n filename = os.path.join(libdir, found[0])\n\n else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one.\n filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))]\n if len(filtered) == 1: # If more than one is available we can't be sure...\n filename = os.path.join(libdir, found[0])\n\n if filename is None:\n print("Unable to attach to process in arch: %s (did not find %s in %s)." % (arch, expected_name, libdir))\n return None\n\n print("Using %s in arch: %s." % (filename, arch))\n\n else:\n if is_target_process_64:\n suffix = suffix_64\n else:\n suffix = suffix_32\n\n if not prefix:\n # Default is looking for the attach_ / attach_linux\n if IS_WINDOWS or IS_MAC: # just the extension changes\n prefix = "attach_"\n elif IS_LINUX:\n prefix = "attach_linux_" # historically it has a different name\n else:\n print("Unable to attach to process in platform: %s" % (sys.platform,))\n return None\n\n filename = os.path.join(libdir, "%s%s%s" % (prefix, suffix, extension))\n\n if not os.path.exists(filename):\n print("Expected: %s to exist." % (filename,))\n return None\n\n return filename\n\n\ndef run_python_code_windows(pid, python_code, connect_debugger_tracing=False, show_debug_info=0):\n assert "'" not in python_code, "Having a single quote messes with our command."\n\n # Suppress winappdbg warning about sql package missing.\n import warnings\n\n with warnings.catch_warnings():\n warnings.simplefilter("ignore", category=ImportWarning)\n from winappdbg.process import Process\n\n if not isinstance(python_code, bytes):\n python_code = python_code.encode("utf-8")\n\n process = Process(pid)\n bits = process.get_bits()\n is_target_process_64 = bits == 64\n\n # Note: this restriction no longer applies (we create a process with the proper bitness from\n # this process so that the attach works).\n # if is_target_process_64 != is_python_64bit():\n # raise RuntimeError("The architecture of the Python used to connect doesn't match the architecture of the target.\n"\n # "Target 64 bits: %s\n"\n # "Current Python 64 bits: %s" % (is_target_process_64, is_python_64bit()))\n\n with _acquire_mutex("_pydevd_pid_attach_mutex_%s" % (pid,), 10):\n print("--- Connecting to %s bits target (current process is: %s) ---" % (bits, 64 if is_python_64bit() else 32))\n sys.stdout.flush()\n\n with _win_write_to_shared_named_memory(python_code, pid):\n target_executable = get_target_filename(is_target_process_64, "inject_dll_", ".exe")\n if not target_executable:\n raise RuntimeError("Could not find expected .exe file to inject dll in attach to process.")\n\n target_dll = get_target_filename(is_target_process_64)\n if not target_dll:\n raise RuntimeError("Could not find expected .dll file in attach to process.")\n\n print("\n--- Injecting attach dll: %s into pid: %s ---" % (os.path.basename(target_dll), pid))\n sys.stdout.flush()\n args = [target_executable, str(pid), target_dll]\n subprocess.check_call(args)\n\n # Now, if the first injection worked, go on to the second which will actually\n # run the code.\n target_dll_run_on_dllmain = get_target_filename(is_target_process_64, "run_code_on_dllmain_", ".dll")\n if not target_dll_run_on_dllmain:\n raise RuntimeError("Could not find expected .dll in attach to process.")\n\n with _create_win_event("_pydevd_pid_event_%s" % (pid,)) as event:\n print("\n--- Injecting run code dll: %s into pid: %s ---" % (os.path.basename(target_dll_run_on_dllmain), pid))\n sys.stdout.flush()\n args = [target_executable, str(pid), target_dll_run_on_dllmain]\n subprocess.check_call(args)\n\n if not event.wait_for_event_set(15):\n print("Timeout error: the attach may not have completed.")\n sys.stdout.flush()\n print("--- Finished dll injection ---\n")\n sys.stdout.flush()\n\n return 0\n\n\n@contextmanager\ndef _acquire_mutex(mutex_name, timeout):\n """\n Only one process may be attaching to a pid, so, create a system mutex\n to make sure this holds in practice.\n """\n from winappdbg.win32.kernel32 import CreateMutex, GetLastError, CloseHandle\n from winappdbg.win32.defines import ERROR_ALREADY_EXISTS\n\n initial_time = time.time()\n while True:\n mutex = CreateMutex(None, True, mutex_name)\n acquired = GetLastError() != ERROR_ALREADY_EXISTS\n if acquired:\n break\n if time.time() - initial_time > timeout:\n raise TimeoutError("Unable to acquire mutex to make attach before timeout.")\n time.sleep(0.2)\n\n try:\n yield\n finally:\n CloseHandle(mutex)\n\n\n@contextmanager\ndef _win_write_to_shared_named_memory(python_code, pid):\n # Use the definitions from winappdbg when possible.\n from winappdbg.win32 import defines\n from winappdbg.win32.kernel32 import (\n CreateFileMapping,\n MapViewOfFile,\n CloseHandle,\n UnmapViewOfFile,\n )\n\n memmove = ctypes.cdll.msvcrt.memmove\n memmove.argtypes = [\n ctypes.c_void_p,\n ctypes.c_void_p,\n defines.SIZE_T,\n ]\n memmove.restype = ctypes.c_void_p\n\n # Note: BUFSIZE must be the same from run_code_in_memory.hpp\n BUFSIZE = 2048\n assert isinstance(python_code, bytes)\n assert len(python_code) > 0, "Python code must not be empty."\n # Note: -1 so that we're sure we'll add a \0 to the end.\n assert len(python_code) < BUFSIZE - 1, "Python code must have at most %s bytes (found: %s)" % (BUFSIZE - 1, len(python_code))\n\n python_code += b"\0" * (BUFSIZE - len(python_code))\n assert python_code.endswith(b"\0")\n\n INVALID_HANDLE_VALUE = -1\n PAGE_READWRITE = 0x4\n FILE_MAP_WRITE = 0x2\n filemap = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, BUFSIZE, "__pydevd_pid_code_to_run__%s" % (pid,))\n\n if filemap == INVALID_HANDLE_VALUE or filemap is None:\n raise Exception("Failed to create named file mapping (ctypes: CreateFileMapping): %s" % (filemap,))\n try:\n view = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0)\n if not view:\n raise Exception("Failed to create view of named file mapping (ctypes: MapViewOfFile).")\n\n try:\n memmove(view, python_code, BUFSIZE)\n yield\n finally:\n UnmapViewOfFile(view)\n finally:\n CloseHandle(filemap)\n\n\ndef run_python_code_linux(pid, python_code, connect_debugger_tracing=False, show_debug_info=0):\n assert "'" not in python_code, "Having a single quote messes with our command."\n\n target_dll = get_target_filename()\n if not target_dll:\n libdir = os.path.dirname(os.path.abspath(__file__))\n found = [name for name in os.listdir(libdir)]\n raise RuntimeError(\n "Could not find .so for attach to process.\nlibdir: %s\nAvailable in dir: %s"\n % (\n libdir,\n found,\n )\n )\n target_dll_name = os.path.splitext(os.path.basename(target_dll))[0]\n\n # Note: we currently don't support debug builds\n is_debug = 0\n # Note that the space in the beginning of each line in the multi-line is important!\n cmd = [\n "gdb",\n "--nw", # no gui interface\n "--nh", # no ~/.gdbinit\n "--nx", # no .gdbinit\n # '--quiet', # no version number on startup\n "--pid",\n str(pid),\n "--batch",\n # '--batch-silent',\n ]\n\n # PYDEVD_GDB_SCAN_SHARED_LIBRARIES can be a list of strings with the shared libraries\n # which should be scanned by default to make the attach to process (i.e.: libdl, libltdl, libc, libfreebl3).\n #\n # The default is scanning all shared libraries, but on some cases this can be in the 20-30\n # seconds range for some corner cases.\n # See: https://github.com/JetBrains/intellij-community/pull/1608\n #\n # By setting PYDEVD_GDB_SCAN_SHARED_LIBRARIES (to a comma-separated string), it's possible to\n # specify just a few libraries to be loaded (not many are needed for the attach,\n # but it can be tricky to pre-specify for all Linux versions as this may change\n # across different versions).\n #\n # See: https://github.com/microsoft/debugpy/issues/762#issuecomment-947103844\n # for a comment that explains the basic steps on how to discover what should be available\n # in each case (mostly trying different versions based on the output of gdb).\n #\n # The upside is that for cases when too many libraries are loaded the attach could be slower\n # and just specifying the one that is actually needed for the attach can make it much faster.\n #\n # The downside is that it may be dependent on the Linux version being attached to (which is the\n # reason why this is no longer done by default -- see: https://github.com/microsoft/debugpy/issues/882).\n gdb_load_shared_libraries = os.environ.get("PYDEVD_GDB_SCAN_SHARED_LIBRARIES", "").strip()\n if gdb_load_shared_libraries:\n print("PYDEVD_GDB_SCAN_SHARED_LIBRARIES set: %s." % (gdb_load_shared_libraries,))\n cmd.extend(["--init-eval-command='set auto-solib-add off'"]) # Don't scan all libraries.\n\n for lib in gdb_load_shared_libraries.split(","):\n lib = lib.strip()\n cmd.extend(["--eval-command='sharedlibrary %s'" % (lib,)]) # Scan the specified library\n else:\n print("PYDEVD_GDB_SCAN_SHARED_LIBRARIES not set (scanning all libraries for needed symbols).")\n\n cmd.extend(["--eval-command='set scheduler-locking off'"]) # If on we'll deadlock.\n\n # Leave auto by default (it should do the right thing as we're attaching to a process in the\n # current host).\n cmd.extend(["--eval-command='set architecture auto'"])\n\n cmd.extend(\n [\n "--eval-command='call (void*)dlopen(\"%s\", 2)'" % target_dll,\n "--eval-command='sharedlibrary %s'" % target_dll_name,\n "--eval-command='call (int)DoAttach(%s, \"%s\", %s)'" % (is_debug, python_code, show_debug_info),\n ]\n )\n\n # print ' '.join(cmd)\n\n env = os.environ.copy()\n # Remove the PYTHONPATH (if gdb has a builtin Python it could fail if we\n # have the PYTHONPATH for a different python version or some forced encoding).\n env.pop("PYTHONIOENCODING", None)\n env.pop("PYTHONPATH", None)\n print("Running: %s" % (" ".join(cmd)))\n subprocess.check_call(" ".join(cmd), shell=True, env=env)\n\n\ndef find_helper_script(filedir, script_name):\n target_filename = os.path.join(filedir, "linux_and_mac", script_name)\n target_filename = os.path.normpath(target_filename)\n if not os.path.exists(target_filename):\n raise RuntimeError("Could not find helper script: %s" % target_filename)\n\n return target_filename\n\n\ndef run_python_code_mac(pid, python_code, connect_debugger_tracing=False, show_debug_info=0):\n assert "'" not in python_code, "Having a single quote messes with our command."\n\n target_dll = get_target_filename()\n if not target_dll:\n raise RuntimeError("Could not find .dylib for attach to process.")\n\n libdir = os.path.dirname(__file__)\n lldb_prepare_file = find_helper_script(libdir, "lldb_prepare.py")\n # Note: we currently don't support debug builds\n\n is_debug = 0\n # Note that the space in the beginning of each line in the multi-line is important!\n cmd = [\n "lldb",\n "--no-lldbinit", # Do not automatically parse any '.lldbinit' files.\n # '--attach-pid',\n # str(pid),\n # '--arch',\n # arch,\n "--script-language",\n "Python",\n # '--batch-silent',\n ]\n\n cmd.extend(\n [\n "-o 'process attach --pid %d'" % pid,\n "-o 'command script import \"%s\"'" % (lldb_prepare_file,),\n '-o \'load_lib_and_attach "%s" %s "%s" %s\'' % (target_dll, is_debug, python_code, show_debug_info),\n ]\n )\n\n cmd.extend(\n [\n "-o 'process detach'",\n "-o 'script import os; os._exit(1)'",\n ]\n )\n\n # print ' '.join(cmd)\n\n env = os.environ.copy()\n # Remove the PYTHONPATH (if lldb has a builtin Python it could fail if we\n # have the PYTHONPATH for a different python version or some forced encoding).\n env.pop("PYTHONIOENCODING", None)\n env.pop("PYTHONPATH", None)\n print("Running: %s" % (" ".join(cmd)))\n subprocess.check_call(" ".join(cmd), shell=True, env=env)\n\n\nif IS_WINDOWS:\n run_python_code = run_python_code_windows\nelif IS_MAC:\n run_python_code = run_python_code_mac\nelif IS_LINUX:\n run_python_code = run_python_code_linux\nelse:\n\n def run_python_code(*args, **kwargs):\n print("Unable to attach to process in platform: %s", sys.platform)\n\n\ndef test():\n print("Running with: %s" % (sys.executable,))\n code = """\nimport os, time, sys\nprint(os.getpid())\n#from threading import Thread\n#Thread(target=str).start()\nif __name__ == '__main__':\n while True:\n time.sleep(.5)\n sys.stdout.write('.\\n')\n sys.stdout.flush()\n"""\n\n p = subprocess.Popen([sys.executable, "-u", "-c", code])\n try:\n code = 'print("It worked!")\n'\n\n # Real code will be something as:\n # code = '''import sys;sys.path.append(r'X:\winappdbg-code\examples'); import imported;'''\n run_python_code(p.pid, python_code=code)\n print("\nRun a 2nd time...\n")\n run_python_code(p.pid, python_code=code)\n\n time.sleep(3)\n finally:\n p.kill()\n\n\ndef main(args):\n # Otherwise, assume the first parameter is the pid and anything else is code to be executed\n # in the target process.\n pid = int(args[0])\n del args[0]\n python_code = ";".join(args)\n\n # Note: on Linux the python code may not have a single quote char: '\n run_python_code(pid, python_code)\n\n\nif __name__ == "__main__":\n args = sys.argv[1:]\n if not args:\n print("Expected pid and Python code to execute in target process.")\n else:\n if "--test" == args[0]:\n test()\n else:\n main(args)\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\add_code_to_python_process.py
|
add_code_to_python_process.py
|
Python
| 23,194 | 0.95 | 0.164179 | 0.171134 |
awesome-app
| 940 |
2024-03-01T05:15:26.404349
|
Apache-2.0
| false |
6a4adb925fa2cf2872278cce7cdf4bf4
|
MZ
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\attach_amd64.dll
|
attach_amd64.dll
|
Other
| 48,688 | 0.95 | 0.011737 | 0.011848 |
awesome-app
| 574 |
2024-12-15T16:19:57.166867
|
MIT
| false |
2790d1eb87f74b95eeb8e33cf9a310a7
|
import sys\nimport os\n\n\ndef process_command_line(argv):\n setup = {}\n setup["port"] = 5678 # Default port for PyDev remote debugger\n setup["pid"] = 0\n setup["host"] = "127.0.0.1"\n setup["protocol"] = ""\n setup["debug-mode"] = ""\n\n i = 0\n while i < len(argv):\n if argv[i] == "--port":\n del argv[i]\n setup["port"] = int(argv[i])\n del argv[i]\n\n elif argv[i] == "--pid":\n del argv[i]\n setup["pid"] = int(argv[i])\n del argv[i]\n\n elif argv[i] == "--host":\n del argv[i]\n setup["host"] = argv[i]\n del argv[i]\n\n elif argv[i] == "--protocol":\n del argv[i]\n setup["protocol"] = argv[i]\n del argv[i]\n\n elif argv[i] == "--debug-mode":\n del argv[i]\n setup["debug-mode"] = argv[i]\n del argv[i]\n\n if not setup["pid"]:\n sys.stderr.write("Expected --pid to be passed.\n")\n sys.exit(1)\n return setup\n\n\ndef main(setup):\n sys.path.append(os.path.dirname(__file__))\n import add_code_to_python_process\n\n show_debug_info_on_target_process = 0\n\n pydevd_dirname = os.path.dirname(os.path.dirname(__file__))\n\n if sys.platform == "win32":\n setup["pythonpath"] = pydevd_dirname.replace("\\", "/")\n setup["pythonpath2"] = os.path.dirname(__file__).replace("\\", "/")\n python_code = (\n """import sys;\nsys.path.append("%(pythonpath)s");\nsys.path.append("%(pythonpath2)s");\nimport attach_script;\nattach_script.attach(port=%(port)s, host="%(host)s", protocol="%(protocol)s", debug_mode="%(debug-mode)s");\n""".replace("\r\n", "")\n .replace("\r", "")\n .replace("\n", "")\n )\n else:\n setup["pythonpath"] = pydevd_dirname\n setup["pythonpath2"] = os.path.dirname(__file__)\n # We have to pass it a bit differently for gdb\n python_code = (\n """import sys;\nsys.path.append(\\\"%(pythonpath)s\\\");\nsys.path.append(\\\"%(pythonpath2)s\\\");\nimport attach_script;\nattach_script.attach(port=%(port)s, host=\\\"%(host)s\\\", protocol=\\\"%(protocol)s\\\", debug_mode=\\\"%(debug-mode)s\\\");\n""".replace("\r\n", "")\n .replace("\r", "")\n .replace("\n", "")\n )\n\n python_code = python_code % setup\n add_code_to_python_process.run_python_code(\n setup["pid"], python_code, connect_debugger_tracing=True, show_debug_info=show_debug_info_on_target_process\n )\n\n\nif __name__ == "__main__":\n main(process_command_line(sys.argv[1:]))\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\attach_pydevd.py
|
attach_pydevd.py
|
Python
| 2,674 | 0.95 | 0.101124 | 0.013699 |
node-utils
| 613 |
2024-07-06T05:19:39.040714
|
Apache-2.0
| false |
ebf2ca8968989e1254b557cfce085743
|
def get_main_thread_instance(threading):\n if hasattr(threading, "main_thread"):\n return threading.main_thread()\n else:\n # On Python 2 we don't really have an API to get the main thread,\n # so, we just get it from the 'shutdown' bound method.\n return threading._shutdown.im_self\n\n\ndef get_main_thread_id(unlikely_thread_id=None):\n """\n :param unlikely_thread_id:\n Pass to mark some thread id as not likely the main thread.\n\n :return tuple(thread_id, critical_warning)\n """\n import sys\n import os\n\n current_frames = sys._current_frames()\n possible_thread_ids = []\n for thread_ident, frame in current_frames.items():\n while frame.f_back is not None:\n frame = frame.f_back\n\n basename = os.path.basename(frame.f_code.co_filename)\n if basename.endswith((".pyc", ".pyo")):\n basename = basename[:-1]\n\n if (frame.f_code.co_name, basename) in [\n ("_run_module_as_main", "runpy.py"),\n ("_run_module_as_main", "<frozen runpy>"),\n ("run_module_as_main", "runpy.py"),\n ("run_module", "runpy.py"),\n ("run_path", "runpy.py"),\n ]:\n # This is the case for python -m <module name> (this is an ideal match, so,\n # let's return it).\n return thread_ident, ""\n\n if frame.f_code.co_name == "<module>":\n if frame.f_globals.get("__name__") == "__main__":\n possible_thread_ids.insert(0, thread_ident) # Add with higher priority\n continue\n\n # Usually the main thread will be started in the <module>, whereas others would\n # be started in another place (but when Python is embedded, this may not be\n # correct, so, just add to the available possibilities as we'll have to choose\n # one if there are multiple).\n possible_thread_ids.append(thread_ident)\n\n if len(possible_thread_ids) > 0:\n if len(possible_thread_ids) == 1:\n return possible_thread_ids[0], "" # Ideal: only one match\n\n while unlikely_thread_id in possible_thread_ids:\n possible_thread_ids.remove(unlikely_thread_id)\n\n if len(possible_thread_ids) == 1:\n return possible_thread_ids[0], "" # Ideal: only one match\n\n elif len(possible_thread_ids) > 1:\n # Bad: we can't really be certain of anything at this point.\n return possible_thread_ids[0], "Multiple thread ids found (%s). Choosing main thread id randomly (%s)." % (\n possible_thread_ids,\n possible_thread_ids[0],\n )\n\n # If we got here we couldn't discover the main thread id.\n return None, "Unable to discover main thread id."\n\n\ndef fix_main_thread_id(on_warn=lambda msg: None, on_exception=lambda msg: None, on_critical=lambda msg: None):\n # This means that we weren't able to import threading in the main thread (which most\n # likely means that the main thread is paused or in some very long operation).\n # In this case we'll import threading here and hotfix what may be wrong in the threading\n # module (if we're on Windows where we create a thread to do the attach and on Linux\n # we are not certain on which thread we're executing this code).\n #\n # The code below is a workaround for https://bugs.python.org/issue37416\n import sys\n import threading\n\n # This is no longer needed in Py 3.13 (as the related issue is already fixed).\n if sys.version_info[:2] >= (3, 13):\n return\n\n try:\n with threading._active_limbo_lock:\n main_thread_instance = get_main_thread_instance(threading)\n\n if sys.platform == "win32":\n # On windows this code would be called in a secondary thread, so,\n # the current thread is unlikely to be the main thread.\n if hasattr(threading, "_get_ident"):\n unlikely_thread_id = threading._get_ident() # py2\n else:\n unlikely_thread_id = threading.get_ident() # py3\n else:\n unlikely_thread_id = None\n\n main_thread_id, critical_warning = get_main_thread_id(unlikely_thread_id)\n\n if main_thread_id is not None:\n main_thread_id_attr = "_ident"\n if not hasattr(main_thread_instance, main_thread_id_attr):\n main_thread_id_attr = "_Thread__ident"\n assert hasattr(main_thread_instance, main_thread_id_attr)\n\n if main_thread_id != getattr(main_thread_instance, main_thread_id_attr):\n # Note that we also have to reset the '_tstack_lock' for a regular lock.\n # This is needed to avoid an error on shutdown because this lock is bound\n # to the thread state and will be released when the secondary thread\n # that initialized the lock is finished -- making an assert fail during\n # process shutdown.\n main_thread_instance._tstate_lock = threading._allocate_lock()\n main_thread_instance._tstate_lock.acquire()\n\n # Actually patch the thread ident as well as the threading._active dict\n # (we should have the _active_limbo_lock to do that).\n threading._active.pop(getattr(main_thread_instance, main_thread_id_attr), None)\n setattr(main_thread_instance, main_thread_id_attr, main_thread_id)\n threading._active[getattr(main_thread_instance, main_thread_id_attr)] = main_thread_instance\n\n # Note: only import from pydevd after the patching is done (we want to do the minimum\n # possible when doing that patching).\n on_warn(\n "The threading module was not imported by user code in the main thread. The debugger will attempt to work around https://bugs.python.org/issue37416."\n )\n\n if critical_warning:\n on_critical("Issue found when debugger was trying to work around https://bugs.python.org/issue37416:\n%s" % (critical_warning,))\n except:\n on_exception("Error patching main thread id.")\n\n\ndef attach(port, host, protocol="", debug_mode=""):\n try:\n import sys\n\n fix_main_thread = "threading" not in sys.modules\n\n if fix_main_thread:\n\n def on_warn(msg):\n from _pydev_bundle import pydev_log\n\n pydev_log.warn(msg)\n\n def on_exception(msg):\n from _pydev_bundle import pydev_log\n\n pydev_log.exception(msg)\n\n def on_critical(msg):\n from _pydev_bundle import pydev_log\n\n pydev_log.critical(msg)\n\n fix_main_thread_id(on_warn=on_warn, on_exception=on_exception, on_critical=on_critical)\n\n else:\n from _pydev_bundle import pydev_log # @Reimport\n\n pydev_log.debug("The threading module is already imported by user code.")\n\n if protocol:\n from _pydevd_bundle import pydevd_defaults\n\n pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = protocol\n\n if debug_mode:\n from _pydevd_bundle import pydevd_defaults\n\n pydevd_defaults.PydevdCustomization.DEBUG_MODE = debug_mode\n\n import pydevd\n\n # I.e.: disconnect/reset if already connected.\n\n pydevd.SetupHolder.setup = None\n\n py_db = pydevd.get_global_debugger()\n if py_db is not None:\n py_db.dispose_and_kill_all_pydevd_threads(wait=False)\n\n # pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3\n pydevd.settrace(\n port=port,\n host=host,\n stdoutToServer=True,\n stderrToServer=True,\n overwrite_prev_trace=True,\n suspend=False,\n trace_only_current_thread=False,\n patch_multiprocessing=False,\n )\n except:\n import traceback\n\n traceback.print_exc()\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\attach_script.py
|
attach_script.py
|
Python
| 8,228 | 0.95 | 0.18408 | 0.201299 |
python-kit
| 397 |
2024-09-01T03:24:10.699570
|
GPL-3.0
| false |
9481b86f669d867e49cf413f84226d8c
|
MZ
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\attach_x86.dll
|
attach_x86.dll
|
Other
| 43,056 | 0.95 | 0.018587 | 0 |
vue-tools
| 442 |
2025-03-20T19:04:28.912894
|
BSD-3-Clause
| false |
f1b4f03d2504fe7974bc25b37161a51d
|
This folder contains the utilities to attach a target process to the pydev debugger.\n\nThe main module to be called for the attach is:\n\nattach_pydevd.py\n\nit should be called as;\n\npython attach_pydevd.py --port 5678 --pid 1234\n\nNote that the client is responsible for having a remote debugger alive in the given port for the attach to work.\n\n\nThe binaries are now compiled at:\n- https://github.com/fabioz/PyDev.Debugger.binaries/actions\n(after generation the binaries are copied to this repo)\n\n\nTo copy:\ncd /D X:\PyDev.Debugger\n"C:\Program Files\7-Zip\7z" e C:\Users\fabio\Downloads\win_binaries.zip -oX:\PyDev.Debugger\pydevd_attach_to_process * -r -y\n"C:\Program Files\7-Zip\7z" e C:\Users\fabio\Downloads\linux_binaries.zip -oX:\PyDev.Debugger\pydevd_attach_to_process * -r -y\n"C:\Program Files\7-Zip\7z" e C:\Users\fabio\Downloads\mac_binaries.zip -oX:\PyDev.Debugger\pydevd_attach_to_process * -r -y\ngit add *.exe\ngit add *.dll\ngit add *.dylib\ngit add *.so\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\README.txt
|
README.txt
|
Other
| 987 | 0.8 | 0.111111 | 0 |
python-kit
| 564 |
2024-03-15T01:49:09.966753
|
GPL-3.0
| false |
67353b3a049b0cd20487a17362d33f3e
|
MZ
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\run_code_on_dllmain_amd64.dll
|
run_code_on_dllmain_amd64.dll
|
Other
| 29,240 | 0.8 | 0 | 0.017422 |
node-utils
| 916 |
2024-04-26T18:08:16.935078
|
Apache-2.0
| false |
552dd30477b58d64a86d70a48c6b3e6f
|
MZ
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\run_code_on_dllmain_x86.dll
|
run_code_on_dllmain_x86.dll
|
Other
| 25,648 | 0.8 | 0 | 0 |
vue-tools
| 260 |
2024-04-09T18:18:09.905052
|
Apache-2.0
| false |
b79ee89805232a86cee9fd7a683463c4
|
import sys\nimport struct\n\nprint("Executable: %s" % sys.executable)\nimport os\n\n\ndef loop_in_thread():\n while True:\n import time\n\n time.sleep(0.5)\n sys.stdout.write("#")\n sys.stdout.flush()\n\n\nimport threading\n\nthreading.Thread(target=loop_in_thread).start()\n\n\ndef is_python_64bit():\n return struct.calcsize("P") == 8\n\n\nprint("Is 64: %s" % is_python_64bit())\n\nif __name__ == "__main__":\n print("pid:%s" % (os.getpid()))\n i = 0\n while True:\n i += 1\n import time\n\n time.sleep(0.5)\n sys.stdout.write(".")\n sys.stdout.flush()\n if i % 40 == 0:\n sys.stdout.write("\n")\n sys.stdout.flush()\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\_always_live_program.py
|
_always_live_program.py
|
Python
| 727 | 0.95 | 0.15 | 0 |
react-lib
| 43 |
2024-09-25T06:20:14.671273
|
MIT
| false |
7d89f6fc9d205e8bd4526a48cf49564c
|
import add_code_to_python_process\n\nprint(add_code_to_python_process.run_python_code(3736, "print(20)", connect_debugger_tracing=False))\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\_check.py
|
_check.py
|
Python
| 139 | 0.85 | 0 | 0 |
awesome-app
| 613 |
2024-11-01T07:14:06.453888
|
MIT
| false |
f8a51522322c969d3c671b594aebe922
|
#ifndef _PY_CUSTOM_PYEVAL_SETTRACE_HPP_\n#define _PY_CUSTOM_PYEVAL_SETTRACE_HPP_\n\n#include "python.h"\n#include "py_utils.hpp"\n#include "py_custom_pyeval_settrace_common.hpp"\n#include "py_custom_pyeval_settrace_310.hpp"\n#include "py_custom_pyeval_settrace_311.hpp"\n\n// On Python 3.7 onwards the thread state is not kept in PyThread_set_key_value (rather\n// it uses PyThread_tss_set using PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)\n// and we don't have access to that key from here (thus, we can't use the previous approach which\n// made CPython think that the current thread had the thread state where we wanted to set the tracing).\n//\n// So, the solution implemented here is not faking that change and reimplementing PyEval_SetTrace.\n// The implementation is mostly the same from the one in CPython, but we have one shortcoming:\n//\n// When CPython sets the tracing for a thread it increments _Py_TracingPossible (actually\n// _PyRuntime.ceval.tracing_possible). This implementation has one issue: it only works on\n// deltas when the tracing is set (so, a settrace(func) will increase the _Py_TracingPossible global value and a\n// settrace(None) will decrease it, but when a thread dies it's kept as is and is not decreased).\n// -- as we don't currently have access to _PyRuntime we have to create a thread, set the tracing\n// and let it die so that the count is increased (this is really hacky, but better than having\n// to create a local copy of the whole _PyRuntime (defined in pystate.h with several inner structs)\n// which would need to be kept up to date for each new CPython version just to increment that variable).\n\n\n\n/**\n * This version is used in internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict on older\n * versions of CPython (pre 3.7).\n */\n static PyObject *\n PyObject_FastCallDictCustom(PyObject* callback, PyObject *stack[3], int ignoredStackSizeAlways3, void* ignored)\n {\n PyObject *args = internalInitializeCustomPyEvalSetTrace->pyTuple_New(3);\n PyObject *result;\n\n if (args == NULL) {\n return NULL;\n }\n\n IncRef(stack[0]);\n IncRef(stack[1]);\n IncRef(stack[2]);\n\n // I.e.: same thing as: PyTuple_SET_ITEM(args, 0, stack[0]);\n reinterpret_cast<PyTupleObject *>(args)->ob_item[0] = stack[0];\n reinterpret_cast<PyTupleObject *>(args)->ob_item[1] = stack[1];\n reinterpret_cast<PyTupleObject *>(args)->ob_item[2] = stack[2];\n\n /* call the Python-level function */\n result = internalInitializeCustomPyEvalSetTrace->pyEval_CallObjectWithKeywords(callback, args, (PyObject*)NULL);\n\n /* cleanup */\n DecRef(args, internalInitializeCustomPyEvalSetTrace->isDebug);\n return result;\n}\n\nstatic PyObject *\nInternalCallTrampoline(PyObject* callback,\n PyFrameObjectBaseUpTo39 *frame, int what, PyObject *arg)\n{\n PyObject *result;\n PyObject *stack[3];\n\n// Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead).\n// if (PyFrame_FastToLocalsWithError(frame) < 0) {\n// return NULL;\n// }\n//\n stack[0] = (PyObject *)frame;\n stack[1] = InternalWhatstrings_37[what];\n stack[2] = (arg != NULL) ? arg : internalInitializeCustomPyEvalSetTrace->pyNone;\n \n \n // Helpers to print info.\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[0])));\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[1])));\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[2])));\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)callback)));\n\n // call the Python-level function\n // result = _PyObject_FastCall(callback, stack, 3);\n //\n // Note that _PyObject_FastCall is actually a define:\n // #define _PyObject_FastCall(func, args, nargs) _PyObject_FastCallDict((func), (args), (nargs), NULL)\n\n result = internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict(callback, stack, 3, NULL);\n\n\n// Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead).\n// PyFrame_LocalsToFast(frame, 1);\n\n if (result == NULL) {\n internalInitializeCustomPyEvalSetTrace->pyTraceBack_Here(frame);\n }\n\n return result;\n}\n\nstatic int\nInternalTraceTrampoline(PyObject *self, PyFrameObject *frameParam,\n int what, PyObject *arg)\n{\n PyObject *callback;\n PyObject *result;\n \n PyFrameObjectBaseUpTo39 *frame = reinterpret_cast<PyFrameObjectBaseUpTo39*>(frameParam);\n\n if (what == PyTrace_CALL){\n callback = self;\n } else {\n callback = frame->f_trace;\n }\n\n if (callback == NULL){\n return 0;\n }\n\n result = InternalCallTrampoline(callback, frame, what, arg);\n if (result == NULL) {\n // Note: calling the original sys.settrace here.\n internalInitializeCustomPyEvalSetTrace->pyEval_SetTrace(NULL, NULL);\n PyObject *temp_f_trace = frame->f_trace;\n frame->f_trace = NULL;\n if(temp_f_trace != NULL){\n DecRef(temp_f_trace, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n return -1;\n }\n if (result != internalInitializeCustomPyEvalSetTrace->pyNone) {\n PyObject *tmp = frame->f_trace;\n frame->f_trace = result;\n DecRef(tmp, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n else {\n DecRef(result, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n return 0;\n}\n\n// Based on ceval.c (PyEval_SetTrace(Py_tracefunc func, PyObject *arg))\ntemplate<typename T>\nvoid InternalPySetTrace_Template(T tstate, PyObjectHolder* traceFunc, bool isDebug)\n{\n PyObject *temp = tstate->c_traceobj;\n\n // We can't increase _Py_TracingPossible. Everything else should be equal to CPython.\n // runtime->ceval.tracing_possible += (func != NULL) - (tstate->c_tracefunc != NULL);\n\n PyObject *arg = traceFunc->ToPython();\n IncRef(arg);\n tstate->c_tracefunc = NULL;\n tstate->c_traceobj = NULL;\n /* Must make sure that profiling is not ignored if 'temp' is freed */\n tstate->use_tracing = tstate->c_profilefunc != NULL;\n if(temp != NULL){\n DecRef(temp, isDebug);\n }\n tstate->c_tracefunc = InternalTraceTrampoline;\n tstate->c_traceobj = arg;\n /* Flag that tracing or profiling is turned on */\n tstate->use_tracing = ((InternalTraceTrampoline != NULL)\n || (tstate->c_profilefunc != NULL));\n\n};\n\n\nvoid InternalPySetTrace(PyThreadState* curThread, PyObjectHolder* traceFunc, bool isDebug, PythonVersion version)\n{\n if (PyThreadState_25_27::IsFor(version)) {\n InternalPySetTrace_Template<PyThreadState_25_27*>(reinterpret_cast<PyThreadState_25_27*>(curThread), traceFunc, isDebug);\n } else if (PyThreadState_30_33::IsFor(version)) {\n InternalPySetTrace_Template<PyThreadState_30_33*>(reinterpret_cast<PyThreadState_30_33*>(curThread), traceFunc, isDebug);\n } else if (PyThreadState_34_36::IsFor(version)) {\n InternalPySetTrace_Template<PyThreadState_34_36*>(reinterpret_cast<PyThreadState_34_36*>(curThread), traceFunc, isDebug);\n } else if (PyThreadState_37_38::IsFor(version)) {\n InternalPySetTrace_Template<PyThreadState_37_38*>(reinterpret_cast<PyThreadState_37_38*>(curThread), traceFunc, isDebug);\n } else if (PyThreadState_39::IsFor(version)) {\n InternalPySetTrace_Template<PyThreadState_39*>(reinterpret_cast<PyThreadState_39*>(curThread), traceFunc, isDebug);\n } else if (PyThreadState_310::IsFor(version)) {\n // 3.10 has other changes on the actual algorithm (use_tracing is per-frame now), so, we have a full new version for it.\n InternalPySetTrace_Template310<PyThreadState_310*>(reinterpret_cast<PyThreadState_310*>(curThread), traceFunc, isDebug);\n } else if (PyThreadState_311::IsFor(version)) {\n InternalPySetTrace_Template311<PyThreadState_311*>(reinterpret_cast<PyThreadState_311*>(curThread), traceFunc, isDebug);\n } else {\n printf("Unable to set trace to target thread with Python version: %d", version);\n }\n}\n\n\n#endif //_PY_CUSTOM_PYEVAL_SETTRACE_HPP_
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\py_custom_pyeval_settrace.hpp
|
py_custom_pyeval_settrace.hpp
|
Other
| 8,591 | 0.95 | 0.114583 | 0.34375 |
node-utils
| 557 |
2023-12-02T07:19:48.024307
|
Apache-2.0
| false |
204af7312da5d3773121070d93e112fd
|
#ifndef _PY_CUSTOM_PYEVAL_SETTRACE_310_HPP_\n#define _PY_CUSTOM_PYEVAL_SETTRACE_310_HPP_\n\n#include "python.h"\n#include "py_utils.hpp"\n\nstatic PyObject *\nInternalCallTrampoline310(PyObject* callback,\n PyFrameObject310 *frame, int what, PyObject *arg)\n{\n PyObject *result;\n PyObject *stack[3];\n\n// Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead).\n// if (PyFrame_FastToLocalsWithError(frame) < 0) {\n// return NULL;\n// }\n//\n stack[0] = (PyObject *)frame;\n stack[1] = InternalWhatstrings_37[what];\n stack[2] = (arg != NULL) ? arg : internalInitializeCustomPyEvalSetTrace->pyNone;\n \n \n // Helper to print info.\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[0])));\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[1])));\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[2])));\n // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)callback)));\n\n result = internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict(callback, stack, 3, NULL);\n\n// Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead).\n// PyFrame_LocalsToFast(frame, 1);\n\n if (result == NULL) {\n internalInitializeCustomPyEvalSetTrace->pyTraceBack_Here(frame);\n }\n\n return result;\n}\n\n// See: static int trace_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg)\n// in: https://github.com/python/cpython/blob/3.10/Python/sysmodule.c\nstatic int\nInternalTraceTrampoline310(PyObject *self, PyFrameObject *frameParam,\n int what, PyObject *arg)\n{\n PyObject *callback;\n PyObject *result;\n \n PyFrameObject310 *frame = reinterpret_cast<PyFrameObject310*>(frameParam);\n\n if (what == PyTrace_CALL){\n callback = self;\n } else {\n callback = frame->f_trace;\n }\n\n if (callback == NULL){\n return 0;\n }\n\n result = InternalCallTrampoline310(callback, frame, what, arg);\n if (result == NULL) {\n // Note: calling the original sys.settrace here.\n internalInitializeCustomPyEvalSetTrace->pyEval_SetTrace(NULL, NULL);\n PyObject *temp_f_trace = frame->f_trace;\n frame->f_trace = NULL;\n if(temp_f_trace != NULL){\n DecRef(temp_f_trace, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n return -1;\n }\n if (result != internalInitializeCustomPyEvalSetTrace->pyNone) {\n PyObject *tmp = frame->f_trace;\n frame->f_trace = result;\n DecRef(tmp, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n else {\n DecRef(result, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n return 0;\n}\n\n// Based on ceval.c (PyEval_SetTrace(Py_tracefunc func, PyObject *arg))\n// https://github.com/python/cpython/blob/3.10/Python/ceval.c\ntemplate<typename T>\nvoid InternalPySetTrace_Template310(T tstate, PyObjectHolder* traceFunc, bool isDebug)\n{\n PyObject *temp = tstate->c_traceobj;\n\n PyObject *arg = traceFunc->ToPython();\n IncRef(arg);\n tstate->c_tracefunc = NULL;\n tstate->c_traceobj = NULL;\n \n // This is different (previously it was just: tstate->use_tracing, now\n // this flag is per-frame). \n tstate->cframe->use_tracing = tstate->c_profilefunc != NULL;\n \n if(temp != NULL){\n DecRef(temp, isDebug);\n }\n tstate->c_tracefunc = InternalTraceTrampoline310;\n tstate->c_traceobj = arg;\n /* Flag that tracing or profiling is turned on */\n tstate->cframe->use_tracing = ((InternalTraceTrampoline310 != NULL)\n || (tstate->c_profilefunc != NULL));\n\n};\n\n\n#endif //_PY_CUSTOM_PYEVAL_SETTRACE_310_HPP_
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\py_custom_pyeval_settrace_310.hpp
|
py_custom_pyeval_settrace_310.hpp
|
Other
| 4,174 | 0.95 | 0.071429 | 0.271739 |
awesome-app
| 296 |
2023-12-31T23:42:15.342751
|
BSD-3-Clause
| false |
b287d53669c44d7bff0d290702a85c09
|
#ifndef _PY_CUSTOM_PYEVAL_SETTRACE_311_HPP_\n#define _PY_CUSTOM_PYEVAL_SETTRACE_311_HPP_\n\n#include "python.h"\n#include "py_utils.hpp"\n\nstatic PyObject *\nInternalCallTrampoline311(PyObject* callback,\n PyFrameObject311 *frame, int what, PyObject *arg)\n{\n PyObject *result;\n PyObject *stack[3];\n\n// Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead).\n// if (PyFrame_FastToLocalsWithError(frame) < 0) {\n// return NULL;\n// }\n//\n stack[0] = (PyObject *)frame;\n stack[1] = InternalWhatstrings_37[what];\n stack[2] = (arg != NULL) ? arg : internalInitializeCustomPyEvalSetTrace->pyNone;\n \n \n // Helper to print info.\n //printf("--- start\n");\n //printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[0])));\n //printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[1])));\n //printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[2])));\n //printf("--- end\n");\n\n result = internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict(callback, stack, 3, NULL);\n\n// Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead).\n// PyFrame_LocalsToFast(frame, 1);\n\n if (result == NULL) {\n internalInitializeCustomPyEvalSetTrace->pyTraceBack_Here(frame);\n }\n\n return result;\n}\n\n// See: static int trace_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg)\n// in: https://github.com/python/cpython/blob/3.11/Python/sysmodule.c\nstatic int\nInternalTraceTrampoline311(PyObject *self, PyFrameObject *frameParam,\n int what, PyObject *arg)\n{\n PyObject *callback;\n PyObject *result;\n \n PyFrameObject311 *frame = reinterpret_cast<PyFrameObject311*>(frameParam);\n\n if (what == PyTrace_CALL){\n callback = self;\n } else {\n callback = frame->f_trace;\n }\n\n if (callback == NULL){\n return 0;\n }\n\n result = InternalCallTrampoline311(callback, frame, what, arg);\n if (result == NULL) {\n // Note: calling the original sys.settrace here.\n internalInitializeCustomPyEvalSetTrace->pyEval_SetTrace(NULL, NULL);\n PyObject *temp_f_trace = frame->f_trace;\n frame->f_trace = NULL;\n if(temp_f_trace != NULL){\n DecRef(temp_f_trace, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n return -1;\n }\n if (result != internalInitializeCustomPyEvalSetTrace->pyNone) {\n PyObject *tmp = frame->f_trace;\n frame->f_trace = result;\n DecRef(tmp, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n else {\n DecRef(result, internalInitializeCustomPyEvalSetTrace->isDebug);\n }\n return 0;\n}\n\n// Based on ceval.c (PyEval_SetTrace(Py_tracefunc func, PyObject *arg))\n// https://github.com/python/cpython/blob/3.11/Python/ceval.c\ntemplate<typename T>\nvoid InternalPySetTrace_Template311(T tstate, PyObjectHolder* traceFunc, bool isDebug)\n{\n PyObject *traceobj = tstate->c_traceobj;\n\n PyObject *arg = traceFunc->ToPython();\n IncRef(arg);\n tstate->c_tracefunc = NULL;\n tstate->c_traceobj = NULL;\n \n // This is different (previously it was just: tstate->use_tracing, now\n // this flag is per-frame). \n int use_tracing = (tstate->c_profilefunc != NULL);\n \n // Note: before 3.11 this was just 1 or 0, now it needs to be 255 or 0.\n tstate->cframe->use_tracing = (use_tracing ? 255 : 0);\n \n if(traceobj != NULL){\n DecRef(traceobj, isDebug);\n }\n tstate->c_tracefunc = InternalTraceTrampoline311;\n tstate->c_traceobj = arg;\n /* Flag that tracing or profiling is turned on */\n use_tracing = ((InternalTraceTrampoline311 != NULL)\n || (tstate->c_profilefunc != NULL));\n \n // Note: before 3.11 this was just 1 or 0, now it needs to be 255 or 0.\n tstate->cframe->use_tracing = (use_tracing ? 255 : 0);\n\n};\n\n\n#endif //_PY_CUSTOM_PYEVAL_SETTRACE_311_HPP_
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\py_custom_pyeval_settrace_311.hpp
|
py_custom_pyeval_settrace_311.hpp
|
Other
| 4,388 | 0.95 | 0.067227 | 0.28866 |
python-kit
| 800 |
2024-12-23T16:00:24.537389
|
MIT
| false |
4bbcfa2a6f383aad70815a6f09c478c2
|
#ifndef _PY_CUSTOM_PYEVAL_SETTRACE_COMMON_HPP_\n#define _PY_CUSTOM_PYEVAL_SETTRACE_COMMON_HPP_\n\n#include "python.h"\n#include "py_utils.hpp"\n\nstruct InternalInitializeCustomPyEvalSetTrace {\n PyObject* pyNone;\n PyTuple_New* pyTuple_New;\n _PyObject_FastCallDict* pyObject_FastCallDict;\n PyEval_CallObjectWithKeywords* pyEval_CallObjectWithKeywords;\n PyUnicode_InternFromString* pyUnicode_InternFromString; // Note: in Py2 will be PyString_InternFromString.\n PyTraceBack_Here* pyTraceBack_Here;\n PyEval_SetTrace* pyEval_SetTrace;\n bool isDebug;\n PyUnicode_AsUTF8* pyUnicode_AsUTF8;\n PyObject_Repr* pyObject_Repr;\n};\n\n/**\n * Helper information to access CPython internals.\n */\nstatic InternalInitializeCustomPyEvalSetTrace *internalInitializeCustomPyEvalSetTrace = NULL;\n\n/*\n * Cached interned string objects used for calling the profile and\n * trace functions. Initialized by InternalTraceInit().\n */\nstatic PyObject *InternalWhatstrings_37[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};\n\n\nstatic int\nInternalIsTraceInitialized()\n{\n return internalInitializeCustomPyEvalSetTrace != NULL;\n}\n\n\n\nstatic int\nInternalTraceInit(InternalInitializeCustomPyEvalSetTrace *p_internalInitializeSettrace_37)\n{\n internalInitializeCustomPyEvalSetTrace = p_internalInitializeSettrace_37;\n static const char * const whatnames[8] = {\n "call", "exception", "line", "return",\n "c_call", "c_exception", "c_return",\n "opcode"\n };\n PyObject *name;\n int i;\n for (i = 0; i < 8; ++i) {\n if (InternalWhatstrings_37[i] == NULL) {\n name = internalInitializeCustomPyEvalSetTrace->pyUnicode_InternFromString(whatnames[i]);\n if (name == NULL)\n return -1;\n InternalWhatstrings_37[i] = name;\n }\n }\n return 0;\n}\n\n#endif //_PY_CUSTOM_PYEVAL_SETTRACE_COMMON_HPP_
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\py_custom_pyeval_settrace_common.hpp
|
py_custom_pyeval_settrace_common.hpp
|
Other
| 1,931 | 0.95 | 0.065574 | 0.230769 |
node-utils
| 565 |
2024-05-06T04:05:33.551677
|
BSD-3-Clause
| false |
5514ab5ddf3eade24020aa5e54d8f620
|
#ifndef _PY_SETTRACE_HPP_\n#define _PY_SETTRACE_HPP_\n\n#include "ref_utils.hpp"\n#include "py_utils.hpp"\n#include "python.h"\n#include "py_custom_pyeval_settrace.hpp"\n#include <unordered_set>\n\n\n#ifdef _WIN32\n\ntypedef HMODULE MODULE_TYPE;\n#else // LINUX -----------------------------------------------------------------\n\ntypedef void* MODULE_TYPE;\ntypedef ssize_t SSIZE_T;\ntypedef unsigned int DWORD;\n\n#endif\n\nDWORD GetPythonThreadId(PythonVersion version, PyThreadState* curThread) {\n DWORD threadId = 0;\n if (PyThreadState_25_27::IsFor(version)) {\n threadId = (DWORD)((PyThreadState_25_27*)curThread)->thread_id;\n } else if (PyThreadState_30_33::IsFor(version)) {\n threadId = (DWORD)((PyThreadState_30_33*)curThread)->thread_id;\n } else if (PyThreadState_34_36::IsFor(version)) {\n threadId = (DWORD)((PyThreadState_34_36*)curThread)->thread_id;\n } else if (PyThreadState_37_38::IsFor(version)) {\n threadId = (DWORD)((PyThreadState_37_38*)curThread)->thread_id;\n } else if (PyThreadState_39::IsFor(version)) {\n threadId = (DWORD)((PyThreadState_39*)curThread)->thread_id;\n } else if (PyThreadState_310::IsFor(version)) {\n threadId = (DWORD)((PyThreadState_310*)curThread)->thread_id;\n } else if (PyThreadState_311::IsFor(version)) {\n threadId = (DWORD)((PyThreadState_311*)curThread)->thread_id;\n }\n return threadId;\n}\n\n\n/**\n * This function may be called to set a tracing function to existing python threads.\n */\nint InternalSetSysTraceFunc(\n MODULE_TYPE module,\n bool isDebug,\n bool showDebugInfo,\n PyObjectHolder* traceFunc,\n PyObjectHolder* setTraceFunc,\n unsigned int threadId,\n PyObjectHolder* pyNone)\n{\n\n if(showDebugInfo){\n PRINT("InternalSetSysTraceFunc started.");\n }\n\n DEFINE_PROC(isInit, Py_IsInitialized*, "Py_IsInitialized", 100);\n if (!isInit()) {\n PRINT("Py_IsInitialized returned false.");\n return 110;\n }\n\n auto version = GetPythonVersion(module);\n\n // found initialized Python runtime, gather and check the APIs we need.\n\n DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", 120);\n DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 130);\n DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", 140);\n DEFINE_PROC(threadHead, PyInterpreterState_ThreadHead*, "PyInterpreterState_ThreadHead", 150);\n DEFINE_PROC(threadNext, PyThreadState_Next*, "PyThreadState_Next", 160);\n DEFINE_PROC(threadSwap, PyThreadState_Swap*, "PyThreadState_Swap", 170);\n DEFINE_PROC(call, PyObject_CallFunctionObjArgs*, "PyObject_CallFunctionObjArgs", 180);\n\n PyInt_FromLong* intFromLong;\n\n if (version >= PythonVersion_30) {\n DEFINE_PROC(intFromLongPy3, PyInt_FromLong*, "PyLong_FromLong", 190);\n intFromLong = intFromLongPy3;\n } else {\n DEFINE_PROC(intFromLongPy2, PyInt_FromLong*, "PyInt_FromLong", 200);\n intFromLong = intFromLongPy2;\n }\n\n DEFINE_PROC(pyGetAttr, PyObject_GetAttrString*, "PyObject_GetAttrString", 250);\n DEFINE_PROC(pyHasAttr, PyObject_HasAttrString*, "PyObject_HasAttrString", 260);\n DEFINE_PROC_NO_CHECK(PyCFrame_Type, PyTypeObject*, "PyCFrame_Type", 300); // optional\n\n DEFINE_PROC_NO_CHECK(curPythonThread, PyThreadState**, "_PyThreadState_Current", 310); // optional\n DEFINE_PROC_NO_CHECK(getPythonThread, _PyThreadState_UncheckedGet*, "_PyThreadState_UncheckedGet", 320); // optional\n\n if (curPythonThread == nullptr && getPythonThread == nullptr) {\n // we're missing some APIs, we cannot attach.\n PRINT("Error, missing Python threading API!!");\n return 330;\n }\n\n auto head = interpHead();\n if (head == nullptr) {\n // this interpreter is loaded but not initialized.\n PRINT("Interpreter not initialized!");\n return 340;\n }\n\n GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done...\n\n int retVal = 0;\n // find what index is holding onto the thread state...\n auto curPyThread = getPythonThread ? getPythonThread() : *curPythonThread;\n\n if(curPyThread == nullptr){\n PRINT("Getting the current python thread returned nullptr.");\n return 345;\n }\n\n\n // We do what PyEval_SetTrace does, but for any target thread.\n PyUnicode_InternFromString* pyUnicode_InternFromString;\n if (version >= PythonVersion_30) {\n DEFINE_PROC(unicodeFromString, PyUnicode_InternFromString*, "PyUnicode_InternFromString", 520);\n pyUnicode_InternFromString = unicodeFromString;\n } else {\n DEFINE_PROC(stringFromString, PyUnicode_InternFromString*, "PyString_InternFromString", 525);\n pyUnicode_InternFromString = stringFromString;\n }\n\n _PyObject_FastCallDict* pyObject_FastCallDict;\n if (version < PythonVersion_37) {\n pyObject_FastCallDict = reinterpret_cast<_PyObject_FastCallDict*>(&PyObject_FastCallDictCustom);\n } else if (version < PythonVersion_39) {\n DEFINE_PROC(fastCallDict, _PyObject_FastCallDict*, "_PyObject_FastCallDict", 530);\n pyObject_FastCallDict = fastCallDict;\n } else {\n DEFINE_PROC(vectorcallDict, _PyObject_FastCallDict*, "PyObject_VectorcallDict", 530);\n pyObject_FastCallDict = vectorcallDict;\n }\n\n DEFINE_PROC(pyTuple_New, PyTuple_New*, "PyTuple_New", 531);\n DEFINE_PROC(pyEval_CallObjectWithKeywords, PyEval_CallObjectWithKeywords*, "PyEval_CallObjectWithKeywords", 532);\n\n\n DEFINE_PROC(pyTraceBack_Here, PyTraceBack_Here*, "PyTraceBack_Here", 540);\n DEFINE_PROC(pyEval_SetTrace, PyEval_SetTrace*, "PyEval_SetTrace", 550);\n \n // These are defined mostly for printing info while debugging, so, if they're not there, don't bother reporting.\n DEFINE_PROC_NO_CHECK(pyObject_Repr, PyObject_Repr*, "PyObject_Repr", 551);\n DEFINE_PROC_NO_CHECK(pyUnicode_AsUTF8, PyUnicode_AsUTF8*, "PyUnicode_AsUTF8", 552);\n\n\n bool found = false;\n for (PyThreadState* curThread = threadHead(head); curThread != nullptr; curThread = threadNext(curThread)) {\n if (GetPythonThreadId(version, curThread) != threadId) {\n continue;\n }\n found = true;\n\n if(showDebugInfo){\n printf("setting trace for thread: %d\n", threadId);\n }\n\n if(!InternalIsTraceInitialized())\n {\n InternalInitializeCustomPyEvalSetTrace *internalInitializeCustomPyEvalSetTrace = new InternalInitializeCustomPyEvalSetTrace();\n\n IncRef(pyNone->ToPython());\n internalInitializeCustomPyEvalSetTrace->pyNone = pyNone->ToPython();\n\n internalInitializeCustomPyEvalSetTrace->pyUnicode_InternFromString = pyUnicode_InternFromString;\n internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict = pyObject_FastCallDict;\n internalInitializeCustomPyEvalSetTrace->isDebug = isDebug;\n internalInitializeCustomPyEvalSetTrace->pyTraceBack_Here = pyTraceBack_Here;\n internalInitializeCustomPyEvalSetTrace->pyEval_SetTrace = pyEval_SetTrace;\n internalInitializeCustomPyEvalSetTrace->pyTuple_New = pyTuple_New;\n internalInitializeCustomPyEvalSetTrace->pyEval_CallObjectWithKeywords = pyEval_CallObjectWithKeywords;\n internalInitializeCustomPyEvalSetTrace->pyObject_Repr = pyObject_Repr;\n internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8 = pyUnicode_AsUTF8;\n\n InternalTraceInit(internalInitializeCustomPyEvalSetTrace);\n }\n InternalPySetTrace(curThread, traceFunc, isDebug, version);\n break;\n }\n if(!found) {\n retVal = 501;\n }\n\n return retVal;\n\n}\n\n#endif // _PY_SETTRACE_HPP_\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\py_settrace.hpp
|
py_settrace.hpp
|
Other
| 7,875 | 0.95 | 0.14433 | 0.12987 |
vue-tools
| 328 |
2024-08-03T10:25:14.626324
|
MIT
| false |
b7748f26f998860f036be926035e9f1d
|
#ifndef _PY_UTILS_HPP_\n#define _PY_UTILS_HPP_\n\ntypedef int (Py_IsInitialized)();\ntypedef PyInterpreterState* (PyInterpreterState_Head)();\ntypedef enum { PyGILState_LOCKED, PyGILState_UNLOCKED } PyGILState_STATE;\ntypedef PyGILState_STATE(PyGILState_Ensure)();\ntypedef void (PyGILState_Release)(PyGILState_STATE);\ntypedef int (PyRun_SimpleString)(const char *command);\ntypedef PyThreadState* (PyInterpreterState_ThreadHead)(PyInterpreterState* interp);\ntypedef PyThreadState* (PyThreadState_Next)(PyThreadState *tstate);\ntypedef PyThreadState* (PyThreadState_Swap)(PyThreadState *tstate);\ntypedef PyThreadState* (_PyThreadState_UncheckedGet)();\ntypedef PyThreadState* (_PyThreadState_GetCurrent)();\ntypedef PyObject* (PyObject_CallFunctionObjArgs)(PyObject *callable, ...); // call w/ varargs, last arg should be nullptr\ntypedef PyObject* (PyInt_FromLong)(long);\ntypedef PyObject* (PyErr_Occurred)();\ntypedef void (PyErr_Fetch)(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback);\ntypedef void (PyErr_Restore)(PyObject *type, PyObject *value, PyObject *traceback);\ntypedef PyObject* (PyImport_ImportModule) (const char *name);\ntypedef PyObject* (PyImport_ImportModuleNoBlock) (const char *name);\ntypedef PyObject* (PyObject_GetAttrString)(PyObject *o, const char *attr_name);\ntypedef PyObject* (PyObject_HasAttrString)(PyObject *o, const char *attr_name);\ntypedef void* (PyThread_get_key_value)(int);\ntypedef int (PyThread_set_key_value)(int, void*);\ntypedef void (PyThread_delete_key_value)(int);\ntypedef int (PyObject_Not) (PyObject *o);\ntypedef PyObject* (PyDict_New)();\ntypedef PyObject* (PyUnicode_InternFromString)(const char *u);\ntypedef PyObject * (_PyObject_FastCallDict)(\n PyObject *callable, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs);\ntypedef int (PyTraceBack_Here)(PyFrameObject *frame);\n\ntypedef PyObject* PyTuple_New(Py_ssize_t len);\ntypedef PyObject* PyEval_CallObjectWithKeywords(PyObject *callable, PyObject *args, PyObject *kwargs);\n\ntypedef void (PyEval_SetTrace)(Py_tracefunc, PyObject *);\ntypedef int (*Py_tracefunc)(PyObject *, PyFrameObject *frame, int, PyObject *);\ntypedef int (_PyEval_SetTrace)(PyThreadState *tstate, Py_tracefunc func, PyObject *arg);\n\ntypedef PyObject* PyObject_Repr(PyObject *);\ntypedef const char* PyUnicode_AsUTF8(PyObject *unicode);\n\n// holder to ensure we release the GIL even in error conditions\nclass GilHolder {\n PyGILState_STATE _gilState;\n PyGILState_Release* _release;\npublic:\n GilHolder(PyGILState_Ensure* acquire, PyGILState_Release* release) {\n _gilState = acquire();\n _release = release;\n }\n\n ~GilHolder() {\n _release(_gilState);\n }\n};\n\n#ifdef _WIN32\n\n#define PRINT(msg) {std::cout << msg << std::endl << std::flush;}\n\n#define DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode) \\n funcType func=reinterpret_cast<funcType>(GetProcAddress(module, funcNameStr));\n\n#define DEFINE_PROC(func, funcType, funcNameStr, errorCode) \\n DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode); \\n if(func == nullptr){std::cout << funcNameStr << " not found." << std::endl << std::flush; return errorCode;};\n\n#else // LINUX -----------------------------------------------------------------\n\n#define PRINT(msg) {printf(msg); printf("\n");}\n\n#define CHECK_NULL(ptr, msg, errorCode) if(ptr == nullptr){printf(msg); return errorCode;}\n\n#define DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode) \\n funcType func; *(void**)(&func) = dlsym(module, funcNameStr);\n\n#define DEFINE_PROC(func, funcType, funcNameStr, errorCode) \\n DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode); \\n if(func == nullptr){printf(funcNameStr); printf(" not found.\n"); return errorCode;};\n\n#endif //_WIN32\n\n#endif //_PY_UTILS_HPP_
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\py_utils.hpp
|
py_utils.hpp
|
Other
| 3,949 | 0.95 | 0.047619 | 0.205882 |
python-kit
| 183 |
2025-07-01T10:14:21.688288
|
GPL-3.0
| false |
65ff7bdfbf618072535b072bd78c6cec
|
\n#ifndef __PY_VERSION_HPP__\n#define __PY_VERSION_HPP__\n\n\n#include <cstring>\n\nenum PythonVersion {\n PythonVersion_Unknown,\n PythonVersion_25 = 0x0205,\n PythonVersion_26 = 0x0206,\n PythonVersion_27 = 0x0207,\n PythonVersion_30 = 0x0300,\n PythonVersion_31 = 0x0301,\n PythonVersion_32 = 0x0302,\n PythonVersion_33 = 0x0303,\n PythonVersion_34 = 0x0304,\n PythonVersion_35 = 0x0305,\n PythonVersion_36 = 0x0306,\n PythonVersion_37 = 0x0307,\n PythonVersion_38 = 0x0308,\n PythonVersion_39 = 0x0309,\n PythonVersion_310 = 0x030A,\n PythonVersion_311 = 0x030B,\n PythonVersion_312 = 0x030C,\n PythonVersion_313 = 0x030D,\n};\n\n\n#ifdef _WIN32\n\ntypedef const char* (GetVersionFunc)();\n\nstatic PythonVersion GetPythonVersion(HMODULE hMod) {\n auto versionFunc = reinterpret_cast<GetVersionFunc*>(GetProcAddress(hMod, "Py_GetVersion"));\n if (versionFunc == nullptr) {\n return PythonVersion_Unknown;\n }\n const char* version = versionFunc();\n\n\n#else // LINUX -----------------------------------------------------------------\n\ntypedef const char* (*GetVersionFunc) ();\n\nstatic PythonVersion GetPythonVersion(void *module) {\n GetVersionFunc versionFunc;\n *(void**)(&versionFunc) = dlsym(module, "Py_GetVersion");\n if(versionFunc == nullptr) {\n return PythonVersion_Unknown;\n }\n const char* version = versionFunc();\n\n#endif //_WIN32\n\n if (version != nullptr && strlen(version) >= 3 && version[1] == '.') {\n if (version[0] == '2') {\n switch (version[2]) {\n case '5': return PythonVersion_25;\n case '6': return PythonVersion_26;\n case '7': return PythonVersion_27;\n }\n }\n else if (version[0] == '3') {\n switch (version[2]) {\n case '0': return PythonVersion_30;\n case '1':\n if(strlen(version) >= 4){\n if(version[3] == '0'){\n return PythonVersion_310;\n }\n if(version[3] == '1'){\n return PythonVersion_311;\n }\n if(version[3] == '2'){\n return PythonVersion_312;\n }\n if(version[3] == '3'){\n return PythonVersion_313;\n }\n }\n return PythonVersion_Unknown; // we don't care about 3.1 anymore...\n \n case '2': return PythonVersion_32;\n case '3': return PythonVersion_33;\n case '4': return PythonVersion_34;\n case '5': return PythonVersion_35;\n case '6': return PythonVersion_36;\n case '7': return PythonVersion_37;\n case '8': return PythonVersion_38;\n case '9': return PythonVersion_39;\n }\n }\n }\n return PythonVersion_Unknown;\n}\n\n#endif
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\py_version.hpp
|
py_version.hpp
|
Other
| 3,009 | 0.95 | 0.123711 | 0.097561 |
node-utils
| 658 |
2025-01-19T00:28:40.669651
|
GPL-3.0
| false |
3542d761cd850f60a4b796429c5b41ac
|
#ifndef _REF_UTILS_HPP_\n#define _REF_UTILS_HPP_\n\n\nPyObject* GetPyObjectPointerNoDebugInfo(bool isDebug, PyObject* object) {\n if (object != nullptr && isDebug) {\n // debug builds have 2 extra pointers at the front that we don't care about\n return (PyObject*)((size_t*)object + 2);\n }\n return object;\n}\n\nvoid DecRef(PyObject* object, bool isDebug) {\n auto noDebug = GetPyObjectPointerNoDebugInfo(isDebug, object);\n\n if (noDebug != nullptr && --noDebug->ob_refcnt == 0) {\n ((PyTypeObject*)GetPyObjectPointerNoDebugInfo(isDebug, noDebug->ob_type))->tp_dealloc(object);\n }\n}\n\nvoid IncRef(PyObject* object) {\n object->ob_refcnt++;\n}\n\nclass PyObjectHolder {\nprivate:\n PyObject* _object;\npublic:\n bool _isDebug;\n\n PyObjectHolder(bool isDebug) {\n _object = nullptr;\n _isDebug = isDebug;\n }\n\n PyObjectHolder(bool isDebug, PyObject *object) {\n _object = object;\n _isDebug = isDebug;\n };\n\n PyObjectHolder(bool isDebug, PyObject *object, bool addRef) {\n _object = object;\n _isDebug = isDebug;\n if (_object != nullptr && addRef) {\n GetPyObjectPointerNoDebugInfo(_isDebug, _object)->ob_refcnt++;\n }\n };\n\n PyObject* ToPython() {\n return _object;\n }\n\n ~PyObjectHolder() {\n DecRef(_object, _isDebug);\n }\n\n PyObject* operator* () {\n return GetPyObjectPointerNoDebugInfo(_isDebug, _object);\n }\n};\n\n\n#endif //_REF_UTILS_HPP_
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\common\ref_utils.hpp
|
ref_utils.hpp
|
Other
| 1,537 | 0.95 | 0.064516 | 0.081633 |
react-lib
| 518 |
2024-03-05T13:18:24.570534
|
GPL-3.0
| false |
0202eb318b1fdba2acf750bc2e2bb5ab
|
/attach_x86.dylib\n/attach_x86_64.dylib\n/attach_linux_x86.o\n/attach_linux_x86_64.o\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\linux_and_mac\.gitignore
|
.gitignore
|
Other
| 86 | 0.5 | 0 | 0 |
react-lib
| 472 |
2024-04-08T11:09:05.445822
|
GPL-3.0
| false |
5ef39df7c34dc95013e28570bc1893f9
|
// This is much simpler than the windows version because we're using gdb and\n// we assume that gdb will call things in the correct thread already.\n\n//compile with: g++ -shared -o attach_linux.so -fPIC -nostartfiles attach_linux.c\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <dlfcn.h>\n#include <stdbool.h>\n\n#include "../common/python.h"\n#include "../common/ref_utils.hpp"\n#include "../common/py_utils.hpp"\n#include "../common/py_settrace.hpp"\n//#include <unistd.h> used for usleep\n\n// Exported function: hello(): Just to print something and check that we've been\n// able to connect.\nextern "C" int hello(void);\n\nint hello()\n{\n printf("Hello world!\n");\n\n void *module = dlopen(nullptr, 0x2);\n\n void *hndl = dlsym (module, "PyGILState_Ensure");\n if(hndl == nullptr){\n printf("nullptr\n");\n\n }else{\n printf("Worked (found PyGILState_Ensure)!\n");\n }\n\n printf("%d", GetPythonVersion(module));\n\n\n return 2;\n}\n\n\n// Internal function to keep on the tracing\nint _PYDEVD_ExecWithGILSetSysStrace(bool showDebugInfo, bool isDebug);\n\n// Implementation details below\ntypedef PyObject* (PyImport_ImportModuleNoBlock) (const char *name);\ntypedef int (*PyEval_ThreadsInitialized)();\ntypedef unsigned long (*_PyEval_GetSwitchInterval)(void);\ntypedef void (*_PyEval_SetSwitchInterval)(unsigned long microseconds);\n\n// isDebug is pretty important! Must be true on python debug builds (python_d)\n// If this value is passed wrongly the program will crash.\nextern "C" int DoAttach(bool isDebug, const char *command, bool showDebugInfo);\n\nint DoAttach(bool isDebug, const char *command, bool showDebugInfo)\n{\n void *module = dlopen(nullptr, 0x2);\n DEFINE_PROC(isInitFunc, Py_IsInitialized*, "Py_IsInitialized", 1);\n DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 51);\n DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", 51);\n\n\n if(!isInitFunc()){\n if(showDebugInfo){\n printf("Py_IsInitialized returned false.\n");\n }\n return 2;\n }\n\n PythonVersion version = GetPythonVersion(module);\n\n DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", 51);\n\n auto head = interpHead();\n if (head == nullptr) {\n // this interpreter is loaded but not initialized.\n if(showDebugInfo){\n printf("Interpreter not initialized!\n");\n }\n return 54;\n }\n\n // Note: unlike windows where we have to do many things to enable threading\n // to work to get the gil, here we'll be executing in an existing thread,\n // so, it's mostly a matter of getting the GIL and running it and we shouldn't\n // have any more problems.\n\n DEFINE_PROC(pyRun_SimpleString, PyRun_SimpleString*, "PyRun_SimpleString", 51);\n \n GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done...\n \n pyRun_SimpleString(command);\n return 0;\n}\n\n\n// This is the function which enables us to set the sys.settrace for all the threads\n// which are already running.\nextern "C" int AttachDebuggerTracing(bool showDebugInfo, void* pSetTraceFunc, void* pTraceFunc, unsigned int threadId, void* pPyNone);\n\nint AttachDebuggerTracing(bool showDebugInfo, void* pSetTraceFunc, void* pTraceFunc, unsigned int threadId, void* pPyNone)\n{\n void *module = dlopen(nullptr, 0x2);\n bool isDebug = false;\n PyObjectHolder traceFunc(isDebug, (PyObject*) pTraceFunc, true);\n PyObjectHolder setTraceFunc(isDebug, (PyObject*) pSetTraceFunc, true);\n PyObjectHolder pyNone(isDebug, reinterpret_cast<PyObject*>(pPyNone), true);\n return InternalSetSysTraceFunc(module, isDebug, showDebugInfo, &traceFunc, &setTraceFunc, threadId, &pyNone);\n}\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\linux_and_mac\attach.cpp
|
attach.cpp
|
C++
| 3,814 | 0.95 | 0.09009 | 0.308642 |
python-kit
| 532 |
2025-01-30T21:51:21.878723
|
GPL-3.0
| false |
a0c65828b66ed1c8645cdb43b53c3b56
|
set -e\n\nARCH="$(uname -m)"\ncase $ARCH in\n i*86) SUFFIX=x86;;\n x86_64*) SUFFIX=amd64;;\n *) echo >&2 "unsupported: $ARCH"; exit 1;;\nesac\n\nSRC="$(dirname "$0")/.."\ng++ -std=c++11 -shared -fPIC -O2 -D_FORTIFY_SOURCE=2 -nostartfiles --stack-protector-strong $SRC/linux_and_mac/attach.cpp -o $SRC/attach_linux_$SUFFIX.so\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\linux_and_mac\compile_linux.sh
|
compile_linux.sh
|
Shell
| 335 | 0.7 | 0 | 0.111111 |
awesome-app
| 687 |
2024-11-01T16:14:41.451793
|
BSD-3-Clause
| false |
f5645ff85a3688589a4a15963d3c5763
|
set -e\nSRC="$(dirname "$0")/.."\ng++ -fPIC -D_REENTRANT -std=c++11 -D_FORTIFY_SOURCE=2 -arch x86_64 -c $SRC/linux_and_mac/attach.cpp -o $SRC/attach_x86_64.o\ng++ -dynamiclib -nostartfiles -arch x86_64 -lc $SRC/attach_x86_64.o -o $SRC/attach_x86_64.dylib\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\linux_and_mac\compile_mac.sh
|
compile_mac.sh
|
Shell
| 256 | 0.7 | 0 | 0 |
node-utils
| 941 |
2025-06-04T23:58:27.719906
|
GPL-3.0
| false |
13f35380e7120a972226263ca186afa9
|
:: WARNING: manylinux1 images are based on CentOS 5, which requires vsyscall to be available on\n:: the host. For any recent version of Linux, this requires passing vsyscall=emulate during boot.\n:: For WSL, add the following to your .wslconfig:\n::\n:: [wsl2]\n:: kernelCommandLine = vsyscall=emulate\n\ndocker run --rm -v %~dp0/..:/src quay.io/pypa/manylinux1_x86_64 g++ -std=c++11 -D_FORTIFY_SOURCE=2 -shared -o /src/attach_linux_amd64.so -fPIC -nostartfiles /src/linux_and_mac/attach.cpp\n\ndocker run --rm -v %~dp0/..:/src quay.io/pypa/manylinux1_i686 g++ -std=c++11 -D_FORTIFY_SOURCE=2 -shared -o /src/attach_linux_x86.so -fPIC -nostartfiles /src/linux_and_mac/attach.cpp\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\linux_and_mac\compile_manylinux.cmd
|
compile_manylinux.cmd
|
Other
| 683 | 0.85 | 0 | 0 |
vue-tools
| 919 |
2025-07-09T17:16:38.047612
|
BSD-3-Clause
| false |
e829bfcb6d4cdb3cc97c06abbb7aefc2
|
# This file is meant to be run inside lldb\n# It registers command to load library and invoke attach function\n# Also it marks process threads to to distinguish them from debugger\n# threads later while settings trace in threads\n\n\ndef load_lib_and_attach(debugger, command, result, internal_dict):\n import shlex\n\n args = shlex.split(command)\n\n dll = args[0]\n is_debug = args[1]\n python_code = args[2]\n show_debug_info = args[3]\n\n import lldb\n\n options = lldb.SBExpressionOptions()\n options.SetFetchDynamicValue()\n options.SetTryAllThreads(run_others=False)\n options.SetTimeoutInMicroSeconds(timeout=10000000)\n\n print(dll)\n target = debugger.GetSelectedTarget()\n res = target.EvaluateExpression('(void*)dlopen("%s", 2);' % (dll), options)\n error = res.GetError()\n if error:\n print(error)\n\n print(python_code)\n res = target.EvaluateExpression('(int)DoAttach(%s, "%s", %s);' % (is_debug, python_code.replace('"', "'"), show_debug_info), options)\n error = res.GetError()\n if error:\n print(error)\n\n\ndef __lldb_init_module(debugger, internal_dict):\n import lldb\n\n debugger.HandleCommand("command script add -f lldb_prepare.load_lib_and_attach load_lib_and_attach")\n\n try:\n target = debugger.GetSelectedTarget()\n if target:\n process = target.GetProcess()\n if process:\n for thread in process:\n # print('Marking process thread %d'%thread.GetThreadID())\n internal_dict["_thread_%d" % thread.GetThreadID()] = True\n # thread.Suspend()\n except:\n import traceback\n\n traceback.print_exc()\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\linux_and_mac\lldb_prepare.py
|
lldb_prepare.py
|
Python
| 1,734 | 0.95 | 0.181818 | 0.142857 |
awesome-app
| 604 |
2024-06-25T10:54:06.212499
|
BSD-3-Clause
| false |
5738b07d7917495f0f3590822d97c7f9
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\linux_and_mac\__pycache__\lldb_prepare.cpython-313.pyc
|
lldb_prepare.cpython-313.pyc
|
Other
| 2,315 | 0.8 | 0 | 0.114286 |
awesome-app
| 111 |
2023-10-26T15:40:09.648621
|
GPL-3.0
| false |
bd0434ffd8bbc2a9e4dcb9c357aa1218
|
#!~/.wine/drive_c/Python25/python.exe\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2009-2014, Mario Vilas\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice,this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n"""\nBinary code disassembly.\n\n@group Disassembler loader:\n Disassembler, Engine\n\n@group Disassembler engines:\n BeaEngine, CapstoneEngine, DistormEngine,\n LibdisassembleEngine, PyDasmEngine\n"""\n\nfrom __future__ import with_statement\n\n__revision__ = "$Id$"\n\n__all__ = [\n "Disassembler",\n "Engine",\n "BeaEngine",\n "CapstoneEngine",\n "DistormEngine",\n "LibdisassembleEngine",\n "PyDasmEngine",\n]\n\nfrom winappdbg.textio import HexDump\nfrom winappdbg import win32\n\nimport ctypes\nimport warnings\n\n# lazy imports\nBeaEnginePython = None\ndistorm3 = None\npydasm = None\nlibdisassemble = None\ncapstone = None\n\n# ==============================================================================\n\n\nclass Engine(object):\n """\n Base class for disassembly engine adaptors.\n\n @type name: str\n @cvar name: Engine name to use with the L{Disassembler} class.\n\n @type desc: str\n @cvar desc: User friendly name of the disassembler engine.\n\n @type url: str\n @cvar url: Download URL.\n\n @type supported: set(str)\n @cvar supported: Set of supported processor architectures.\n For more details see L{win32.version._get_arch}.\n\n @type arch: str\n @ivar arch: Name of the processor architecture.\n """\n\n name = "<insert engine name here>"\n desc = "<insert engine description here>"\n url = "<insert download url here>"\n supported = set()\n\n def __init__(self, arch=None):\n """\n @type arch: str\n @param arch: Name of the processor architecture.\n If not provided the current processor architecture is assumed.\n For more details see L{win32.version._get_arch}.\n\n @raise NotImplementedError: This disassembler doesn't support the\n requested processor architecture.\n """\n self.arch = self._validate_arch(arch)\n try:\n self._import_dependencies()\n except ImportError:\n msg = "%s is not installed or can't be found. Download it from: %s"\n msg = msg % (self.name, self.url)\n raise NotImplementedError(msg)\n\n def _validate_arch(self, arch=None):\n """\n @type arch: str\n @param arch: Name of the processor architecture.\n If not provided the current processor architecture is assumed.\n For more details see L{win32.version._get_arch}.\n\n @rtype: str\n @return: Name of the processor architecture.\n If not provided the current processor architecture is assumed.\n For more details see L{win32.version._get_arch}.\n\n @raise NotImplementedError: This disassembler doesn't support the\n requested processor architecture.\n """\n\n # Use the default architecture if none specified.\n if not arch:\n arch = win32.arch\n\n # Validate the architecture.\n if arch not in self.supported:\n msg = "The %s engine cannot decode %s code."\n msg = msg % (self.name, arch)\n raise NotImplementedError(msg)\n\n # Return the architecture.\n return arch\n\n def _import_dependencies(self):\n """\n Loads the dependencies for this disassembler.\n\n @raise ImportError: This disassembler cannot find or load the\n necessary dependencies to make it work.\n """\n raise SyntaxError("Subclasses MUST implement this method!")\n\n def decode(self, address, code):\n """\n @type address: int\n @param address: Memory address where the code was read from.\n\n @type code: str\n @param code: Machine code to disassemble.\n\n @rtype: list of tuple( long, int, str, str )\n @return: List of tuples. Each tuple represents an assembly instruction\n and contains:\n - Memory address of instruction.\n - Size of instruction in bytes.\n - Disassembly line of instruction.\n - Hexadecimal dump of instruction.\n\n @raise NotImplementedError: This disassembler could not be loaded.\n This may be due to missing dependencies.\n """\n raise NotImplementedError()\n\n\n# ==============================================================================\n\n\nclass BeaEngine(Engine):\n """\n Integration with the BeaEngine disassembler by Beatrix.\n\n @see: U{https://sourceforge.net/projects/winappdbg/files/additional%20packages/BeaEngine/}\n """\n\n name = "BeaEngine"\n desc = "BeaEngine disassembler by Beatrix"\n url = "https://sourceforge.net/projects/winappdbg/files/additional%20packages/BeaEngine/"\n\n supported = set(\n (\n win32.ARCH_I386,\n win32.ARCH_AMD64,\n )\n )\n\n def _import_dependencies(self):\n # Load the BeaEngine ctypes wrapper.\n global BeaEnginePython\n if BeaEnginePython is None:\n import BeaEnginePython\n\n def decode(self, address, code):\n addressof = ctypes.addressof\n\n # Instance the code buffer.\n buffer = ctypes.create_string_buffer(code)\n buffer_ptr = addressof(buffer)\n\n # Instance the disassembler structure.\n Instruction = BeaEnginePython.DISASM()\n Instruction.VirtualAddr = address\n Instruction.EIP = buffer_ptr\n Instruction.SecurityBlock = buffer_ptr + len(code)\n if self.arch == win32.ARCH_I386:\n Instruction.Archi = 0\n else:\n Instruction.Archi = 0x40\n Instruction.Options = (\n BeaEnginePython.Tabulation + BeaEnginePython.NasmSyntax + BeaEnginePython.SuffixedNumeral + BeaEnginePython.ShowSegmentRegs\n )\n\n # Prepare for looping over each instruction.\n result = []\n Disasm = BeaEnginePython.Disasm\n InstructionPtr = addressof(Instruction)\n hexdump = HexDump.hexadecimal\n append = result.append\n OUT_OF_BLOCK = BeaEnginePython.OUT_OF_BLOCK\n UNKNOWN_OPCODE = BeaEnginePython.UNKNOWN_OPCODE\n\n # For each decoded instruction...\n while True:\n # Calculate the current offset into the buffer.\n offset = Instruction.EIP - buffer_ptr\n\n # If we've gone past the buffer, break the loop.\n if offset >= len(code):\n break\n\n # Decode the current instruction.\n InstrLength = Disasm(InstructionPtr)\n\n # If BeaEngine detects we've gone past the buffer, break the loop.\n if InstrLength == OUT_OF_BLOCK:\n break\n\n # The instruction could not be decoded.\n if InstrLength == UNKNOWN_OPCODE:\n # Output a single byte as a "db" instruction.\n char = "%.2X" % ord(buffer[offset])\n result.append(\n (\n Instruction.VirtualAddr,\n 1,\n "db %sh" % char,\n char,\n )\n )\n Instruction.VirtualAddr += 1\n Instruction.EIP += 1\n\n # The instruction was decoded but reading past the buffer's end.\n # This can happen when the last instruction is a prefix without an\n # opcode. For example: decode(0, '\x66')\n elif offset + InstrLength > len(code):\n # Output each byte as a "db" instruction.\n for char in buffer[offset : offset + len(code)]:\n char = "%.2X" % ord(char)\n result.append(\n (\n Instruction.VirtualAddr,\n 1,\n "db %sh" % char,\n char,\n )\n )\n Instruction.VirtualAddr += 1\n Instruction.EIP += 1\n\n # The instruction was decoded correctly.\n else:\n # Output the decoded instruction.\n append(\n (\n Instruction.VirtualAddr,\n InstrLength,\n Instruction.CompleteInstr.strip(),\n hexdump(buffer.raw[offset : offset + InstrLength]),\n )\n )\n Instruction.VirtualAddr += InstrLength\n Instruction.EIP += InstrLength\n\n # Return the list of decoded instructions.\n return result\n\n\n# ==============================================================================\n\n\nclass DistormEngine(Engine):\n """\n Integration with the diStorm disassembler by Gil Dabah.\n\n @see: U{https://code.google.com/p/distorm3}\n """\n\n name = "diStorm"\n desc = "diStorm disassembler by Gil Dabah"\n url = "https://code.google.com/p/distorm3"\n\n supported = set(\n (\n win32.ARCH_I386,\n win32.ARCH_AMD64,\n )\n )\n\n def _import_dependencies(self):\n # Load the distorm bindings.\n global distorm3\n if distorm3 is None:\n try:\n import distorm3\n except ImportError:\n import distorm as distorm3\n\n # Load the decoder function.\n self.__decode = distorm3.Decode\n\n # Load the bits flag.\n self.__flag = {\n win32.ARCH_I386: distorm3.Decode32Bits,\n win32.ARCH_AMD64: distorm3.Decode64Bits,\n }[self.arch]\n\n def decode(self, address, code):\n return self.__decode(address, code, self.__flag)\n\n\n# ==============================================================================\n\n\nclass PyDasmEngine(Engine):\n """\n Integration with PyDasm: Python bindings to libdasm.\n\n @see: U{https://code.google.com/p/libdasm/}\n """\n\n name = "PyDasm"\n desc = "PyDasm: Python bindings to libdasm"\n url = "https://code.google.com/p/libdasm/"\n\n supported = set((win32.ARCH_I386,))\n\n def _import_dependencies(self):\n # Load the libdasm bindings.\n global pydasm\n if pydasm is None:\n import pydasm\n\n def decode(self, address, code):\n # Decode each instruction in the buffer.\n result = []\n offset = 0\n while offset < len(code):\n # Try to decode the current instruction.\n instruction = pydasm.get_instruction(code[offset : offset + 32], pydasm.MODE_32)\n\n # Get the memory address of the current instruction.\n current = address + offset\n\n # Illegal opcode or opcode longer than remaining buffer.\n if not instruction or instruction.length + offset > len(code):\n hexdump = "%.2X" % ord(code[offset])\n disasm = "db 0x%s" % hexdump\n ilen = 1\n\n # Correctly decoded instruction.\n else:\n disasm = pydasm.get_instruction_string(instruction, pydasm.FORMAT_INTEL, current)\n ilen = instruction.length\n hexdump = HexDump.hexadecimal(code[offset : offset + ilen])\n\n # Add the decoded instruction to the list.\n result.append(\n (\n current,\n ilen,\n disasm,\n hexdump,\n )\n )\n\n # Move to the next instruction.\n offset += ilen\n\n # Return the list of decoded instructions.\n return result\n\n\n# ==============================================================================\n\n\nclass LibdisassembleEngine(Engine):\n """\n Integration with Immunity libdisassemble.\n\n @see: U{http://www.immunitysec.com/resources-freesoftware.shtml}\n """\n\n name = "Libdisassemble"\n desc = "Immunity libdisassemble"\n url = "http://www.immunitysec.com/resources-freesoftware.shtml"\n\n supported = set((win32.ARCH_I386,))\n\n def _import_dependencies(self):\n # Load the libdisassemble module.\n # Since it doesn't come with an installer or an __init__.py file\n # users can only install it manually however they feel like it,\n # so we'll have to do a bit of guessing to find it.\n\n global libdisassemble\n if libdisassemble is None:\n try:\n # If installed properly with __init__.py\n import libdisassemble.disassemble as libdisassemble\n\n except ImportError:\n # If installed by just copying and pasting the files\n import disassemble as libdisassemble\n\n def decode(self, address, code):\n # Decode each instruction in the buffer.\n result = []\n offset = 0\n while offset < len(code):\n # Decode the current instruction.\n opcode = libdisassemble.Opcode(code[offset : offset + 32])\n length = opcode.getSize()\n disasm = opcode.printOpcode("INTEL")\n hexdump = HexDump.hexadecimal(code[offset : offset + length])\n\n # Add the decoded instruction to the list.\n result.append(\n (\n address + offset,\n length,\n disasm,\n hexdump,\n )\n )\n\n # Move to the next instruction.\n offset += length\n\n # Return the list of decoded instructions.\n return result\n\n\n# ==============================================================================\n\n\nclass CapstoneEngine(Engine):\n """\n Integration with the Capstone disassembler by Nguyen Anh Quynh.\n\n @see: U{http://www.capstone-engine.org/}\n """\n\n name = "Capstone"\n desc = "Capstone disassembler by Nguyen Anh Quynh"\n url = "http://www.capstone-engine.org/"\n\n supported = set(\n (\n win32.ARCH_I386,\n win32.ARCH_AMD64,\n win32.ARCH_THUMB,\n win32.ARCH_ARM,\n win32.ARCH_ARM64,\n )\n )\n\n def _import_dependencies(self):\n # Load the Capstone bindings.\n global capstone\n if capstone is None:\n import capstone\n\n # Load the constants for the requested architecture.\n self.__constants = {\n win32.ARCH_I386: (capstone.CS_ARCH_X86, capstone.CS_MODE_32),\n win32.ARCH_AMD64: (capstone.CS_ARCH_X86, capstone.CS_MODE_64),\n win32.ARCH_THUMB: (capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB),\n win32.ARCH_ARM: (capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM),\n win32.ARCH_ARM64: (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),\n }\n\n # Test for the bug in early versions of Capstone.\n # If found, warn the user about it.\n try:\n self.__bug = not isinstance(\n capstone.cs_disasm_quick(capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1)[0], capstone.capstone.CsInsn\n )\n except AttributeError:\n self.__bug = False\n if self.__bug:\n warnings.warn(\n "This version of the Capstone bindings is unstable," " please upgrade to a newer one!", RuntimeWarning, stacklevel=4\n )\n\n def decode(self, address, code):\n # Get the constants for the requested architecture.\n arch, mode = self.__constants[self.arch]\n\n # Get the decoder function outside the loop.\n decoder = capstone.cs_disasm_quick\n\n # If the buggy version of the bindings are being used, we need to catch\n # all exceptions broadly. If not, we only need to catch CsError.\n if self.__bug:\n CsError = Exception\n else:\n CsError = capstone.CsError\n\n # Create the variables for the instruction length, mnemonic and\n # operands. That way they won't be created within the loop,\n # minimizing the chances data might be overwritten.\n # This only makes sense for the buggy vesion of the bindings, normally\n # memory accesses are safe).\n length = mnemonic = op_str = None\n\n # For each instruction...\n result = []\n offset = 0\n while offset < len(code):\n # Disassemble a single instruction, because disassembling multiple\n # instructions may cause excessive memory usage (Capstone allocates\n # approximately 1K of metadata per each decoded instruction).\n instr = None\n try:\n instr = decoder(arch, mode, code[offset : offset + 16], address + offset, 1)[0]\n except IndexError:\n pass # No instructions decoded.\n except CsError:\n pass # Any other error.\n\n # On success add the decoded instruction.\n if instr is not None:\n # Get the instruction length, mnemonic and operands.\n # Copy the values quickly before someone overwrites them,\n # if using the buggy version of the bindings (otherwise it's\n # irrelevant in which order we access the properties).\n length = instr.size\n mnemonic = instr.mnemonic\n op_str = instr.op_str\n\n # Concatenate the mnemonic and the operands.\n if op_str:\n disasm = "%s %s" % (mnemonic, op_str)\n else:\n disasm = mnemonic\n\n # Get the instruction bytes as a hexadecimal dump.\n hexdump = HexDump.hexadecimal(code[offset : offset + length])\n\n # On error add a "define constant" instruction.\n # The exact instruction depends on the architecture.\n else:\n # The number of bytes to skip depends on the architecture.\n # On Intel processors we'll skip one byte, since we can't\n # really know the instruction length. On the rest of the\n # architectures we always know the instruction length.\n if self.arch in (win32.ARCH_I386, win32.ARCH_AMD64):\n length = 1\n else:\n length = 4\n\n # Get the skipped bytes as a hexadecimal dump.\n skipped = code[offset : offset + length]\n hexdump = HexDump.hexadecimal(skipped)\n\n # Build the "define constant" instruction.\n # On Intel processors it's "db".\n # On ARM processors it's "dcb".\n if self.arch in (win32.ARCH_I386, win32.ARCH_AMD64):\n mnemonic = "db "\n else:\n mnemonic = "dcb "\n bytes = []\n for b in skipped:\n if b.isalpha():\n bytes.append("'%s'" % b)\n else:\n bytes.append("0x%x" % ord(b))\n op_str = ", ".join(bytes)\n disasm = mnemonic + op_str\n\n # Add the decoded instruction to the list.\n result.append(\n (\n address + offset,\n length,\n disasm,\n hexdump,\n )\n )\n\n # Update the offset.\n offset += length\n\n # Return the list of decoded instructions.\n return result\n\n\n# ==============================================================================\n\n# TODO: use a lock to access __decoder\n# TODO: look in sys.modules for whichever disassembler is already loaded\n\n\nclass Disassembler(object):\n """\n Generic disassembler. Uses a set of adapters to decide which library to\n load for which supported platform.\n\n @type engines: tuple( L{Engine} )\n @cvar engines: Set of supported engines. If you implement your own adapter\n you can add its class here to make it available to L{Disassembler}.\n Supported disassemblers are:\n """\n\n engines = (\n DistormEngine, # diStorm engine goes first for backwards compatibility\n BeaEngine,\n CapstoneEngine,\n LibdisassembleEngine,\n PyDasmEngine,\n )\n\n # Add the list of supported disassemblers to the docstring.\n __doc__ += "\n"\n for e in engines:\n __doc__ += " - %s - %s (U{%s})\n" % (e.name, e.desc, e.url)\n del e\n\n # Cache of already loaded disassemblers.\n __decoder = {}\n\n def __new__(cls, arch=None, engine=None):\n """\n Factory class. You can't really instance a L{Disassembler} object,\n instead one of the adapter L{Engine} subclasses is returned.\n\n @type arch: str\n @param arch: (Optional) Name of the processor architecture.\n If not provided the current processor architecture is assumed.\n For more details see L{win32.version._get_arch}.\n\n @type engine: str\n @param engine: (Optional) Name of the disassembler engine.\n If not provided a compatible one is loaded automatically.\n See: L{Engine.name}\n\n @raise NotImplementedError: No compatible disassembler was found that\n could decode machine code for the requested architecture. This may\n be due to missing dependencies.\n\n @raise ValueError: An unknown engine name was supplied.\n """\n\n # Use the default architecture if none specified.\n if not arch:\n arch = win32.arch\n\n # Return a compatible engine if none specified.\n if not engine:\n found = False\n for clazz in cls.engines:\n try:\n if arch in clazz.supported:\n selected = (clazz.name, arch)\n try:\n decoder = cls.__decoder[selected]\n except KeyError:\n decoder = clazz(arch)\n cls.__decoder[selected] = decoder\n return decoder\n except NotImplementedError:\n pass\n msg = "No disassembler engine available for %s code." % arch\n raise NotImplementedError(msg)\n\n # Return the specified engine.\n selected = (engine, arch)\n try:\n decoder = cls.__decoder[selected]\n except KeyError:\n found = False\n engineLower = engine.lower()\n for clazz in cls.engines:\n if clazz.name.lower() == engineLower:\n found = True\n break\n if not found:\n msg = "Unsupported disassembler engine: %s" % engine\n raise ValueError(msg)\n if arch not in clazz.supported:\n msg = "The %s engine cannot decode %s code." % selected\n raise NotImplementedError(msg)\n decoder = clazz(arch)\n cls.__decoder[selected] = decoder\n return decoder\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\disasm.py
|
disasm.py
|
Python
| 25,106 | 0.95 | 0.124128 | 0.212693 |
python-kit
| 965 |
2023-11-24T11:36:28.092304
|
BSD-3-Clause
| false |
8143c0f86b58a60d4163bc1f62c2801f
|
#!~/.wine/drive_c/Python25/python.exe\n# -*- coding: utf-8 -*-\n\n# Process memory finder\n# Copyright (c) 2009-2014, Mario Vilas\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice,this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n"""\nProcess memory search.\n\n@group Memory search:\n Search,\n Pattern,\n BytePattern,\n TextPattern,\n RegExpPattern,\n HexPattern\n"""\n\n__revision__ = "$Id$"\n\n__all__ = [\n "Search",\n "Pattern",\n "BytePattern",\n "TextPattern",\n "RegExpPattern",\n "HexPattern",\n]\n\nfrom winappdbg.textio import HexInput\nfrom winappdbg.util import StaticClass, MemoryAddresses\nfrom winappdbg import win32\n\nimport warnings\n\ntry:\n # http://pypi.python.org/pypi/regex\n import regex as re\nexcept ImportError:\n import re\n\n# ==============================================================================\n\n\nclass Pattern(object):\n """\n Base class for search patterns.\n\n The following L{Pattern} subclasses are provided by WinAppDbg:\n - L{BytePattern}\n - L{TextPattern}\n - L{RegExpPattern}\n - L{HexPattern}\n\n @see: L{Search.search_process}\n """\n\n def __init__(self, pattern):\n """\n Class constructor.\n\n The only mandatory argument should be the pattern string.\n\n This method B{MUST} be reimplemented by subclasses of L{Pattern}.\n """\n raise NotImplementedError()\n\n def __len__(self):\n """\n Returns the maximum expected length of the strings matched by this\n pattern. Exact behavior is implementation dependent.\n\n Ideally it should be an exact value, but in some cases it's not\n possible to calculate so an upper limit should be returned instead.\n\n If that's not possible either an exception must be raised.\n\n This value will be used to calculate the required buffer size when\n doing buffered searches.\n\n This method B{MUST} be reimplemented by subclasses of L{Pattern}.\n """\n raise NotImplementedError()\n\n def read(self, process, address, size):\n """\n Reads the requested number of bytes from the process memory at the\n given address.\n\n Subclasses of L{Pattern} tipically don't need to reimplement this\n method.\n """\n return process.read(address, size)\n\n def find(self, buffer, pos=None):\n """\n Searches for the pattern in the given buffer, optionally starting at\n the given position within the buffer.\n\n This method B{MUST} be reimplemented by subclasses of L{Pattern}.\n\n @type buffer: str\n @param buffer: Buffer to search on.\n\n @type pos: int\n @param pos:\n (Optional) Position within the buffer to start searching from.\n\n @rtype: tuple( int, int )\n @return: Tuple containing the following:\n - Position within the buffer where a match is found, or C{-1} if\n no match was found.\n - Length of the matched data if a match is found, or undefined if\n no match was found.\n """\n raise NotImplementedError()\n\n def found(self, address, size, data):\n """\n This method gets called when a match is found.\n\n This allows subclasses of L{Pattern} to filter out unwanted results,\n or modify the results before giving them to the caller of\n L{Search.search_process}.\n\n If the return value is C{None} the result is skipped.\n\n Subclasses of L{Pattern} don't need to reimplement this method unless\n filtering is needed.\n\n @type address: int\n @param address: The memory address where the pattern was found.\n\n @type size: int\n @param size: The size of the data that matches the pattern.\n\n @type data: str\n @param data: The data that matches the pattern.\n\n @rtype: tuple( int, int, str )\n @return: Tuple containing the following:\n * The memory address where the pattern was found.\n * The size of the data that matches the pattern.\n * The data that matches the pattern.\n """\n return (address, size, data)\n\n\n# ------------------------------------------------------------------------------\n\n\nclass BytePattern(Pattern):\n """\n Fixed byte pattern.\n\n @type pattern: str\n @ivar pattern: Byte string to search for.\n\n @type length: int\n @ivar length: Length of the byte pattern.\n """\n\n def __init__(self, pattern):\n """\n @type pattern: str\n @param pattern: Byte string to search for.\n """\n self.pattern = str(pattern)\n self.length = len(pattern)\n\n def __len__(self):\n """\n Returns the exact length of the pattern.\n\n @see: L{Pattern.__len__}\n """\n return self.length\n\n def find(self, buffer, pos=None):\n return buffer.find(self.pattern, pos), self.length\n\n\n# ------------------------------------------------------------------------------\n\n# FIXME: case insensitive compat.unicode searches are probably buggy!\n\n\nclass TextPattern(BytePattern):\n """\n Text pattern.\n\n @type isUnicode: bool\n @ivar isUnicode: C{True} if the text to search for is a compat.unicode string,\n C{False} otherwise.\n\n @type encoding: str\n @ivar encoding: Encoding for the text parameter.\n Only used when the text to search for is a Unicode string.\n Don't change unless you know what you're doing!\n\n @type caseSensitive: bool\n @ivar caseSensitive: C{True} of the search is case sensitive,\n C{False} otherwise.\n """\n\n def __init__(self, text, encoding="utf-16le", caseSensitive=False):\n """\n @type text: str or compat.unicode\n @param text: Text to search for.\n\n @type encoding: str\n @param encoding: (Optional) Encoding for the text parameter.\n Only used when the text to search for is a Unicode string.\n Don't change unless you know what you're doing!\n\n @type caseSensitive: bool\n @param caseSensitive: C{True} of the search is case sensitive,\n C{False} otherwise.\n """\n self.isUnicode = isinstance(text, compat.unicode)\n self.encoding = encoding\n self.caseSensitive = caseSensitive\n if not self.caseSensitive:\n pattern = text.lower()\n if self.isUnicode:\n pattern = text.encode(encoding)\n super(TextPattern, self).__init__(pattern)\n\n def read(self, process, address, size):\n data = super(TextPattern, self).read(address, size)\n if not self.caseSensitive:\n if self.isUnicode:\n try:\n encoding = self.encoding\n text = data.decode(encoding, "replace")\n text = text.lower()\n new_data = text.encode(encoding, "replace")\n if len(data) == len(new_data):\n data = new_data\n else:\n data = data.lower()\n except Exception:\n data = data.lower()\n else:\n data = data.lower()\n return data\n\n def found(self, address, size, data):\n if self.isUnicode:\n try:\n data = compat.unicode(data, self.encoding)\n except Exception:\n ## traceback.print_exc() # XXX DEBUG\n return None\n return (address, size, data)\n\n\n# ------------------------------------------------------------------------------\n\n\nclass RegExpPattern(Pattern):\n """\n Regular expression pattern.\n\n @type pattern: str\n @ivar pattern: Regular expression in text form.\n\n @type flags: int\n @ivar flags: Regular expression flags.\n\n @type regexp: re.compile\n @ivar regexp: Regular expression in compiled form.\n\n @type maxLength: int\n @ivar maxLength:\n Maximum expected length of the strings matched by this regular\n expression.\n\n This value will be used to calculate the required buffer size when\n doing buffered searches.\n\n Ideally it should be an exact value, but in some cases it's not\n possible to calculate so an upper limit should be given instead.\n\n If that's not possible either, C{None} should be used. That will\n cause an exception to be raised if this pattern is used in a\n buffered search.\n """\n\n def __init__(self, regexp, flags=0, maxLength=None):\n """\n @type regexp: str\n @param regexp: Regular expression string.\n\n @type flags: int\n @param flags: Regular expression flags.\n\n @type maxLength: int\n @param maxLength: Maximum expected length of the strings matched by\n this regular expression.\n\n This value will be used to calculate the required buffer size when\n doing buffered searches.\n\n Ideally it should be an exact value, but in some cases it's not\n possible to calculate so an upper limit should be given instead.\n\n If that's not possible either, C{None} should be used. That will\n cause an exception to be raised if this pattern is used in a\n buffered search.\n """\n self.pattern = regexp\n self.flags = flags\n self.regexp = re.compile(regexp, flags)\n self.maxLength = maxLength\n\n def __len__(self):\n """\n Returns the maximum expected length of the strings matched by this\n pattern. This value is taken from the C{maxLength} argument of the\n constructor if this class.\n\n Ideally it should be an exact value, but in some cases it's not\n possible to calculate so an upper limit should be returned instead.\n\n If that's not possible either an exception must be raised.\n\n This value will be used to calculate the required buffer size when\n doing buffered searches.\n """\n if self.maxLength is None:\n raise NotImplementedError()\n return self.maxLength\n\n def find(self, buffer, pos=None):\n if not pos: # make sure pos is an int\n pos = 0\n match = self.regexp.search(buffer, pos)\n if match:\n start, end = match.span()\n return start, end - start\n return -1, 0\n\n\n# ------------------------------------------------------------------------------\n\n\nclass HexPattern(RegExpPattern):\n """\n Hexadecimal pattern.\n\n Hex patterns must be in this form::\n "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world"\n\n Spaces are optional. Capitalization of hex digits doesn't matter.\n This is exactly equivalent to the previous example::\n "68656C6C6F20776F726C64" # "hello world"\n\n Wildcards are allowed, in the form of a C{?} sign in any hex digit::\n "5? 5? c3" # pop register / pop register / ret\n "b8 ?? ?? ?? ??" # mov eax, immediate value\n\n @type pattern: str\n @ivar pattern: Hexadecimal pattern.\n """\n\n def __new__(cls, pattern):\n """\n If the pattern is completely static (no wildcards are present) a\n L{BytePattern} is created instead. That's because searching for a\n fixed byte pattern is faster than searching for a regular expression.\n """\n if "?" not in pattern:\n return BytePattern(HexInput.hexadecimal(pattern))\n return object.__new__(cls, pattern)\n\n def __init__(self, hexa):\n """\n Hex patterns must be in this form::\n "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world"\n\n Spaces are optional. Capitalization of hex digits doesn't matter.\n This is exactly equivalent to the previous example::\n "68656C6C6F20776F726C64" # "hello world"\n\n Wildcards are allowed, in the form of a C{?} sign in any hex digit::\n "5? 5? c3" # pop register / pop register / ret\n "b8 ?? ?? ?? ??" # mov eax, immediate value\n\n @type hexa: str\n @param hexa: Pattern to search for.\n """\n maxLength = len([x for x in hexa if x in "?0123456789ABCDEFabcdef"]) / 2\n super(HexPattern, self).__init__(HexInput.pattern(hexa), maxLength=maxLength)\n\n\n# ==============================================================================\n\n\nclass Search(StaticClass):\n """\n Static class to group the search functionality.\n\n Do not instance this class! Use its static methods instead.\n """\n\n # TODO: aligned searches\n # TODO: method to coalesce search results\n # TODO: search memory dumps\n # TODO: search non-ascii C strings\n\n @staticmethod\n def search_process(process, pattern, minAddr=None, maxAddr=None, bufferPages=None, overlapping=False):\n """\n Search for the given pattern within the process memory.\n\n @type process: L{Process}\n @param process: Process to search.\n\n @type pattern: L{Pattern}\n @param pattern: Pattern to search for.\n It must be an instance of a subclass of L{Pattern}.\n\n The following L{Pattern} subclasses are provided by WinAppDbg:\n - L{BytePattern}\n - L{TextPattern}\n - L{RegExpPattern}\n - L{HexPattern}\n\n You can also write your own subclass of L{Pattern} for customized\n searches.\n\n @type minAddr: int\n @param minAddr: (Optional) Start the search at this memory address.\n\n @type maxAddr: int\n @param maxAddr: (Optional) Stop the search at this memory address.\n\n @type bufferPages: int\n @param bufferPages: (Optional) Number of memory pages to buffer when\n performing the search. Valid values are:\n - C{0} or C{None}:\n Automatically determine the required buffer size. May not give\n complete results for regular expressions that match variable\n sized strings.\n - C{> 0}: Set the buffer size, in memory pages.\n - C{< 0}: Disable buffering entirely. This may give you a little\n speed gain at the cost of an increased memory usage. If the\n target process has very large contiguous memory regions it may\n actually be slower or even fail. It's also the only way to\n guarantee complete results for regular expressions that match\n variable sized strings.\n\n @type overlapping: bool\n @param overlapping: C{True} to allow overlapping results, C{False}\n otherwise.\n\n Overlapping results yield the maximum possible number of results.\n\n For example, if searching for "AAAA" within "AAAAAAAA" at address\n C{0x10000}, when overlapping is turned off the following matches\n are yielded::\n (0x10000, 4, "AAAA")\n (0x10004, 4, "AAAA")\n\n If overlapping is turned on, the following matches are yielded::\n (0x10000, 4, "AAAA")\n (0x10001, 4, "AAAA")\n (0x10002, 4, "AAAA")\n (0x10003, 4, "AAAA")\n (0x10004, 4, "AAAA")\n\n As you can see, the middle results are overlapping the last two.\n\n @rtype: iterator of tuple( int, int, str )\n @return: An iterator of tuples. Each tuple contains the following:\n - The memory address where the pattern was found.\n - The size of the data that matches the pattern.\n - The data that matches the pattern.\n\n @raise WindowsError: An error occurred when querying or reading the\n process memory.\n """\n\n # Do some namespace lookups of symbols we'll be using frequently.\n MEM_COMMIT = win32.MEM_COMMIT\n PAGE_GUARD = win32.PAGE_GUARD\n page = MemoryAddresses.pageSize\n read = pattern.read\n find = pattern.find\n\n # Calculate the address range.\n if minAddr is None:\n minAddr = 0\n if maxAddr is None:\n maxAddr = win32.LPVOID(-1).value # XXX HACK\n\n # Calculate the buffer size from the number of pages.\n if bufferPages is None:\n try:\n size = MemoryAddresses.align_address_to_page_end(len(pattern)) + page\n except NotImplementedError:\n size = None\n elif bufferPages > 0:\n size = page * (bufferPages + 1)\n else:\n size = None\n\n # Get the memory map of the process.\n memory_map = process.iter_memory_map(minAddr, maxAddr)\n\n # Perform search with buffering enabled.\n if size:\n # Loop through all memory blocks containing data.\n buffer = "" # buffer to hold the memory data\n prev_addr = 0 # previous memory block address\n last = 0 # position of the last match\n delta = 0 # delta of last read address and start of buffer\n for mbi in memory_map:\n # Skip blocks with no data to search on.\n if not mbi.has_content():\n continue\n\n # Get the address and size of this block.\n address = mbi.BaseAddress # current address to search on\n block_size = mbi.RegionSize # total size of the block\n if address >= maxAddr:\n break\n end = address + block_size # end address of the block\n\n # If the block is contiguous to the previous block,\n # coalesce the new data in the buffer.\n if delta and address == prev_addr:\n buffer += read(process, address, page)\n\n # If not, clear the buffer and read new data.\n else:\n buffer = read(process, address, min(size, block_size))\n last = 0\n delta = 0\n\n # Search for the pattern in this block.\n while 1:\n # Yield each match of the pattern in the buffer.\n pos, length = find(buffer, last)\n while pos >= last:\n match_addr = address + pos - delta\n if minAddr <= match_addr < maxAddr:\n result = pattern.found(match_addr, length, buffer[pos : pos + length])\n if result is not None:\n yield result\n if overlapping:\n last = pos + 1\n else:\n last = pos + length\n pos, length = find(buffer, last)\n\n # Advance to the next page.\n address = address + page\n block_size = block_size - page\n prev_addr = address\n\n # Fix the position of the last match.\n last = last - page\n if last < 0:\n last = 0\n\n # Remove the first page in the buffer.\n buffer = buffer[page:]\n delta = page\n\n # If we haven't reached the end of the block yet,\n # read the next page in the block and keep seaching.\n if address < end:\n buffer = buffer + read(process, address, page)\n\n # Otherwise, we're done searching this block.\n else:\n break\n\n # Perform search with buffering disabled.\n else:\n # Loop through all memory blocks containing data.\n for mbi in memory_map:\n # Skip blocks with no data to search on.\n if not mbi.has_content():\n continue\n\n # Get the address and size of this block.\n address = mbi.BaseAddress\n block_size = mbi.RegionSize\n if address >= maxAddr:\n break\n\n # Read the whole memory region.\n buffer = process.read(address, block_size)\n\n # Search for the pattern in this region.\n pos, length = find(buffer)\n last = 0\n while pos >= last:\n match_addr = address + pos\n if minAddr <= match_addr < maxAddr:\n result = pattern.found(match_addr, length, buffer[pos : pos + length])\n if result is not None:\n yield result\n if overlapping:\n last = pos + 1\n else:\n last = pos + length\n pos, length = find(buffer, last)\n\n @classmethod\n def extract_ascii_strings(cls, process, minSize=4, maxSize=1024):\n """\n Extract ASCII strings from the process memory.\n\n @type process: L{Process}\n @param process: Process to search.\n\n @type minSize: int\n @param minSize: (Optional) Minimum size of the strings to search for.\n\n @type maxSize: int\n @param maxSize: (Optional) Maximum size of the strings to search for.\n\n @rtype: iterator of tuple(int, int, str)\n @return: Iterator of strings extracted from the process memory.\n Each tuple contains the following:\n - The memory address where the string was found.\n - The size of the string.\n - The string.\n """\n regexp = r"[\s\w\!\@\#\$\%%\^\&\*\(\)\{\}\[\]\~\`\'\"\:\;\.\,\\\/\-\+\=\_\<\>]{%d,%d}\0" % (minSize, maxSize)\n pattern = RegExpPattern(regexp, 0, maxSize)\n return cls.search_process(process, pattern, overlapping=False)\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\search.py
|
search.py
|
Python
| 23,902 | 0.95 | 0.146747 | 0.133843 |
react-lib
| 888 |
2025-04-01T20:31:20.475448
|
BSD-3-Clause
| false |
209aef1283cce06a91a3ee506f28cec8
|
#!~/.wine/drive_c/Python25/python.exe\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2009-2014, Mario Vilas\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice,this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n"""\nFunctions for text input, logging or text output.\n\n@group Helpers:\n HexDump,\n HexInput,\n HexOutput,\n Color,\n Table,\n Logger\n DebugLog\n CrashDump\n"""\n\n__revision__ = "$Id$"\n\n__all__ = [\n "HexDump",\n "HexInput",\n "HexOutput",\n "Color",\n "Table",\n "CrashDump",\n "DebugLog",\n "Logger",\n]\n\nimport sys\nfrom winappdbg import win32\nfrom winappdbg import compat\nfrom winappdbg.util import StaticClass\n\nimport re\nimport time\nimport struct\nimport traceback\n\n# ------------------------------------------------------------------------------\n\n\nclass HexInput(StaticClass):\n """\n Static functions for user input parsing.\n The counterparts for each method are in the L{HexOutput} class.\n """\n\n @staticmethod\n def integer(token):\n """\n Convert numeric strings into integers.\n\n @type token: str\n @param token: String to parse.\n\n @rtype: int\n @return: Parsed integer value.\n """\n token = token.strip()\n neg = False\n if token.startswith(compat.b("-")):\n token = token[1:]\n neg = True\n if token.startswith(compat.b("0x")):\n result = int(token, 16) # hexadecimal\n elif token.startswith(compat.b("0b")):\n result = int(token[2:], 2) # binary\n elif token.startswith(compat.b("0o")):\n result = int(token, 8) # octal\n else:\n try:\n result = int(token) # decimal\n except ValueError:\n result = int(token, 16) # hexadecimal (no "0x" prefix)\n if neg:\n result = -result\n return result\n\n @staticmethod\n def address(token):\n """\n Convert numeric strings into memory addresses.\n\n @type token: str\n @param token: String to parse.\n\n @rtype: int\n @return: Parsed integer value.\n """\n return int(token, 16)\n\n @staticmethod\n def hexadecimal(token):\n """\n Convert a strip of hexadecimal numbers into binary data.\n\n @type token: str\n @param token: String to parse.\n\n @rtype: str\n @return: Parsed string value.\n """\n token = "".join([c for c in token if c.isalnum()])\n if len(token) % 2 != 0:\n raise ValueError("Missing characters in hex data")\n data = ""\n for i in compat.xrange(0, len(token), 2):\n x = token[i : i + 2]\n d = int(x, 16)\n s = struct.pack("<B", d)\n data += s\n return data\n\n @staticmethod\n def pattern(token):\n """\n Convert an hexadecimal search pattern into a POSIX regular expression.\n\n For example, the following pattern::\n\n "B8 0? ?0 ?? ??"\n\n Would match the following data::\n\n "B8 0D F0 AD BA" # mov eax, 0xBAADF00D\n\n @type token: str\n @param token: String to parse.\n\n @rtype: str\n @return: Parsed string value.\n """\n token = "".join([c for c in token if c == "?" or c.isalnum()])\n if len(token) % 2 != 0:\n raise ValueError("Missing characters in hex data")\n regexp = ""\n for i in compat.xrange(0, len(token), 2):\n x = token[i : i + 2]\n if x == "??":\n regexp += "."\n elif x[0] == "?":\n f = "\\x%%.1x%s" % x[1]\n x = "".join([f % c for c in compat.xrange(0, 0x10)])\n regexp = "%s[%s]" % (regexp, x)\n elif x[1] == "?":\n f = "\\x%s%%.1x" % x[0]\n x = "".join([f % c for c in compat.xrange(0, 0x10)])\n regexp = "%s[%s]" % (regexp, x)\n else:\n regexp = "%s\\x%s" % (regexp, x)\n return regexp\n\n @staticmethod\n def is_pattern(token):\n """\n Determine if the given argument is a valid hexadecimal pattern to be\n used with L{pattern}.\n\n @type token: str\n @param token: String to parse.\n\n @rtype: bool\n @return:\n C{True} if it's a valid hexadecimal pattern, C{False} otherwise.\n """\n return re.match(r"^(?:[\?A-Fa-f0-9][\?A-Fa-f0-9]\s*)+$", token)\n\n @classmethod\n def integer_list_file(cls, filename):\n """\n Read a list of integers from a file.\n\n The file format is:\n\n - # anywhere in the line begins a comment\n - leading and trailing spaces are ignored\n - empty lines are ignored\n - integers can be specified as:\n - decimal numbers ("100" is 100)\n - hexadecimal numbers ("0x100" is 256)\n - binary numbers ("0b100" is 4)\n - octal numbers ("0100" is 64)\n\n @type filename: str\n @param filename: Name of the file to read.\n\n @rtype: list( int )\n @return: List of integers read from the file.\n """\n count = 0\n result = list()\n fd = open(filename, "r")\n for line in fd:\n count = count + 1\n if "#" in line:\n line = line[: line.find("#")]\n line = line.strip()\n if line:\n try:\n value = cls.integer(line)\n except ValueError:\n e = sys.exc_info()[1]\n msg = "Error in line %d of %s: %s"\n msg = msg % (count, filename, str(e))\n raise ValueError(msg)\n result.append(value)\n return result\n\n @classmethod\n def string_list_file(cls, filename):\n """\n Read a list of string values from a file.\n\n The file format is:\n\n - # anywhere in the line begins a comment\n - leading and trailing spaces are ignored\n - empty lines are ignored\n - strings cannot span over a single line\n\n @type filename: str\n @param filename: Name of the file to read.\n\n @rtype: list\n @return: List of integers and strings read from the file.\n """\n count = 0\n result = list()\n fd = open(filename, "r")\n for line in fd:\n count = count + 1\n if "#" in line:\n line = line[: line.find("#")]\n line = line.strip()\n if line:\n result.append(line)\n return result\n\n @classmethod\n def mixed_list_file(cls, filename):\n """\n Read a list of mixed values from a file.\n\n The file format is:\n\n - # anywhere in the line begins a comment\n - leading and trailing spaces are ignored\n - empty lines are ignored\n - strings cannot span over a single line\n - integers can be specified as:\n - decimal numbers ("100" is 100)\n - hexadecimal numbers ("0x100" is 256)\n - binary numbers ("0b100" is 4)\n - octal numbers ("0100" is 64)\n\n @type filename: str\n @param filename: Name of the file to read.\n\n @rtype: list\n @return: List of integers and strings read from the file.\n """\n count = 0\n result = list()\n fd = open(filename, "r")\n for line in fd:\n count = count + 1\n if "#" in line:\n line = line[: line.find("#")]\n line = line.strip()\n if line:\n try:\n value = cls.integer(line)\n except ValueError:\n value = line\n result.append(value)\n return result\n\n\n# ------------------------------------------------------------------------------\n\n\nclass HexOutput(StaticClass):\n """\n Static functions for user output parsing.\n The counterparts for each method are in the L{HexInput} class.\n\n @type integer_size: int\n @cvar integer_size: Default size in characters of an outputted integer.\n This value is platform dependent.\n\n @type address_size: int\n @cvar address_size: Default Number of bits of the target architecture.\n This value is platform dependent.\n """\n\n integer_size = (win32.SIZEOF(win32.DWORD) * 2) + 2\n address_size = (win32.SIZEOF(win32.SIZE_T) * 2) + 2\n\n @classmethod\n def integer(cls, integer, bits=None):\n """\n @type integer: int\n @param integer: Integer.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexOutput.integer_size}\n\n @rtype: str\n @return: Text output.\n """\n if bits is None:\n integer_size = cls.integer_size\n else:\n integer_size = (bits / 4) + 2\n if integer >= 0:\n return ("0x%%.%dx" % (integer_size - 2)) % integer\n return ("-0x%%.%dx" % (integer_size - 2)) % -integer\n\n @classmethod\n def address(cls, address, bits=None):\n """\n @type address: int\n @param address: Memory address.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexOutput.address_size}\n\n @rtype: str\n @return: Text output.\n """\n if bits is None:\n address_size = cls.address_size\n bits = win32.bits\n else:\n address_size = (bits / 4) + 2\n if address < 0:\n address = ((2**bits) - 1) ^ ~address\n return ("0x%%.%dx" % (address_size - 2)) % address\n\n @staticmethod\n def hexadecimal(data):\n """\n Convert binary data to a string of hexadecimal numbers.\n\n @type data: str\n @param data: Binary data.\n\n @rtype: str\n @return: Hexadecimal representation.\n """\n return HexDump.hexadecimal(data, separator="")\n\n @classmethod\n def integer_list_file(cls, filename, values, bits=None):\n """\n Write a list of integers to a file.\n If a file of the same name exists, it's contents are replaced.\n\n See L{HexInput.integer_list_file} for a description of the file format.\n\n @type filename: str\n @param filename: Name of the file to write.\n\n @type values: list( int )\n @param values: List of integers to write to the file.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexOutput.integer_size}\n """\n fd = open(filename, "w")\n for integer in values:\n print >> fd, cls.integer(integer, bits)\n fd.close()\n\n @classmethod\n def string_list_file(cls, filename, values):\n """\n Write a list of strings to a file.\n If a file of the same name exists, it's contents are replaced.\n\n See L{HexInput.string_list_file} for a description of the file format.\n\n @type filename: str\n @param filename: Name of the file to write.\n\n @type values: list( int )\n @param values: List of strings to write to the file.\n """\n fd = open(filename, "w")\n for string in values:\n print >> fd, string\n fd.close()\n\n @classmethod\n def mixed_list_file(cls, filename, values, bits):\n """\n Write a list of mixed values to a file.\n If a file of the same name exists, it's contents are replaced.\n\n See L{HexInput.mixed_list_file} for a description of the file format.\n\n @type filename: str\n @param filename: Name of the file to write.\n\n @type values: list( int )\n @param values: List of mixed values to write to the file.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexOutput.integer_size}\n """\n fd = open(filename, "w")\n for original in values:\n try:\n parsed = cls.integer(original, bits)\n except TypeError:\n parsed = repr(original)\n print >> fd, parsed\n fd.close()\n\n\n# ------------------------------------------------------------------------------\n\n\nclass HexDump(StaticClass):\n """\n Static functions for hexadecimal dumps.\n\n @type integer_size: int\n @cvar integer_size: Size in characters of an outputted integer.\n This value is platform dependent.\n\n @type address_size: int\n @cvar address_size: Size in characters of an outputted address.\n This value is platform dependent.\n """\n\n integer_size = win32.SIZEOF(win32.DWORD) * 2\n address_size = win32.SIZEOF(win32.SIZE_T) * 2\n\n @classmethod\n def integer(cls, integer, bits=None):\n """\n @type integer: int\n @param integer: Integer.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.integer_size}\n\n @rtype: str\n @return: Text output.\n """\n if bits is None:\n integer_size = cls.integer_size\n else:\n integer_size = bits / 4\n return ("%%.%dX" % integer_size) % integer\n\n @classmethod\n def address(cls, address, bits=None):\n """\n @type address: int\n @param address: Memory address.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @rtype: str\n @return: Text output.\n """\n if bits is None:\n address_size = cls.address_size\n bits = win32.bits\n else:\n address_size = bits / 4\n if address < 0:\n address = ((2**bits) - 1) ^ ~address\n return ("%%.%dX" % address_size) % address\n\n @staticmethod\n def printable(data):\n """\n Replace unprintable characters with dots.\n\n @type data: str\n @param data: Binary data.\n\n @rtype: str\n @return: Printable text.\n """\n result = ""\n for c in data:\n if 32 < ord(c) < 128:\n result += c\n else:\n result += "."\n return result\n\n @staticmethod\n def hexadecimal(data, separator=""):\n """\n Convert binary data to a string of hexadecimal numbers.\n\n @type data: str\n @param data: Binary data.\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each character.\n\n @rtype: str\n @return: Hexadecimal representation.\n """\n return separator.join(["%.2x" % ord(c) for c in data])\n\n @staticmethod\n def hexa_word(data, separator=" "):\n """\n Convert binary data to a string of hexadecimal WORDs.\n\n @type data: str\n @param data: Binary data.\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each WORD.\n\n @rtype: str\n @return: Hexadecimal representation.\n """\n if len(data) & 1 != 0:\n data += "\0"\n return separator.join(["%.4x" % struct.unpack("<H", data[i : i + 2])[0] for i in compat.xrange(0, len(data), 2)])\n\n @staticmethod\n def hexa_dword(data, separator=" "):\n """\n Convert binary data to a string of hexadecimal DWORDs.\n\n @type data: str\n @param data: Binary data.\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each DWORD.\n\n @rtype: str\n @return: Hexadecimal representation.\n """\n if len(data) & 3 != 0:\n data += "\0" * (4 - (len(data) & 3))\n return separator.join(["%.8x" % struct.unpack("<L", data[i : i + 4])[0] for i in compat.xrange(0, len(data), 4)])\n\n @staticmethod\n def hexa_qword(data, separator=" "):\n """\n Convert binary data to a string of hexadecimal QWORDs.\n\n @type data: str\n @param data: Binary data.\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each QWORD.\n\n @rtype: str\n @return: Hexadecimal representation.\n """\n if len(data) & 7 != 0:\n data += "\0" * (8 - (len(data) & 7))\n return separator.join(["%.16x" % struct.unpack("<Q", data[i : i + 8])[0] for i in compat.xrange(0, len(data), 8)])\n\n @classmethod\n def hexline(cls, data, separator=" ", width=None):\n """\n Dump a line of hexadecimal numbers from binary data.\n\n @type data: str\n @param data: Binary data.\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each character.\n\n @type width: int\n @param width:\n (Optional) Maximum number of characters to convert per text line.\n This value is also used for padding.\n\n @rtype: str\n @return: Multiline output text.\n """\n if width is None:\n fmt = "%s %s"\n else:\n fmt = "%%-%ds %%-%ds" % ((len(separator) + 2) * width - 1, width)\n return fmt % (cls.hexadecimal(data, separator), cls.printable(data))\n\n @classmethod\n def hexblock(cls, data, address=None, bits=None, separator=" ", width=8):\n """\n Dump a block of hexadecimal numbers from binary data.\n Also show a printable text version of the data.\n\n @type data: str\n @param data: Binary data.\n\n @type address: str\n @param address: Memory address where the data was read from.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each character.\n\n @type width: int\n @param width:\n (Optional) Maximum number of characters to convert per text line.\n\n @rtype: str\n @return: Multiline output text.\n """\n return cls.hexblock_cb(cls.hexline, data, address, bits, width, cb_kwargs={"width": width, "separator": separator})\n\n @classmethod\n def hexblock_cb(cls, callback, data, address=None, bits=None, width=16, cb_args=(), cb_kwargs={}):\n """\n Dump a block of binary data using a callback function to convert each\n line of text.\n\n @type callback: function\n @param callback: Callback function to convert each line of data.\n\n @type data: str\n @param data: Binary data.\n\n @type address: str\n @param address:\n (Optional) Memory address where the data was read from.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @type cb_args: str\n @param cb_args:\n (Optional) Arguments to pass to the callback function.\n\n @type cb_kwargs: str\n @param cb_kwargs:\n (Optional) Keyword arguments to pass to the callback function.\n\n @type width: int\n @param width:\n (Optional) Maximum number of bytes to convert per text line.\n\n @rtype: str\n @return: Multiline output text.\n """\n result = ""\n if address is None:\n for i in compat.xrange(0, len(data), width):\n result = "%s%s\n" % (result, callback(data[i : i + width], *cb_args, **cb_kwargs))\n else:\n for i in compat.xrange(0, len(data), width):\n result = "%s%s: %s\n" % (result, cls.address(address, bits), callback(data[i : i + width], *cb_args, **cb_kwargs))\n address += width\n return result\n\n @classmethod\n def hexblock_byte(cls, data, address=None, bits=None, separator=" ", width=16):\n """\n Dump a block of hexadecimal BYTEs from binary data.\n\n @type data: str\n @param data: Binary data.\n\n @type address: str\n @param address: Memory address where the data was read from.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each BYTE.\n\n @type width: int\n @param width:\n (Optional) Maximum number of BYTEs to convert per text line.\n\n @rtype: str\n @return: Multiline output text.\n """\n return cls.hexblock_cb(cls.hexadecimal, data, address, bits, width, cb_kwargs={"separator": separator})\n\n @classmethod\n def hexblock_word(cls, data, address=None, bits=None, separator=" ", width=8):\n """\n Dump a block of hexadecimal WORDs from binary data.\n\n @type data: str\n @param data: Binary data.\n\n @type address: str\n @param address: Memory address where the data was read from.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each WORD.\n\n @type width: int\n @param width:\n (Optional) Maximum number of WORDs to convert per text line.\n\n @rtype: str\n @return: Multiline output text.\n """\n return cls.hexblock_cb(cls.hexa_word, data, address, bits, width * 2, cb_kwargs={"separator": separator})\n\n @classmethod\n def hexblock_dword(cls, data, address=None, bits=None, separator=" ", width=4):\n """\n Dump a block of hexadecimal DWORDs from binary data.\n\n @type data: str\n @param data: Binary data.\n\n @type address: str\n @param address: Memory address where the data was read from.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each DWORD.\n\n @type width: int\n @param width:\n (Optional) Maximum number of DWORDs to convert per text line.\n\n @rtype: str\n @return: Multiline output text.\n """\n return cls.hexblock_cb(cls.hexa_dword, data, address, bits, width * 4, cb_kwargs={"separator": separator})\n\n @classmethod\n def hexblock_qword(cls, data, address=None, bits=None, separator=" ", width=2):\n """\n Dump a block of hexadecimal QWORDs from binary data.\n\n @type data: str\n @param data: Binary data.\n\n @type address: str\n @param address: Memory address where the data was read from.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each QWORD.\n\n @type width: int\n @param width:\n (Optional) Maximum number of QWORDs to convert per text line.\n\n @rtype: str\n @return: Multiline output text.\n """\n return cls.hexblock_cb(cls.hexa_qword, data, address, bits, width * 8, cb_kwargs={"separator": separator})\n\n\n# ------------------------------------------------------------------------------\n\n# TODO: implement an ANSI parser to simplify using colors\n\n\nclass Color(object):\n """\n Colored console output.\n """\n\n @staticmethod\n def _get_text_attributes():\n return win32.GetConsoleScreenBufferInfo().wAttributes\n\n @staticmethod\n def _set_text_attributes(wAttributes):\n win32.SetConsoleTextAttribute(wAttributes=wAttributes)\n\n # --------------------------------------------------------------------------\n\n @classmethod\n def can_use_colors(cls):\n """\n Determine if we can use colors.\n\n Colored output only works when the output is a real console, and fails\n when redirected to a file or pipe. Call this method before issuing a\n call to any other method of this class to make sure it's actually\n possible to use colors.\n\n @rtype: bool\n @return: C{True} if it's possible to output text with color,\n C{False} otherwise.\n """\n try:\n cls._get_text_attributes()\n return True\n except Exception:\n return False\n\n @classmethod\n def reset(cls):\n "Reset the colors to the default values."\n cls._set_text_attributes(win32.FOREGROUND_GREY)\n\n # --------------------------------------------------------------------------\n\n # @classmethod\n # def underscore(cls, on = True):\n # wAttributes = cls._get_text_attributes()\n # if on:\n # wAttributes |= win32.COMMON_LVB_UNDERSCORE\n # else:\n # wAttributes &= ~win32.COMMON_LVB_UNDERSCORE\n # cls._set_text_attributes(wAttributes)\n\n # --------------------------------------------------------------------------\n\n @classmethod\n def default(cls):\n "Make the current foreground color the default."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_GREY\n wAttributes &= ~win32.FOREGROUND_INTENSITY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def light(cls):\n "Make the current foreground color light."\n wAttributes = cls._get_text_attributes()\n wAttributes |= win32.FOREGROUND_INTENSITY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def dark(cls):\n "Make the current foreground color dark."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_INTENSITY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def black(cls):\n "Make the text foreground color black."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n # wAttributes |= win32.FOREGROUND_BLACK\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def white(cls):\n "Make the text foreground color white."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_GREY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def red(cls):\n "Make the text foreground color red."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_RED\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def green(cls):\n "Make the text foreground color green."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_GREEN\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def blue(cls):\n "Make the text foreground color blue."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_BLUE\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def cyan(cls):\n "Make the text foreground color cyan."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_CYAN\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def magenta(cls):\n "Make the text foreground color magenta."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_MAGENTA\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def yellow(cls):\n "Make the text foreground color yellow."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.FOREGROUND_MASK\n wAttributes |= win32.FOREGROUND_YELLOW\n cls._set_text_attributes(wAttributes)\n\n # --------------------------------------------------------------------------\n\n @classmethod\n def bk_default(cls):\n "Make the current background color the default."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n # wAttributes |= win32.BACKGROUND_BLACK\n wAttributes &= ~win32.BACKGROUND_INTENSITY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_light(cls):\n "Make the current background color light."\n wAttributes = cls._get_text_attributes()\n wAttributes |= win32.BACKGROUND_INTENSITY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_dark(cls):\n "Make the current background color dark."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_INTENSITY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_black(cls):\n "Make the text background color black."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n # wAttributes |= win32.BACKGROUND_BLACK\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_white(cls):\n "Make the text background color white."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n wAttributes |= win32.BACKGROUND_GREY\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_red(cls):\n "Make the text background color red."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n wAttributes |= win32.BACKGROUND_RED\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_green(cls):\n "Make the text background color green."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n wAttributes |= win32.BACKGROUND_GREEN\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_blue(cls):\n "Make the text background color blue."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n wAttributes |= win32.BACKGROUND_BLUE\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_cyan(cls):\n "Make the text background color cyan."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n wAttributes |= win32.BACKGROUND_CYAN\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_magenta(cls):\n "Make the text background color magenta."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n wAttributes |= win32.BACKGROUND_MAGENTA\n cls._set_text_attributes(wAttributes)\n\n @classmethod\n def bk_yellow(cls):\n "Make the text background color yellow."\n wAttributes = cls._get_text_attributes()\n wAttributes &= ~win32.BACKGROUND_MASK\n wAttributes |= win32.BACKGROUND_YELLOW\n cls._set_text_attributes(wAttributes)\n\n\n# ------------------------------------------------------------------------------\n\n# TODO: another class for ASCII boxes\n\n\nclass Table(object):\n """\n Text based table. The number of columns and the width of each column\n is automatically calculated.\n """\n\n def __init__(self, sep=" "):\n """\n @type sep: str\n @param sep: Separator between cells in each row.\n """\n self.__cols = list()\n self.__width = list()\n self.__sep = sep\n\n def addRow(self, *row):\n """\n Add a row to the table. All items are converted to strings.\n\n @type row: tuple\n @keyword row: Each argument is a cell in the table.\n """\n row = [str(item) for item in row]\n len_row = [len(item) for item in row]\n width = self.__width\n len_old = len(width)\n len_new = len(row)\n known = min(len_old, len_new)\n missing = len_new - len_old\n if missing > 0:\n width.extend(len_row[-missing:])\n elif missing < 0:\n len_row.extend([0] * (-missing))\n self.__width = [max(width[i], len_row[i]) for i in compat.xrange(len(len_row))]\n self.__cols.append(row)\n\n def justify(self, column, direction):\n """\n Make the text in a column left or right justified.\n\n @type column: int\n @param column: Index of the column.\n\n @type direction: int\n @param direction:\n C{-1} to justify left,\n C{1} to justify right.\n\n @raise IndexError: Bad column index.\n @raise ValueError: Bad direction value.\n """\n if direction == -1:\n self.__width[column] = abs(self.__width[column])\n elif direction == 1:\n self.__width[column] = -abs(self.__width[column])\n else:\n raise ValueError("Bad direction value.")\n\n def getWidth(self):\n """\n Get the width of the text output for the table.\n\n @rtype: int\n @return: Width in characters for the text output,\n including the newline character.\n """\n width = 0\n if self.__width:\n width = sum(abs(x) for x in self.__width)\n width = width + len(self.__width) * len(self.__sep) + 1\n return width\n\n def getOutput(self):\n """\n Get the text output for the table.\n\n @rtype: str\n @return: Text output.\n """\n return "%s\n" % "\n".join(self.yieldOutput())\n\n def yieldOutput(self):\n """\n Generate the text output for the table.\n\n @rtype: generator of str\n @return: Text output.\n """\n width = self.__width\n if width:\n num_cols = len(width)\n fmt = ["%%%ds" % -w for w in width]\n if width[-1] > 0:\n fmt[-1] = "%s"\n fmt = self.__sep.join(fmt)\n for row in self.__cols:\n row.extend([""] * (num_cols - len(row)))\n yield fmt % tuple(row)\n\n def show(self):\n """\n Print the text output for the table.\n """\n print(self.getOutput())\n\n\n# ------------------------------------------------------------------------------\n\n\nclass CrashDump(StaticClass):\n """\n Static functions for crash dumps.\n\n @type reg_template: str\n @cvar reg_template: Template for the L{dump_registers} method.\n """\n\n # Templates for the dump_registers method.\n reg_template = {\n win32.ARCH_I386: (\n "eax=%(Eax).8x ebx=%(Ebx).8x ecx=%(Ecx).8x edx=%(Edx).8x esi=%(Esi).8x edi=%(Edi).8x\n"\n "eip=%(Eip).8x esp=%(Esp).8x ebp=%(Ebp).8x %(efl_dump)s\n"\n "cs=%(SegCs).4x ss=%(SegSs).4x ds=%(SegDs).4x es=%(SegEs).4x fs=%(SegFs).4x gs=%(SegGs).4x efl=%(EFlags).8x\n"\n ),\n win32.ARCH_AMD64: (\n "rax=%(Rax).16x rbx=%(Rbx).16x rcx=%(Rcx).16x\n"\n "rdx=%(Rdx).16x rsi=%(Rsi).16x rdi=%(Rdi).16x\n"\n "rip=%(Rip).16x rsp=%(Rsp).16x rbp=%(Rbp).16x\n"\n " r8=%(R8).16x r9=%(R9).16x r10=%(R10).16x\n"\n "r11=%(R11).16x r12=%(R12).16x r13=%(R13).16x\n"\n "r14=%(R14).16x r15=%(R15).16x\n"\n "%(efl_dump)s\n"\n "cs=%(SegCs).4x ss=%(SegSs).4x ds=%(SegDs).4x es=%(SegEs).4x fs=%(SegFs).4x gs=%(SegGs).4x efl=%(EFlags).8x\n"\n ),\n }\n\n @staticmethod\n def dump_flags(efl):\n """\n Dump the x86 processor flags.\n The output mimics that of the WinDBG debugger.\n Used by L{dump_registers}.\n\n @type efl: int\n @param efl: Value of the eFlags register.\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if efl is None:\n return ""\n efl_dump = "iopl=%1d" % ((efl & 0x3000) >> 12)\n if efl & 0x100000:\n efl_dump += " vip"\n else:\n efl_dump += " "\n if efl & 0x80000:\n efl_dump += " vif"\n else:\n efl_dump += " "\n # 0x20000 ???\n if efl & 0x800:\n efl_dump += " ov" # Overflow\n else:\n efl_dump += " no" # No overflow\n if efl & 0x400:\n efl_dump += " dn" # Downwards\n else:\n efl_dump += " up" # Upwards\n if efl & 0x200:\n efl_dump += " ei" # Enable interrupts\n else:\n efl_dump += " di" # Disable interrupts\n # 0x100 trap flag\n if efl & 0x80:\n efl_dump += " ng" # Negative\n else:\n efl_dump += " pl" # Positive\n if efl & 0x40:\n efl_dump += " zr" # Zero\n else:\n efl_dump += " nz" # Nonzero\n if efl & 0x10:\n efl_dump += " ac" # Auxiliary carry\n else:\n efl_dump += " na" # No auxiliary carry\n # 0x8 ???\n if efl & 0x4:\n efl_dump += " pe" # Parity odd\n else:\n efl_dump += " po" # Parity even\n # 0x2 ???\n if efl & 0x1:\n efl_dump += " cy" # Carry\n else:\n efl_dump += " nc" # No carry\n return efl_dump\n\n @classmethod\n def dump_registers(cls, registers, arch=None):\n """\n Dump the x86/x64 processor register values.\n The output mimics that of the WinDBG debugger.\n\n @type registers: dict( str S{->} int )\n @param registers: Dictionary mapping register names to their values.\n\n @type arch: str\n @param arch: Architecture of the machine whose registers were dumped.\n Defaults to the current architecture.\n Currently only the following architectures are supported:\n - L{win32.ARCH_I386}\n - L{win32.ARCH_AMD64}\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if registers is None:\n return ""\n if arch is None:\n if "Eax" in registers:\n arch = win32.ARCH_I386\n elif "Rax" in registers:\n arch = win32.ARCH_AMD64\n else:\n arch = "Unknown"\n if arch not in cls.reg_template:\n msg = "Don't know how to dump the registers for architecture: %s"\n raise NotImplementedError(msg % arch)\n registers = registers.copy()\n registers["efl_dump"] = cls.dump_flags(registers["EFlags"])\n return cls.reg_template[arch] % registers\n\n @staticmethod\n def dump_registers_peek(registers, data, separator=" ", width=16):\n """\n Dump data pointed to by the given registers, if any.\n\n @type registers: dict( str S{->} int )\n @param registers: Dictionary mapping register names to their values.\n This value is returned by L{Thread.get_context}.\n\n @type data: dict( str S{->} str )\n @param data: Dictionary mapping register names to the data they point to.\n This value is returned by L{Thread.peek_pointers_in_registers}.\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if None in (registers, data):\n return ""\n names = compat.keys(data)\n names.sort()\n result = ""\n for reg_name in names:\n tag = reg_name.lower()\n dumped = HexDump.hexline(data[reg_name], separator, width)\n result += "%s -> %s\n" % (tag, dumped)\n return result\n\n @staticmethod\n def dump_data_peek(data, base=0, separator=" ", width=16, bits=None):\n """\n Dump data from pointers guessed within the given binary data.\n\n @type data: str\n @param data: Dictionary mapping offsets to the data they point to.\n\n @type base: int\n @param base: Base offset.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if data is None:\n return ""\n pointers = compat.keys(data)\n pointers.sort()\n result = ""\n for offset in pointers:\n dumped = HexDump.hexline(data[offset], separator, width)\n address = HexDump.address(base + offset, bits)\n result += "%s -> %s\n" % (address, dumped)\n return result\n\n @staticmethod\n def dump_stack_peek(data, separator=" ", width=16, arch=None):\n """\n Dump data from pointers guessed within the given stack dump.\n\n @type data: str\n @param data: Dictionary mapping stack offsets to the data they point to.\n\n @type separator: str\n @param separator:\n Separator between the hexadecimal representation of each character.\n\n @type width: int\n @param width:\n (Optional) Maximum number of characters to convert per text line.\n This value is also used for padding.\n\n @type arch: str\n @param arch: Architecture of the machine whose registers were dumped.\n Defaults to the current architecture.\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if data is None:\n return ""\n if arch is None:\n arch = win32.arch\n pointers = compat.keys(data)\n pointers.sort()\n result = ""\n if pointers:\n if arch == win32.ARCH_I386:\n spreg = "esp"\n elif arch == win32.ARCH_AMD64:\n spreg = "rsp"\n else:\n spreg = "STACK" # just a generic tag\n tag_fmt = "[%s+0x%%.%dx]" % (spreg, len("%x" % pointers[-1]))\n for offset in pointers:\n dumped = HexDump.hexline(data[offset], separator, width)\n tag = tag_fmt % offset\n result += "%s -> %s\n" % (tag, dumped)\n return result\n\n @staticmethod\n def dump_stack_trace(stack_trace, bits=None):\n """\n Dump a stack trace, as returned by L{Thread.get_stack_trace} with the\n C{bUseLabels} parameter set to C{False}.\n\n @type stack_trace: list( int, int, str )\n @param stack_trace: Stack trace as a list of tuples of\n ( return address, frame pointer, module filename )\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if not stack_trace:\n return ""\n table = Table()\n table.addRow("Frame", "Origin", "Module")\n for fp, ra, mod in stack_trace:\n fp_d = HexDump.address(fp, bits)\n ra_d = HexDump.address(ra, bits)\n table.addRow(fp_d, ra_d, mod)\n return table.getOutput()\n\n @staticmethod\n def dump_stack_trace_with_labels(stack_trace, bits=None):\n """\n Dump a stack trace,\n as returned by L{Thread.get_stack_trace_with_labels}.\n\n @type stack_trace: list( int, int, str )\n @param stack_trace: Stack trace as a list of tuples of\n ( return address, frame pointer, module filename )\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if not stack_trace:\n return ""\n table = Table()\n table.addRow("Frame", "Origin")\n for fp, label in stack_trace:\n table.addRow(HexDump.address(fp, bits), label)\n return table.getOutput()\n\n # TODO\n # + Instead of a star when EIP points to, it would be better to show\n # any register value (or other values like the exception address) that\n # points to a location in the dissassembled code.\n # + It'd be very useful to show some labels here.\n # + It'd be very useful to show register contents for code at EIP\n @staticmethod\n def dump_code(disassembly, pc=None, bLowercase=True, bits=None):\n """\n Dump a disassembly. Optionally mark where the program counter is.\n\n @type disassembly: list of tuple( int, int, str, str )\n @param disassembly: Disassembly dump as returned by\n L{Process.disassemble} or L{Thread.disassemble_around_pc}.\n\n @type pc: int\n @param pc: (Optional) Program counter.\n\n @type bLowercase: bool\n @param bLowercase: (Optional) If C{True} convert the code to lowercase.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if not disassembly:\n return ""\n table = Table(sep=" | ")\n for addr, size, code, dump in disassembly:\n if bLowercase:\n code = code.lower()\n if addr == pc:\n addr = " * %s" % HexDump.address(addr, bits)\n else:\n addr = " %s" % HexDump.address(addr, bits)\n table.addRow(addr, dump, code)\n table.justify(1, 1)\n return table.getOutput()\n\n @staticmethod\n def dump_code_line(disassembly_line, bShowAddress=True, bShowDump=True, bLowercase=True, dwDumpWidth=None, dwCodeWidth=None, bits=None):\n """\n Dump a single line of code. To dump a block of code use L{dump_code}.\n\n @type disassembly_line: tuple( int, int, str, str )\n @param disassembly_line: Single item of the list returned by\n L{Process.disassemble} or L{Thread.disassemble_around_pc}.\n\n @type bShowAddress: bool\n @param bShowAddress: (Optional) If C{True} show the memory address.\n\n @type bShowDump: bool\n @param bShowDump: (Optional) If C{True} show the hexadecimal dump.\n\n @type bLowercase: bool\n @param bLowercase: (Optional) If C{True} convert the code to lowercase.\n\n @type dwDumpWidth: int or None\n @param dwDumpWidth: (Optional) Width in characters of the hex dump.\n\n @type dwCodeWidth: int or None\n @param dwCodeWidth: (Optional) Width in characters of the code.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if bits is None:\n address_size = HexDump.address_size\n else:\n address_size = bits / 4\n (addr, size, code, dump) = disassembly_line\n dump = dump.replace(" ", "")\n result = list()\n fmt = ""\n if bShowAddress:\n result.append(HexDump.address(addr, bits))\n fmt += "%%%ds:" % address_size\n if bShowDump:\n result.append(dump)\n if dwDumpWidth:\n fmt += " %%-%ds" % dwDumpWidth\n else:\n fmt += " %s"\n if bLowercase:\n code = code.lower()\n result.append(code)\n if dwCodeWidth:\n fmt += " %%-%ds" % dwCodeWidth\n else:\n fmt += " %s"\n return fmt % tuple(result)\n\n @staticmethod\n def dump_memory_map(memoryMap, mappedFilenames=None, bits=None):\n """\n Dump the memory map of a process. Optionally show the filenames for\n memory mapped files as well.\n\n @type memoryMap: list( L{win32.MemoryBasicInformation} )\n @param memoryMap: Memory map returned by L{Process.get_memory_map}.\n\n @type mappedFilenames: dict( int S{->} str )\n @param mappedFilenames: (Optional) Memory mapped filenames\n returned by L{Process.get_mapped_filenames}.\n\n @type bits: int\n @param bits:\n (Optional) Number of bits of the target architecture.\n The default is platform dependent. See: L{HexDump.address_size}\n\n @rtype: str\n @return: Text suitable for logging.\n """\n if not memoryMap:\n return ""\n\n table = Table()\n if mappedFilenames:\n table.addRow("Address", "Size", "State", "Access", "Type", "File")\n else:\n table.addRow("Address", "Size", "State", "Access", "Type")\n\n # For each memory block in the map...\n for mbi in memoryMap:\n # Address and size of memory block.\n BaseAddress = HexDump.address(mbi.BaseAddress, bits)\n RegionSize = HexDump.address(mbi.RegionSize, bits)\n\n # State (free or allocated).\n mbiState = mbi.State\n if mbiState == win32.MEM_RESERVE:\n State = "Reserved"\n elif mbiState == win32.MEM_COMMIT:\n State = "Commited"\n elif mbiState == win32.MEM_FREE:\n State = "Free"\n else:\n State = "Unknown"\n\n # Page protection bits (R/W/X/G).\n if mbiState != win32.MEM_COMMIT:\n Protect = ""\n else:\n mbiProtect = mbi.Protect\n if mbiProtect & win32.PAGE_NOACCESS:\n Protect = "--- "\n elif mbiProtect & win32.PAGE_READONLY:\n Protect = "R-- "\n elif mbiProtect & win32.PAGE_READWRITE:\n Protect = "RW- "\n elif mbiProtect & win32.PAGE_WRITECOPY:\n Protect = "RC- "\n elif mbiProtect & win32.PAGE_EXECUTE:\n Protect = "--X "\n elif mbiProtect & win32.PAGE_EXECUTE_READ:\n Protect = "R-X "\n elif mbiProtect & win32.PAGE_EXECUTE_READWRITE:\n Protect = "RWX "\n elif mbiProtect & win32.PAGE_EXECUTE_WRITECOPY:\n Protect = "RCX "\n else:\n Protect = "??? "\n if mbiProtect & win32.PAGE_GUARD:\n Protect += "G"\n else:\n Protect += "-"\n if mbiProtect & win32.PAGE_NOCACHE:\n Protect += "N"\n else:\n Protect += "-"\n if mbiProtect & win32.PAGE_WRITECOMBINE:\n Protect += "W"\n else:\n Protect += "-"\n\n # Type (file mapping, executable image, or private memory).\n mbiType = mbi.Type\n if mbiType == win32.MEM_IMAGE:\n Type = "Image"\n elif mbiType == win32.MEM_MAPPED:\n Type = "Mapped"\n elif mbiType == win32.MEM_PRIVATE:\n Type = "Private"\n elif mbiType == 0:\n Type = ""\n else:\n Type = "Unknown"\n\n # Output a row in the table.\n if mappedFilenames:\n FileName = mappedFilenames.get(mbi.BaseAddress, "")\n table.addRow(BaseAddress, RegionSize, State, Protect, Type, FileName)\n else:\n table.addRow(BaseAddress, RegionSize, State, Protect, Type)\n\n # Return the table output.\n return table.getOutput()\n\n\n# ------------------------------------------------------------------------------\n\n\nclass DebugLog(StaticClass):\n "Static functions for debug logging."\n\n @staticmethod\n def log_text(text):\n """\n Log lines of text, inserting a timestamp.\n\n @type text: str\n @param text: Text to log.\n\n @rtype: str\n @return: Log line.\n """\n if text.endswith("\n"):\n text = text[: -len("\n")]\n # text = text.replace('\n', '\n\t\t') # text CSV\n ltime = time.strftime("%X")\n msecs = (time.time() % 1) * 1000\n return "[%s.%04d] %s" % (ltime, msecs, text)\n # return '[%s.%04d]\t%s' % (ltime, msecs, text) # text CSV\n\n @classmethod\n def log_event(cls, event, text=None):\n """\n Log lines of text associated with a debug event.\n\n @type event: L{Event}\n @param event: Event object.\n\n @type text: str\n @param text: (Optional) Text to log. If no text is provided the default\n is to show a description of the event itself.\n\n @rtype: str\n @return: Log line.\n """\n if not text:\n if event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT:\n what = event.get_exception_description()\n if event.is_first_chance():\n what = "%s (first chance)" % what\n else:\n what = "%s (second chance)" % what\n try:\n address = event.get_fault_address()\n except NotImplementedError:\n address = event.get_exception_address()\n else:\n what = event.get_event_name()\n address = event.get_thread().get_pc()\n process = event.get_process()\n label = process.get_label_at_address(address)\n address = HexDump.address(address, process.get_bits())\n if label:\n where = "%s (%s)" % (address, label)\n else:\n where = address\n text = "%s at %s" % (what, where)\n text = "pid %d tid %d: %s" % (event.get_pid(), event.get_tid(), text)\n # text = 'pid %d tid %d:\t%s' % (event.get_pid(), event.get_tid(), text) # text CSV\n return cls.log_text(text)\n\n\n# ------------------------------------------------------------------------------\n\n\nclass Logger(object):\n """\n Logs text to standard output and/or a text file.\n\n @type logfile: str or None\n @ivar logfile: Append messages to this text file.\n\n @type verbose: bool\n @ivar verbose: C{True} to print messages to standard output.\n\n @type fd: file\n @ivar fd: File object where log messages are printed to.\n C{None} if no log file is used.\n """\n\n def __init__(self, logfile=None, verbose=True):\n """\n @type logfile: str or None\n @param logfile: Append messages to this text file.\n\n @type verbose: bool\n @param verbose: C{True} to print messages to standard output.\n """\n self.verbose = verbose\n self.logfile = logfile\n if self.logfile:\n self.fd = open(self.logfile, "a+")\n\n def __logfile_error(self, e):\n """\n Shows an error message to standard error\n if the log file can't be written to.\n\n Used internally.\n\n @type e: Exception\n @param e: Exception raised when trying to write to the log file.\n """\n from sys import stderr\n\n msg = "Warning, error writing log file %s: %s\n"\n msg = msg % (self.logfile, str(e))\n stderr.write(DebugLog.log_text(msg))\n self.logfile = None\n self.fd = None\n\n def __do_log(self, text):\n """\n Writes the given text verbatim into the log file (if any)\n and/or standard input (if the verbose flag is turned on).\n\n Used internally.\n\n @type text: str\n @param text: Text to print.\n """\n if isinstance(text, compat.unicode):\n text = text.encode("cp1252")\n if self.verbose:\n print(text)\n if self.logfile:\n try:\n self.fd.writelines("%s\n" % text)\n except IOError:\n e = sys.exc_info()[1]\n self.__logfile_error(e)\n\n def log_text(self, text):\n """\n Log lines of text, inserting a timestamp.\n\n @type text: str\n @param text: Text to log.\n """\n self.__do_log(DebugLog.log_text(text))\n\n def log_event(self, event, text=None):\n """\n Log lines of text associated with a debug event.\n\n @type event: L{Event}\n @param event: Event object.\n\n @type text: str\n @param text: (Optional) Text to log. If no text is provided the default\n is to show a description of the event itself.\n """\n self.__do_log(DebugLog.log_event(event, text))\n\n def log_exc(self):\n """\n Log lines of text associated with the last Python exception.\n """\n self.__do_log("Exception raised: %s" % traceback.format_exc())\n\n def is_enabled(self):\n """\n Determines if the logger will actually print anything when the log_*\n methods are called.\n\n This may save some processing if the log text requires a lengthy\n calculation to prepare. If no log file is set and stdout logging\n is disabled, there's no point in preparing a log text that won't\n be shown to anyone.\n\n @rtype: bool\n @return: C{True} if a log file was set and/or standard output logging\n is enabled, or C{False} otherwise.\n """\n return self.verbose or self.logfile\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\textio.py
|
textio.py
|
Python
| 61,387 | 0.75 | 0.144481 | 0.048146 |
react-lib
| 241 |
2025-01-28T15:25:47.177927
|
GPL-3.0
| false |
e8918da94965777b530aff44278221a1
|
#!~/.wine/drive_c/Python25/python.exe\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2009-2014, Mario Vilas\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice,this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n"""\nWindow instrumentation.\n\n@group Instrumentation:\n Window\n"""\n\n__revision__ = "$Id$"\n\n__all__ = ["Window"]\n\nfrom winappdbg import win32\n\n# delayed imports\nProcess = None\nThread = None\n\n# ==============================================================================\n\n# Unlike Process, Thread and Module, there's no container for Window objects.\n# That's because Window objects don't really store any data besides the handle.\n\n# XXX TODO\n# * implement sending fake user input (mouse and keyboard messages)\n# * maybe implement low-level hooks? (they don't require a dll to be injected)\n\n# XXX TODO\n#\n# Will it be possible to implement window hooks too? That requires a DLL to be\n# injected in the target process. Perhaps with CPython it could be done easier,\n# compiling a native extension is the safe bet, but both require having a non\n# pure Python module, which is something I was trying to avoid so far.\n#\n# Another possibility would be to malloc some CC's in the target process and\n# point the hook callback to it. We'd need to have the remote procedure call\n# feature first as (I believe) the hook can't be set remotely in this case.\n\n\nclass Window(object):\n """\n Interface to an open window in the current desktop.\n\n @group Properties:\n get_handle, get_pid, get_tid,\n get_process, get_thread,\n set_process, set_thread,\n get_classname, get_style, get_extended_style,\n get_text, set_text,\n get_placement, set_placement,\n get_screen_rect, get_client_rect,\n screen_to_client, client_to_screen\n\n @group State:\n is_valid, is_visible, is_enabled, is_maximized, is_minimized, is_child,\n is_zoomed, is_iconic\n\n @group Navigation:\n get_parent, get_children, get_root, get_tree,\n get_child_at\n\n @group Instrumentation:\n enable, disable, show, hide, maximize, minimize, restore, move, kill\n\n @group Low-level access:\n send, post\n\n @type hWnd: int\n @ivar hWnd: Window handle.\n\n @type dwProcessId: int\n @ivar dwProcessId: Global ID of the process that owns this window.\n\n @type dwThreadId: int\n @ivar dwThreadId: Global ID of the thread that owns this window.\n\n @type process: L{Process}\n @ivar process: Process that owns this window.\n Use the L{get_process} method instead.\n\n @type thread: L{Thread}\n @ivar thread: Thread that owns this window.\n Use the L{get_thread} method instead.\n\n @type classname: str\n @ivar classname: Window class name.\n\n @type text: str\n @ivar text: Window text (caption).\n\n @type placement: L{win32.WindowPlacement}\n @ivar placement: Window placement in the desktop.\n """\n\n def __init__(self, hWnd=None, process=None, thread=None):\n """\n @type hWnd: int or L{win32.HWND}\n @param hWnd: Window handle.\n\n @type process: L{Process}\n @param process: (Optional) Process that owns this window.\n\n @type thread: L{Thread}\n @param thread: (Optional) Thread that owns this window.\n """\n self.hWnd = hWnd\n self.dwProcessId = None\n self.dwThreadId = None\n self.set_process(process)\n self.set_thread(thread)\n\n @property\n def _as_parameter_(self):\n """\n Compatibility with ctypes.\n Allows passing transparently a Window object to an API call.\n """\n return self.get_handle()\n\n def get_handle(self):\n """\n @rtype: int\n @return: Window handle.\n @raise ValueError: No window handle set.\n """\n if self.hWnd is None:\n raise ValueError("No window handle set!")\n return self.hWnd\n\n def get_pid(self):\n """\n @rtype: int\n @return: Global ID of the process that owns this window.\n """\n if self.dwProcessId is not None:\n return self.dwProcessId\n self.__get_pid_and_tid()\n return self.dwProcessId\n\n def get_tid(self):\n """\n @rtype: int\n @return: Global ID of the thread that owns this window.\n """\n if self.dwThreadId is not None:\n return self.dwThreadId\n self.__get_pid_and_tid()\n return self.dwThreadId\n\n def __get_pid_and_tid(self):\n "Internally used by get_pid() and get_tid()."\n self.dwThreadId, self.dwProcessId = win32.GetWindowThreadProcessId(self.get_handle())\n\n def __load_Process_class(self):\n global Process # delayed import\n if Process is None:\n from winappdbg.process import Process\n\n def __load_Thread_class(self):\n global Thread # delayed import\n if Thread is None:\n from winappdbg.thread import Thread\n\n def get_process(self):\n """\n @rtype: L{Process}\n @return: Parent Process object.\n """\n if self.__process is not None:\n return self.__process\n self.__load_Process_class()\n self.__process = Process(self.get_pid())\n return self.__process\n\n def set_process(self, process=None):\n """\n Manually set the parent process. Use with care!\n\n @type process: L{Process}\n @param process: (Optional) Process object. Use C{None} to autodetect.\n """\n if process is None:\n self.__process = None\n else:\n self.__load_Process_class()\n if not isinstance(process, Process):\n msg = "Parent process must be a Process instance, "\n msg += "got %s instead" % type(process)\n raise TypeError(msg)\n self.dwProcessId = process.get_pid()\n self.__process = process\n\n def get_thread(self):\n """\n @rtype: L{Thread}\n @return: Parent Thread object.\n """\n if self.__thread is not None:\n return self.__thread\n self.__load_Thread_class()\n self.__thread = Thread(self.get_tid())\n return self.__thread\n\n def set_thread(self, thread=None):\n """\n Manually set the thread process. Use with care!\n\n @type thread: L{Thread}\n @param thread: (Optional) Thread object. Use C{None} to autodetect.\n """\n if thread is None:\n self.__thread = None\n else:\n self.__load_Thread_class()\n if not isinstance(thread, Thread):\n msg = "Parent thread must be a Thread instance, "\n msg += "got %s instead" % type(thread)\n raise TypeError(msg)\n self.dwThreadId = thread.get_tid()\n self.__thread = thread\n\n def __get_window(self, hWnd):\n """\n User internally to get another Window from this one.\n It'll try to copy the parent Process and Thread references if possible.\n """\n window = Window(hWnd)\n if window.get_pid() == self.get_pid():\n window.set_process(self.get_process())\n if window.get_tid() == self.get_tid():\n window.set_thread(self.get_thread())\n return window\n\n # ------------------------------------------------------------------------------\n\n def get_classname(self):\n """\n @rtype: str\n @return: Window class name.\n\n @raise WindowsError: An error occured while processing this request.\n """\n return win32.GetClassName(self.get_handle())\n\n def get_style(self):\n """\n @rtype: int\n @return: Window style mask.\n\n @raise WindowsError: An error occured while processing this request.\n """\n return win32.GetWindowLongPtr(self.get_handle(), win32.GWL_STYLE)\n\n def get_extended_style(self):\n """\n @rtype: int\n @return: Window extended style mask.\n\n @raise WindowsError: An error occured while processing this request.\n """\n return win32.GetWindowLongPtr(self.get_handle(), win32.GWL_EXSTYLE)\n\n def get_text(self):\n """\n @see: L{set_text}\n @rtype: str\n @return: Window text (caption) on success, C{None} on error.\n """\n try:\n return win32.GetWindowText(self.get_handle())\n except WindowsError:\n return None\n\n def set_text(self, text):\n """\n Set the window text (caption).\n\n @see: L{get_text}\n\n @type text: str\n @param text: New window text.\n\n @raise WindowsError: An error occured while processing this request.\n """\n win32.SetWindowText(self.get_handle(), text)\n\n def get_placement(self):\n """\n Retrieve the window placement in the desktop.\n\n @see: L{set_placement}\n\n @rtype: L{win32.WindowPlacement}\n @return: Window placement in the desktop.\n\n @raise WindowsError: An error occured while processing this request.\n """\n return win32.GetWindowPlacement(self.get_handle())\n\n def set_placement(self, placement):\n """\n Set the window placement in the desktop.\n\n @see: L{get_placement}\n\n @type placement: L{win32.WindowPlacement}\n @param placement: Window placement in the desktop.\n\n @raise WindowsError: An error occured while processing this request.\n """\n win32.SetWindowPlacement(self.get_handle(), placement)\n\n def get_screen_rect(self):\n """\n Get the window coordinates in the desktop.\n\n @rtype: L{win32.Rect}\n @return: Rectangle occupied by the window in the desktop.\n\n @raise WindowsError: An error occured while processing this request.\n """\n return win32.GetWindowRect(self.get_handle())\n\n def get_client_rect(self):\n """\n Get the window's client area coordinates in the desktop.\n\n @rtype: L{win32.Rect}\n @return: Rectangle occupied by the window's client area in the desktop.\n\n @raise WindowsError: An error occured while processing this request.\n """\n cr = win32.GetClientRect(self.get_handle())\n cr.left, cr.top = self.client_to_screen(cr.left, cr.top)\n cr.right, cr.bottom = self.client_to_screen(cr.right, cr.bottom)\n return cr\n\n # XXX TODO\n # * properties x, y, width, height\n # * properties left, top, right, bottom\n\n process = property(get_process, set_process, doc="")\n thread = property(get_thread, set_thread, doc="")\n classname = property(get_classname, doc="")\n style = property(get_style, doc="")\n exstyle = property(get_extended_style, doc="")\n text = property(get_text, set_text, doc="")\n placement = property(get_placement, set_placement, doc="")\n\n # ------------------------------------------------------------------------------\n\n def client_to_screen(self, x, y):\n """\n Translates window client coordinates to screen coordinates.\n\n @note: This is a simplified interface to some of the functionality of\n the L{win32.Point} class.\n\n @see: {win32.Point.client_to_screen}\n\n @type x: int\n @param x: Horizontal coordinate.\n @type y: int\n @param y: Vertical coordinate.\n\n @rtype: tuple( int, int )\n @return: Translated coordinates in a tuple (x, y).\n\n @raise WindowsError: An error occured while processing this request.\n """\n return tuple(win32.ClientToScreen(self.get_handle(), (x, y)))\n\n def screen_to_client(self, x, y):\n """\n Translates window screen coordinates to client coordinates.\n\n @note: This is a simplified interface to some of the functionality of\n the L{win32.Point} class.\n\n @see: {win32.Point.screen_to_client}\n\n @type x: int\n @param x: Horizontal coordinate.\n @type y: int\n @param y: Vertical coordinate.\n\n @rtype: tuple( int, int )\n @return: Translated coordinates in a tuple (x, y).\n\n @raise WindowsError: An error occured while processing this request.\n """\n return tuple(win32.ScreenToClient(self.get_handle(), (x, y)))\n\n # ------------------------------------------------------------------------------\n\n def get_parent(self):\n """\n @see: L{get_children}\n @rtype: L{Window} or None\n @return: Parent window. Returns C{None} if the window has no parent.\n @raise WindowsError: An error occured while processing this request.\n """\n hWnd = win32.GetParent(self.get_handle())\n if hWnd:\n return self.__get_window(hWnd)\n\n def get_children(self):\n """\n @see: L{get_parent}\n @rtype: list( L{Window} )\n @return: List of child windows.\n @raise WindowsError: An error occured while processing this request.\n """\n return [self.__get_window(hWnd) for hWnd in win32.EnumChildWindows(self.get_handle())]\n\n def get_tree(self):\n """\n @see: L{get_root}\n @rtype: dict( L{Window} S{->} dict( ... ) )\n @return: Dictionary of dictionaries forming a tree of child windows.\n @raise WindowsError: An error occured while processing this request.\n """\n subtree = dict()\n for aWindow in self.get_children():\n subtree[aWindow] = aWindow.get_tree()\n return subtree\n\n def get_root(self):\n """\n @see: L{get_tree}\n @rtype: L{Window}\n @return: If this is a child window, return the top-level window it\n belongs to.\n If this window is already a top-level window, returns itself.\n @raise WindowsError: An error occured while processing this request.\n """\n hWnd = self.get_handle()\n history = set()\n hPrevWnd = hWnd\n while hWnd and hWnd not in history:\n history.add(hWnd)\n hPrevWnd = hWnd\n hWnd = win32.GetParent(hWnd)\n if hWnd in history:\n # See: https://docs.google.com/View?id=dfqd62nk_228h28szgz\n return self\n if hPrevWnd != self.get_handle():\n return self.__get_window(hPrevWnd)\n return self\n\n def get_child_at(self, x, y, bAllowTransparency=True):\n """\n Get the child window located at the given coordinates. If no such\n window exists an exception is raised.\n\n @see: L{get_children}\n\n @type x: int\n @param x: Horizontal coordinate.\n\n @type y: int\n @param y: Vertical coordinate.\n\n @type bAllowTransparency: bool\n @param bAllowTransparency: If C{True} transparent areas in windows are\n ignored, returning the window behind them. If C{False} transparent\n areas are treated just like any other area.\n\n @rtype: L{Window}\n @return: Child window at the requested position, or C{None} if there\n is no window at those coordinates.\n """\n try:\n if bAllowTransparency:\n hWnd = win32.RealChildWindowFromPoint(self.get_handle(), (x, y))\n else:\n hWnd = win32.ChildWindowFromPoint(self.get_handle(), (x, y))\n if hWnd:\n return self.__get_window(hWnd)\n except WindowsError:\n pass\n return None\n\n # ------------------------------------------------------------------------------\n\n def is_valid(self):\n """\n @rtype: bool\n @return: C{True} if the window handle is still valid.\n """\n return win32.IsWindow(self.get_handle())\n\n def is_visible(self):\n """\n @see: {show}, {hide}\n @rtype: bool\n @return: C{True} if the window is in a visible state.\n """\n return win32.IsWindowVisible(self.get_handle())\n\n def is_enabled(self):\n """\n @see: {enable}, {disable}\n @rtype: bool\n @return: C{True} if the window is in an enabled state.\n """\n return win32.IsWindowEnabled(self.get_handle())\n\n def is_maximized(self):\n """\n @see: L{maximize}\n @rtype: bool\n @return: C{True} if the window is maximized.\n """\n return win32.IsZoomed(self.get_handle())\n\n def is_minimized(self):\n """\n @see: L{minimize}\n @rtype: bool\n @return: C{True} if the window is minimized.\n """\n return win32.IsIconic(self.get_handle())\n\n def is_child(self):\n """\n @see: L{get_parent}\n @rtype: bool\n @return: C{True} if the window is a child window.\n """\n return win32.IsChild(self.get_handle())\n\n is_zoomed = is_maximized\n is_iconic = is_minimized\n\n # ------------------------------------------------------------------------------\n\n def enable(self):\n """\n Enable the user input for the window.\n\n @see: L{disable}\n\n @raise WindowsError: An error occured while processing this request.\n """\n win32.EnableWindow(self.get_handle(), True)\n\n def disable(self):\n """\n Disable the user input for the window.\n\n @see: L{enable}\n\n @raise WindowsError: An error occured while processing this request.\n """\n win32.EnableWindow(self.get_handle(), False)\n\n def show(self, bAsync=True):\n """\n Make the window visible.\n\n @see: L{hide}\n\n @type bAsync: bool\n @param bAsync: Perform the request asynchronously.\n\n @raise WindowsError: An error occured while processing this request.\n """\n if bAsync:\n win32.ShowWindowAsync(self.get_handle(), win32.SW_SHOW)\n else:\n win32.ShowWindow(self.get_handle(), win32.SW_SHOW)\n\n def hide(self, bAsync=True):\n """\n Make the window invisible.\n\n @see: L{show}\n\n @type bAsync: bool\n @param bAsync: Perform the request asynchronously.\n\n @raise WindowsError: An error occured while processing this request.\n """\n if bAsync:\n win32.ShowWindowAsync(self.get_handle(), win32.SW_HIDE)\n else:\n win32.ShowWindow(self.get_handle(), win32.SW_HIDE)\n\n def maximize(self, bAsync=True):\n """\n Maximize the window.\n\n @see: L{minimize}, L{restore}\n\n @type bAsync: bool\n @param bAsync: Perform the request asynchronously.\n\n @raise WindowsError: An error occured while processing this request.\n """\n if bAsync:\n win32.ShowWindowAsync(self.get_handle(), win32.SW_MAXIMIZE)\n else:\n win32.ShowWindow(self.get_handle(), win32.SW_MAXIMIZE)\n\n def minimize(self, bAsync=True):\n """\n Minimize the window.\n\n @see: L{maximize}, L{restore}\n\n @type bAsync: bool\n @param bAsync: Perform the request asynchronously.\n\n @raise WindowsError: An error occured while processing this request.\n """\n if bAsync:\n win32.ShowWindowAsync(self.get_handle(), win32.SW_MINIMIZE)\n else:\n win32.ShowWindow(self.get_handle(), win32.SW_MINIMIZE)\n\n def restore(self, bAsync=True):\n """\n Unmaximize and unminimize the window.\n\n @see: L{maximize}, L{minimize}\n\n @type bAsync: bool\n @param bAsync: Perform the request asynchronously.\n\n @raise WindowsError: An error occured while processing this request.\n """\n if bAsync:\n win32.ShowWindowAsync(self.get_handle(), win32.SW_RESTORE)\n else:\n win32.ShowWindow(self.get_handle(), win32.SW_RESTORE)\n\n def move(self, x=None, y=None, width=None, height=None, bRepaint=True):\n """\n Moves and/or resizes the window.\n\n @note: This is request is performed syncronously.\n\n @type x: int\n @param x: (Optional) New horizontal coordinate.\n\n @type y: int\n @param y: (Optional) New vertical coordinate.\n\n @type width: int\n @param width: (Optional) Desired window width.\n\n @type height: int\n @param height: (Optional) Desired window height.\n\n @type bRepaint: bool\n @param bRepaint:\n (Optional) C{True} if the window should be redrawn afterwards.\n\n @raise WindowsError: An error occured while processing this request.\n """\n if None in (x, y, width, height):\n rect = self.get_screen_rect()\n if x is None:\n x = rect.left\n if y is None:\n y = rect.top\n if width is None:\n width = rect.right - rect.left\n if height is None:\n height = rect.bottom - rect.top\n win32.MoveWindow(self.get_handle(), x, y, width, height, bRepaint)\n\n def kill(self):\n """\n Signals the program to quit.\n\n @note: This is an asyncronous request.\n\n @raise WindowsError: An error occured while processing this request.\n """\n self.post(win32.WM_QUIT)\n\n def send(self, uMsg, wParam=None, lParam=None, dwTimeout=None):\n """\n Send a low-level window message syncronically.\n\n @type uMsg: int\n @param uMsg: Message code.\n\n @param wParam:\n The type and meaning of this parameter depends on the message.\n\n @param lParam:\n The type and meaning of this parameter depends on the message.\n\n @param dwTimeout: Optional timeout for the operation.\n Use C{None} to wait indefinitely.\n\n @rtype: int\n @return: The meaning of the return value depends on the window message.\n Typically a value of C{0} means an error occured. You can get the\n error code by calling L{win32.GetLastError}.\n """\n if dwTimeout is None:\n return win32.SendMessage(self.get_handle(), uMsg, wParam, lParam)\n return win32.SendMessageTimeout(self.get_handle(), uMsg, wParam, lParam, win32.SMTO_ABORTIFHUNG | win32.SMTO_ERRORONEXIT, dwTimeout)\n\n def post(self, uMsg, wParam=None, lParam=None):\n """\n Post a low-level window message asyncronically.\n\n @type uMsg: int\n @param uMsg: Message code.\n\n @param wParam:\n The type and meaning of this parameter depends on the message.\n\n @param lParam:\n The type and meaning of this parameter depends on the message.\n\n @raise WindowsError: An error occured while sending the message.\n """\n win32.PostMessage(self.get_handle(), uMsg, wParam, lParam)\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\window.py
|
window.py
|
Python
| 24,770 | 0.95 | 0.164675 | 0.08985 |
node-utils
| 443 |
2025-07-06T14:38:20.988187
|
Apache-2.0
| false |
07f866b12b11a4014ff3752aea7a8aa3
|
#!~/.wine/drive_c/Python25/python.exe\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2009-2014, Mario Vilas\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice,this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n"""\nWindows application debugging engine for Python.\n\nby Mario Vilas (mvilas at gmail.com)\n\nProject: U{http://sourceforge.net/projects/winappdbg/}\n\nWeb: U{http://winappdbg.sourceforge.net/}\n\nBlog: U{http://breakingcode.wordpress.com}\n\n@group Debugging:\n Debug, EventHandler, EventSift, DebugLog\n\n@group Instrumentation:\n System, Process, Thread, Module, Window, Registry\n\n@group Disassemblers:\n Disassembler,\n BeaEngine, DistormEngine, PyDasmEngine\n\n@group Crash reporting:\n Crash, CrashDump, CrashDAO, CrashDictionary\n\n@group Memory search:\n Search,\n Pattern,\n BytePattern,\n TextPattern,\n RegExpPattern,\n HexPattern\n\n@group Debug events:\n Event,\n NoEvent,\n CreateProcessEvent,\n CreateThreadEvent,\n ExitProcessEvent,\n ExitThreadEvent,\n LoadDLLEvent,\n UnloadDLLEvent,\n OutputDebugStringEvent,\n RIPEvent,\n ExceptionEvent\n\n@group Win32 API wrappers:\n win32, Handle, ProcessHandle, ThreadHandle, FileHandle\n\n@group Helpers:\n HexInput, HexOutput, HexDump, Color, Table, Logger,\n PathOperations,\n MemoryAddresses,\n CustomAddressIterator,\n DataAddressIterator,\n ImageAddressIterator,\n MappedAddressIterator,\n ExecutableAddressIterator,\n ReadableAddressIterator,\n WriteableAddressIterator,\n ExecutableAndWriteableAddressIterator,\n DebugRegister,\n Regenerator\n\n@group Warnings:\n MixedBitsWarning, BreakpointWarning, BreakpointCallbackWarning,\n EventCallbackWarning, DebugSymbolsWarning, CrashWarning\n\n@group Deprecated classes:\n CrashContainer, CrashTable, CrashTableMSSQL,\n VolatileCrashContainer, DummyCrashContainer\n\n@type version_number: float\n@var version_number: This WinAppDbg major and minor version,\n as a floating point number. Use this for compatibility checking.\n\n@type version: str\n@var version: This WinAppDbg release version,\n as a printable string. Use this to show to the user.\n\n@undocumented: plugins\n"""\n\n__revision__ = "$Id$"\n\n# List of all public symbols\n__all__ = [\n # Library version\n "version",\n "version_number",\n # from breakpoint import *\n ## 'Breakpoint',\n ## 'CodeBreakpoint',\n ## 'PageBreakpoint',\n ## 'HardwareBreakpoint',\n ## 'Hook',\n ## 'ApiHook',\n ## 'BufferWatch',\n "BreakpointWarning",\n "BreakpointCallbackWarning",\n # from crash import *\n "Crash",\n "CrashWarning",\n "CrashDictionary",\n "CrashContainer",\n "CrashTable",\n "CrashTableMSSQL",\n "VolatileCrashContainer",\n "DummyCrashContainer",\n # from debug import *\n "Debug",\n "MixedBitsWarning",\n # from disasm import *\n "Disassembler",\n "BeaEngine",\n "DistormEngine",\n "PyDasmEngine",\n # from event import *\n "EventHandler",\n "EventSift",\n ## 'EventFactory',\n ## 'EventDispatcher',\n "EventCallbackWarning",\n "Event",\n ## 'NoEvent',\n "CreateProcessEvent",\n "CreateThreadEvent",\n "ExitProcessEvent",\n "ExitThreadEvent",\n "LoadDLLEvent",\n "UnloadDLLEvent",\n "OutputDebugStringEvent",\n "RIPEvent",\n "ExceptionEvent",\n # from interactive import *\n ## 'ConsoleDebugger',\n # from module import *\n "Module",\n "DebugSymbolsWarning",\n # from process import *\n "Process",\n # from system import *\n "System",\n # from search import *\n "Search",\n "Pattern",\n "BytePattern",\n "TextPattern",\n "RegExpPattern",\n "HexPattern",\n # from registry import *\n "Registry",\n # from textio import *\n "HexDump",\n "HexInput",\n "HexOutput",\n "Color",\n "Table",\n "CrashDump",\n "DebugLog",\n "Logger",\n # from thread import *\n "Thread",\n # from util import *\n "PathOperations",\n "MemoryAddresses",\n "CustomAddressIterator",\n "DataAddressIterator",\n "ImageAddressIterator",\n "MappedAddressIterator",\n "ExecutableAddressIterator",\n "ReadableAddressIterator",\n "WriteableAddressIterator",\n "ExecutableAndWriteableAddressIterator",\n "DebugRegister",\n # from window import *\n "Window",\n # import win32\n "win32",\n # from win32 import Handle, ProcessHandle, ThreadHandle, FileHandle\n "Handle",\n "ProcessHandle",\n "ThreadHandle",\n "FileHandle",\n]\n\n# Import all public symbols\nfrom winappdbg.breakpoint import *\nfrom winappdbg.crash import *\nfrom winappdbg.debug import *\nfrom winappdbg.disasm import *\nfrom winappdbg.event import *\nfrom winappdbg.interactive import *\nfrom winappdbg.module import *\nfrom winappdbg.process import *\nfrom winappdbg.registry import *\nfrom winappdbg.system import *\nfrom winappdbg.search import *\nfrom winappdbg.textio import *\nfrom winappdbg.thread import *\nfrom winappdbg.util import *\nfrom winappdbg.window import *\n\nimport winappdbg.win32\nfrom winappdbg.win32 import Handle, ProcessHandle, ThreadHandle, FileHandle\n\ntry:\n from sql import *\n\n __all__.append("CrashDAO")\nexcept ImportError:\n import warnings\n\n warnings.warn("No SQL database support present (missing dependencies?)", ImportWarning)\n\n# Library version\nversion_number = 1.5\nversion = "Version %s" % version_number\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__init__.py
|
__init__.py
|
Python
| 7,129 | 0.95 | 0.012146 | 0.272727 |
node-utils
| 84 |
2024-04-18T23:28:24.695734
|
GPL-3.0
| false |
c7a32aae73e0e42ce9d43e81f4f8fde2
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\context_amd64.cpython-313.pyc
|
context_amd64.cpython-313.pyc
|
Other
| 19,932 | 0.8 | 0.01227 | 0.012422 |
awesome-app
| 613 |
2024-05-16T10:16:36.422934
|
Apache-2.0
| false |
ad38dd1a396500693cbc99c9fb18e3f1
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\context_i386.cpython-313.pyc
|
context_i386.cpython-313.pyc
|
Other
| 11,865 | 0.8 | 0.022472 | 0.011494 |
vue-tools
| 110 |
2023-07-23T08:41:27.939911
|
MIT
| false |
4be64617c3ec2f8fccc89fbbbf6c3ba4
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\dbghelp.cpython-313.pyc
|
dbghelp.cpython-313.pyc
|
Other
| 35,718 | 0.8 | 0.015385 | 0.005181 |
vue-tools
| 663 |
2023-10-23T16:39:07.253422
|
Apache-2.0
| false |
4c253baf93bd80d98195d482c13b44ad
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\defines.cpython-313.pyc
|
defines.cpython-313.pyc
|
Other
| 22,518 | 0.95 | 0.133663 | 0 |
awesome-app
| 157 |
2024-07-18T10:56:09.736546
|
BSD-3-Clause
| false |
988df13c1cda5833ea5f75175f6bdf48
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\gdi32.cpython-313.pyc
|
gdi32.cpython-313.pyc
|
Other
| 13,734 | 0.8 | 0.00565 | 0 |
vue-tools
| 461 |
2024-02-06T07:58:18.494910
|
MIT
| false |
31941b70fde2aff830db2eebe6762250
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\ntdll.cpython-313.pyc
|
ntdll.cpython-313.pyc
|
Other
| 15,827 | 0.8 | 0.011905 | 0.060241 |
node-utils
| 26 |
2025-06-24T22:30:16.747230
|
Apache-2.0
| false |
45f3b98d1ad0686f0e8377e2108ef3b5
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\peb_teb.cpython-313.pyc
|
peb_teb.cpython-313.pyc
|
Other
| 61,001 | 0.6 | 0.000694 | 0.013928 |
node-utils
| 5 |
2024-04-02T15:31:40.504522
|
MIT
| false |
f6630865db1e112a20b301dac1e0804c
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\psapi.cpython-313.pyc
|
psapi.cpython-313.pyc
|
Other
| 13,174 | 0.8 | 0.009174 | 0 |
react-lib
| 31 |
2025-05-25T12:48:39.442434
|
GPL-3.0
| false |
a86a0827f70584a6f06cd782ec0faf57
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\shell32.cpython-313.pyc
|
shell32.cpython-313.pyc
|
Other
| 12,945 | 0.8 | 0.010638 | 0.022222 |
awesome-app
| 350 |
2023-10-02T10:34:13.702314
|
BSD-3-Clause
| false |
d836bdd711df50173165691518c06859
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\shlwapi.cpython-313.pyc
|
shlwapi.cpython-313.pyc
|
Other
| 28,559 | 0.8 | 0.006803 | 0 |
vue-tools
| 23 |
2023-12-31T11:58:00.719978
|
Apache-2.0
| false |
3de0ca2f1805528f68b8357a667e0582
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\user32.cpython-313.pyc
|
user32.cpython-313.pyc
|
Other
| 60,647 | 0.75 | 0.033841 | 0.001852 |
vue-tools
| 663 |
2024-12-17T23:27:27.724806
|
Apache-2.0
| false |
19a32afd965e125839e4e2329e187f78
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\version.cpython-313.pyc
|
version.cpython-313.pyc
|
Other
| 31,977 | 0.95 | 0.056497 | 0.009259 |
node-utils
| 833 |
2025-04-07T03:14:29.995058
|
GPL-3.0
| false |
ff3cfdf3a5007c987f2d2b8734e48056
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\wtsapi32.cpython-313.pyc
|
wtsapi32.cpython-313.pyc
|
Other
| 6,343 | 0.8 | 0.022222 | 0 |
awesome-app
| 356 |
2025-06-22T22:16:59.227129
|
MIT
| false |
dcea43bdc1544a39d2f94320f8e85db6
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\win32\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 1,994 | 0.8 | 0 | 0 |
react-lib
| 44 |
2024-10-16T00:00:22.178448
|
BSD-3-Clause
| false |
17ae6107579f96f6c669af0c9c0a3dcb
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\compat.cpython-313.pyc
|
compat.cpython-313.pyc
|
Other
| 6,723 | 0.95 | 0 | 0 |
python-kit
| 289 |
2024-12-03T01:27:25.761430
|
BSD-3-Clause
| false |
8404926ed336f2999ef975fa058962f9
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\crash.cpython-313.pyc
|
crash.cpython-313.pyc
|
Other
| 66,665 | 0.75 | 0.075047 | 0 |
react-lib
| 539 |
2025-04-24T09:09:25.667055
|
GPL-3.0
| false |
f6245c63d02f9b350ac49e5fa4b0fe87
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\debug.cpython-313.pyc
|
debug.cpython-313.pyc
|
Other
| 52,131 | 0.95 | 0.063275 | 0 |
python-kit
| 2 |
2023-09-15T01:12:50.431907
|
BSD-3-Clause
| false |
e3dd137224ced5b10c3347a3b4bed9b1
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\disasm.cpython-313.pyc
|
disasm.cpython-313.pyc
|
Other
| 19,865 | 0.95 | 0.032374 | 0 |
python-kit
| 763 |
2024-08-21T14:28:10.520866
|
GPL-3.0
| false |
845a9a2e799878abab055c2ebe8980e6
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\event.cpython-313.pyc
|
event.cpython-313.pyc
|
Other
| 67,251 | 0.75 | 0.083257 | 0.028261 |
vue-tools
| 485 |
2024-04-08T22:55:43.409567
|
MIT
| false |
f448470b779d36f9020cfc7628a153e2
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\interactive.cpython-313.pyc
|
interactive.cpython-313.pyc
|
Other
| 94,367 | 0.6 | 0.023055 | 0.005988 |
python-kit
| 912 |
2024-05-21T17:48:19.836941
|
GPL-3.0
| false |
8bbe9c052fbf963d68b8a47c1595a9c0
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\module.cpython-313.pyc
|
module.cpython-313.pyc
|
Other
| 62,672 | 0.75 | 0.105708 | 0 |
react-lib
| 615 |
2023-12-10T03:06:18.322119
|
BSD-3-Clause
| false |
da03e1685028927dd909dcc5612e9f64
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\registry.cpython-313.pyc
|
registry.cpython-313.pyc
|
Other
| 24,228 | 0.95 | 0.027027 | 0 |
node-utils
| 562 |
2024-12-23T21:23:19.053316
|
MIT
| false |
4ef8c4ae946281e2e6bb01ad1fba816c
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\search.cpython-313.pyc
|
search.cpython-313.pyc
|
Other
| 20,047 | 0.95 | 0.082294 | 0.012121 |
node-utils
| 658 |
2023-11-30T00:38:20.392575
|
Apache-2.0
| false |
f9e460b1de2080ddcffccf2ce9b01bdd
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\sql.cpython-313.pyc
|
sql.cpython-313.pyc
|
Other
| 33,827 | 0.95 | 0.041841 | 0.007246 |
node-utils
| 59 |
2023-08-31T07:49:23.495304
|
BSD-3-Clause
| false |
72a98a78a7d62a93074e088ea31a6d5d
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\system.cpython-313.pyc
|
system.cpython-313.pyc
|
Other
| 44,815 | 0.95 | 0.076037 | 0.021552 |
python-kit
| 440 |
2025-01-11T05:21:59.629322
|
GPL-3.0
| false |
f3c19eb83828f03b2c983850254d4fff
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\textio.cpython-313.pyc
|
textio.cpython-313.pyc
|
Other
| 64,412 | 0.75 | 0.045093 | 0 |
awesome-app
| 537 |
2024-02-18T09:58:09.991089
|
Apache-2.0
| false |
2351cad6bf78704db7a3b97aa42f0e53
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\thread.cpython-313.pyc
|
thread.cpython-313.pyc
|
Other
| 77,232 | 0.75 | 0.058775 | 0 |
node-utils
| 970 |
2024-06-14T21:15:50.383434
|
Apache-2.0
| false |
8b46ccebafb3fc4e430a394bc2159555
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\util.cpython-313.pyc
|
util.cpython-313.pyc
|
Other
| 29,798 | 0.95 | 0.082873 | 0 |
vue-tools
| 475 |
2025-02-22T01:08:28.023077
|
MIT
| false |
ad7f0fff963989520277f08f4788066b
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\window.cpython-313.pyc
|
window.cpython-313.pyc
|
Other
| 25,970 | 0.95 | 0.090909 | 0 |
react-lib
| 641 |
2024-11-12T02:54:11.591794
|
BSD-3-Clause
| false |
53bdb497d4090612aba224cf86618e6f
|
\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\winappdbg\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 4,241 | 0.8 | 0.020833 | 0 |
python-kit
| 478 |
2024-08-14T01:59:42.518420
|
MIT
| false |
aeaafb7e9c95cd4334999aa8babc28de
|
/* ****************************************************************************\n*\n* Copyright (c) Microsoft Corporation.\n*\n* This source code is subject to terms and conditions of the Apache License, Version 2.0. A\n* copy of the license can be found in the License.html file at the root of this distribution. If\n* you cannot locate the Apache License, Version 2.0, please send an email to\n* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound\n* by the terms of the Apache License, Version 2.0.\n*\n* You must not remove this notice, or any other, from this software.\n*\n* Contributor: Fabio Zadrozny\n*\n* Based on PyDebugAttach.cpp from PVTS. Windows only.\n*\n* https://github.com/Microsoft/PTVS/blob/master/Python/Product/PyDebugAttach/PyDebugAttach.cpp\n*\n* Initially we did an attach completely based on shellcode which got the\n* GIL called PyRun_SimpleString with the needed code and was done with it\n* (so, none of this code was needed).\n* Now, newer version of Python don't initialize threading by default, so,\n* most of this code is done only to overcome this limitation (and as a plus,\n* if there's no code running, we also pause the threads to make our code run).\n*\n* On Linux the approach is still the simpler one (using gdb), so, on newer\n* versions of Python it may not work unless the user has some code running\n* and threads are initialized.\n* I.e.:\n*\n* The user may have to add the code below in the start of its script for\n* a successful attach (if he doesn't already use threads).\n*\n* from threading import Thread\n* Thread(target=str).start()\n*\n* -- this is the workaround for the fact that we can't get the gil\n* if there aren't any threads (PyGILState_Ensure gives an error).\n* ***************************************************************************/\n\n\n// Access to std::cout and std::endl\n#include <iostream>\n// DECLDIR will perform an export for us\n#define DLL_EXPORT\n\n#include "attach.h"\n#include "stdafx.h"\n\n#include "../common/python.h"\n#include "../common/ref_utils.hpp"\n#include "../common/py_utils.hpp"\n#include "../common/py_settrace.hpp"\n\n\n#pragma comment(lib, "kernel32.lib")\n#pragma comment(lib, "user32.lib")\n#pragma comment(lib, "advapi32.lib")\n#pragma comment(lib, "psapi.lib")\n\n#include "py_win_helpers.hpp"\n#include "run_code_in_memory.hpp"\n\n// _Always_ is not defined for all versions, so make it a no-op if missing.\n#ifndef _Always_\n#define _Always_(x) x\n#endif\n\n\ntypedef void (PyEval_Lock)(); // Acquire/Release lock\ntypedef void (PyThreadState_API)(PyThreadState *); // Acquire/Release lock\ntypedef PyObject* (Py_CompileString)(const char *str, const char *filename, int start);\ntypedef PyObject* (PyEval_EvalCode)(PyObject *co, PyObject *globals, PyObject *locals);\ntypedef PyObject* (PyDict_GetItemString)(PyObject *p, const char *key);\ntypedef PyObject* (PyEval_GetBuiltins)();\ntypedef int (PyDict_SetItemString)(PyObject *dp, const char *key, PyObject *item);\ntypedef int (PyEval_ThreadsInitialized)();\ntypedef int (Py_AddPendingCall)(int (*func)(void *), void*);\ntypedef PyObject* (PyString_FromString)(const char* s);\ntypedef void PyEval_SetTrace(Py_tracefunc func, PyObject *obj);\ntypedef PyObject* (PyErr_Print)();\ntypedef PyObject* (PyObject_SetAttrString)(PyObject *o, const char *attr_name, PyObject* value);\ntypedef PyObject* (PyBool_FromLong)(long v);\ntypedef unsigned long (_PyEval_GetSwitchInterval)(void);\ntypedef void (_PyEval_SetSwitchInterval)(unsigned long microseconds);\ntypedef PyGILState_STATE PyGILState_EnsureFunc(void);\ntypedef void PyGILState_ReleaseFunc(PyGILState_STATE);\ntypedef PyThreadState *PyThreadState_NewFunc(PyInterpreterState *interp);\n\ntypedef PyObject *PyList_New(Py_ssize_t len);\ntypedef int PyList_Append(PyObject *list, PyObject *item);\n\n\n\nstd::wstring GetCurrentModuleFilename() {\n HMODULE hModule = nullptr;\n if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)GetCurrentModuleFilename, &hModule) != 0) {\n wchar_t filename[MAX_PATH];\n GetModuleFileName(hModule, filename, MAX_PATH);\n return filename;\n }\n return std::wstring();\n}\n\n\nstruct InitializeThreadingInfo {\n PyImport_ImportModule* pyImportMod;\n PyEval_Lock* initThreads;\n\n CRITICAL_SECTION cs;\n HANDLE initedEvent; // Note: only access with mutex locked (and check if not already nullptr).\n bool completed; // Note: only access with mutex locked\n};\n\n\nint AttachCallback(void *voidInitializeThreadingInfo) {\n // initialize us for threading, this will acquire the GIL if not already created, and is a nop if the GIL is created.\n // This leaves us in the proper state when we return back to the runtime whether the GIL was created or not before\n // we were called.\n InitializeThreadingInfo* initializeThreadingInfo = reinterpret_cast<InitializeThreadingInfo*>(voidInitializeThreadingInfo);\n initializeThreadingInfo->initThreads(); // Note: calling multiple times is ok.\n initializeThreadingInfo->pyImportMod("threading");\n\n EnterCriticalSection(&initializeThreadingInfo->cs);\n initializeThreadingInfo->completed = true;\n if(initializeThreadingInfo->initedEvent != nullptr) {\n SetEvent(initializeThreadingInfo->initedEvent);\n }\n LeaveCriticalSection(&initializeThreadingInfo->cs);\n return 0;\n}\n\n\n// create a custom heap for our unordered map. This is necessary because if we suspend a thread while in a heap function\n// then we could deadlock here. We need to be VERY careful about what we do while the threads are suspended.\nstatic HANDLE g_heap = 0;\n\ntemplate<typename T>\nclass PrivateHeapAllocator {\npublic:\n typedef size_t size_type;\n typedef ptrdiff_t difference_type;\n typedef T* pointer;\n typedef const T* const_pointer;\n typedef T& reference;\n typedef const T& const_reference;\n typedef T value_type;\n\n template<class U>\n struct rebind {\n typedef PrivateHeapAllocator<U> other;\n };\n\n explicit PrivateHeapAllocator() {}\n\n PrivateHeapAllocator(PrivateHeapAllocator const&) {}\n\n ~PrivateHeapAllocator() {}\n\n template<typename U>\n PrivateHeapAllocator(PrivateHeapAllocator<U> const&) {}\n\n pointer allocate(size_type size, std::allocator<void>::const_pointer hint = 0) {\n UNREFERENCED_PARAMETER(hint);\n\n if (g_heap == nullptr) {\n g_heap = HeapCreate(0, 0, 0);\n }\n auto mem = HeapAlloc(g_heap, 0, size * sizeof(T));\n return static_cast<pointer>(mem);\n }\n\n void deallocate(pointer p, size_type n) {\n UNREFERENCED_PARAMETER(n);\n\n HeapFree(g_heap, 0, p);\n }\n\n size_type max_size() const {\n return (std::numeric_limits<size_type>::max)() / sizeof(T);\n }\n\n void construct(pointer p, const T& t) {\n new(p) T(t);\n }\n\n void destroy(pointer p) {\n p->~T();\n }\n};\n\ntypedef std::unordered_map<DWORD, HANDLE, std::hash<DWORD>, std::equal_to<DWORD>, PrivateHeapAllocator<std::pair<DWORD, HANDLE>>> ThreadMap;\n\nvoid ResumeThreads(ThreadMap &suspendedThreads) {\n for (auto start = suspendedThreads.begin(); start != suspendedThreads.end(); start++) {\n ResumeThread((*start).second);\n CloseHandle((*start).second);\n }\n suspendedThreads.clear();\n}\n\n// Suspends all threads ensuring that they are not currently in a call to Py_AddPendingCall.\nvoid SuspendThreads(ThreadMap &suspendedThreads, Py_AddPendingCall* addPendingCall, PyEval_ThreadsInitialized* threadsInited) {\n DWORD curThreadId = GetCurrentThreadId();\n DWORD curProcess = GetCurrentProcessId();\n // suspend all the threads in the process so we can do things safely...\n bool suspended;\n\n do {\n suspended = false;\n HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);\n if (h != INVALID_HANDLE_VALUE) {\n\n THREADENTRY32 te;\n te.dwSize = sizeof(te);\n if (Thread32First(h, &te)) {\n do {\n if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID) && te.th32OwnerProcessID == curProcess) {\n\n\n if (te.th32ThreadID != curThreadId && suspendedThreads.find(te.th32ThreadID) == suspendedThreads.end()) {\n auto hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n if (hThread != nullptr) {\n SuspendThread(hThread);\n\n bool addingPendingCall = false;\n\n CONTEXT context;\n memset(&context, 0x00, sizeof(CONTEXT));\n context.ContextFlags = CONTEXT_ALL;\n GetThreadContext(hThread, &context);\n\n#if defined(_X86_)\n if (context.Eip >= *(reinterpret_cast<DWORD*>(addPendingCall)) && context.Eip <= (*(reinterpret_cast<DWORD*>(addPendingCall))) + 0x100) {\n addingPendingCall = true;\n }\n#elif defined(_AMD64_)\n if (context.Rip >= *(reinterpret_cast<DWORD64*>(addPendingCall)) && context.Rip <= *(reinterpret_cast<DWORD64*>(addPendingCall) + 0x100)) {\n addingPendingCall = true;\n }\n#endif\n\n if (addingPendingCall) {\n // we appear to be adding a pending call via this thread - wait for this to finish so we can add our own pending call...\n ResumeThread(hThread);\n SwitchToThread(); // yield to the resumed thread if it's on our CPU...\n CloseHandle(hThread);\n } else {\n suspendedThreads[te.th32ThreadID] = hThread;\n }\n suspended = true;\n }\n }\n }\n\n te.dwSize = sizeof(te);\n } while (Thread32Next(h, &te) && !threadsInited());\n }\n CloseHandle(h);\n }\n } while (suspended && !threadsInited());\n}\n\n\n\nextern "C"\n{\n\n /**\n * The returned value signals the error that happened!\n *\n * Return codes:\n * 0 = all OK.\n * 1 = Py_IsInitialized not found\n * 2 = Py_IsInitialized returned false\n * 3 = Missing Python API\n * 4 = Interpreter not initialized\n * 5 = Python version unknown\n * 6 = Connect timeout\n **/\n int DoAttach(HMODULE module, bool isDebug, const char *command, bool showDebugInfo )\n {\n auto isInit = reinterpret_cast<Py_IsInitialized*>(GetProcAddress(module, "Py_IsInitialized"));\n\n if (isInit == nullptr) {\n std::cerr << "Py_IsInitialized not found. " << std::endl << std::flush;\n return 1;\n }\n if (!isInit()) {\n std::cerr << "Py_IsInitialized returned false. " << std::endl << std::flush;\n return 2;\n }\n\n auto version = GetPythonVersion(module);\n\n // found initialized Python runtime, gather and check the APIs we need for a successful attach...\n DEFINE_PROC(addPendingCall, Py_AddPendingCall*, "Py_AddPendingCall", -100);\n DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", -110);\n DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", -120);\n DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", -130);\n DEFINE_PROC(threadHead, PyInterpreterState_ThreadHead*, "PyInterpreterState_ThreadHead", -140);\n DEFINE_PROC(initThreads, PyEval_Lock*, "PyEval_InitThreads", -150);\n DEFINE_PROC(releaseLock, PyEval_Lock*, "PyEval_ReleaseLock", -160);\n DEFINE_PROC(threadsInited, PyEval_ThreadsInitialized*, "PyEval_ThreadsInitialized", -170);\n DEFINE_PROC(threadNext, PyThreadState_Next*, "PyThreadState_Next", -180);\n DEFINE_PROC(pyImportMod, PyImport_ImportModule*, "PyImport_ImportModule", -190);\n DEFINE_PROC(pyNone, PyObject*, "_Py_NoneStruct", -2000);\n DEFINE_PROC(pyRun_SimpleString, PyRun_SimpleString*, "PyRun_SimpleString", -210);\n\n // Either _PyThreadState_Current or _PyThreadState_UncheckedGet are required\n DEFINE_PROC_NO_CHECK(curPythonThread, PyThreadState**, "_PyThreadState_Current", -220); // optional\n DEFINE_PROC_NO_CHECK(getPythonThread, _PyThreadState_UncheckedGet*, "_PyThreadState_UncheckedGet", -230); // optional\n DEFINE_PROC_NO_CHECK(getPythonThread13, _PyThreadState_GetCurrent*, "_PyThreadState_GetCurrent", -231); // optional\n if (getPythonThread == nullptr && getPythonThread13 != nullptr) {\n std::cout << "Using Python 3.13 or later, using _PyThreadState_GetCurrent" << std::endl << std::flush;\n getPythonThread = getPythonThread13;\n }\n\n if (curPythonThread == nullptr && getPythonThread == nullptr) {\n // we're missing some APIs, we cannot attach.\n std::cerr << "Error, missing Python threading API!!" << std::endl << std::flush;\n return -240;\n }\n\n // Either _Py_CheckInterval or _PyEval_[GS]etSwitchInterval are useful, but not required\n DEFINE_PROC_NO_CHECK(intervalCheck, int*, "_Py_CheckInterval", -250); // optional\n DEFINE_PROC_NO_CHECK(getSwitchInterval, _PyEval_GetSwitchInterval*, "_PyEval_GetSwitchInterval", -260); // optional\n DEFINE_PROC_NO_CHECK(setSwitchInterval, _PyEval_SetSwitchInterval*, "_PyEval_SetSwitchInterval", -270); // optional\n\n auto head = interpHead();\n if (head == nullptr) {\n // this interpreter is loaded but not initialized.\n std::cerr << "Interpreter not initialized! " << std::endl << std::flush;\n return 4;\n }\n\n // check that we're a supported version\n if (version == PythonVersion_Unknown) {\n std::cerr << "Python version unknown! " << std::endl << std::flush;\n return 5;\n } else if (version == PythonVersion_25 || version == PythonVersion_26 ||\n version == PythonVersion_30 || version == PythonVersion_31 || version == PythonVersion_32) {\n std::cerr << "Python version unsupported! " << std::endl << std::flush;\n return 5;\n }\n\n\n // We always try to initialize threading and import the threading module in the main thread in the code\n // below...\n //\n // We need to initialize multiple threading support but we need to do so safely, so we call\n // Py_AddPendingCall and have our callback then initialize multi threading. This is completely safe on 2.7\n // and up. Unfortunately that doesn't work if we're not actively running code on the main thread (blocked on a lock\n // or reading input).\n //\n // Another option is to make sure no code is running - if there is no active thread then we can safely call\n // PyEval_InitThreads and we're in business. But to know this is safe we need to first suspend all the other\n // threads in the process and then inspect if any code is running (note that this is still not ideal because\n // this thread will be the thread head for Python, but still better than not attach at all).\n //\n // Finally if code is running after we've suspended the threads then we can go ahead and do Py_AddPendingCall\n // on down-level interpreters as long as we're sure no one else is making a call to Py_AddPendingCall at the same\n // time.\n //\n // Therefore our strategy becomes: Make the Py_AddPendingCall on interpreters and wait for it. If it doesn't\n // call after a timeout, suspend all threads - if a threads is in Py_AddPendingCall resume and try again. Once we've got all of the threads\n // stopped and not in Py_AddPendingCall (which calls no functions its self, you can see this and it's size in the\n // debugger) then see if we have a current thread. If not go ahead and initialize multiple threading (it's now safe,\n // no Python code is running).\n\n InitializeThreadingInfo *initializeThreadingInfo = new InitializeThreadingInfo();\n initializeThreadingInfo->pyImportMod = pyImportMod;\n initializeThreadingInfo->initThreads = initThreads;\n initializeThreadingInfo->initedEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);\n InitializeCriticalSection(&initializeThreadingInfo->cs);\n\n // Add the call to initialize threading.\n addPendingCall(&AttachCallback, initializeThreadingInfo);\n\n ::WaitForSingleObject(initializeThreadingInfo->initedEvent, 5000);\n\n // Whether this completed or not, release the event handle as we won't use it anymore.\n EnterCriticalSection(&initializeThreadingInfo->cs);\n CloseHandle(initializeThreadingInfo->initedEvent);\n bool completed = initializeThreadingInfo->completed;\n initializeThreadingInfo->initedEvent = nullptr;\n LeaveCriticalSection(&initializeThreadingInfo->cs);\n\n if(completed) {\n // Note that this structure will leak if addPendingCall did not complete in the timeout\n // (we can't release now because it's possible that it'll still be called).\n DeleteCriticalSection(&initializeThreadingInfo->cs);\n delete initializeThreadingInfo;\n if (showDebugInfo) {\n std::cout << "addPendingCall to initialize threads/import threading completed. " << std::endl << std::flush;\n }\n } else {\n if (showDebugInfo) {\n std::cout << "addPendingCall to initialize threads/import threading did NOT complete. " << std::endl << std::flush;\n }\n }\n\n if (threadsInited()) {\n // Note that since Python 3.7, threads are *always* initialized!\n if (showDebugInfo) {\n std::cout << "Threads initialized! " << std::endl << std::flush;\n }\n\n } else {\n int saveIntervalCheck;\n unsigned long saveLongIntervalCheck;\n if (intervalCheck != nullptr) {\n // not available on 3.2\n saveIntervalCheck = *intervalCheck;\n *intervalCheck = -1; // lower the interval check so pending calls are processed faster\n saveLongIntervalCheck = 0; // prevent compiler warning\n } else if (getSwitchInterval != nullptr && setSwitchInterval != nullptr) {\n saveLongIntervalCheck = getSwitchInterval();\n setSwitchInterval(0);\n saveIntervalCheck = 0; // prevent compiler warning\n }\n else {\n saveIntervalCheck = 0; // prevent compiler warning\n saveLongIntervalCheck = 0; // prevent compiler warning\n }\n\n // If threads weren't initialized in our pending call, instead of giving a timeout, try\n // to initialize it in this thread.\n for(int attempts = 0; !threadsInited() && attempts < 20; attempts++) {\n if(attempts > 0){\n // If we haven't been able to do it in the first time, wait a bit before retrying.\n Sleep(10);\n }\n\n ThreadMap suspendedThreads;\n if (showDebugInfo) {\n std::cout << "SuspendThreads(suspendedThreads, addPendingCall, threadsInited);" << std::endl << std::flush;\n }\n SuspendThreads(suspendedThreads, addPendingCall, threadsInited);\n\n if(!threadsInited()){ // Check again with threads suspended.\n if (showDebugInfo) {\n std::cout << "ENTERED if (!threadsInited()) {" << std::endl << std::flush;\n }\n auto curPyThread = getPythonThread ? getPythonThread() : *curPythonThread;\n\n if (curPyThread == nullptr) {\n if (showDebugInfo) {\n std::cout << "ENTERED if (curPyThread == nullptr) {" << std::endl << std::flush;\n }\n // no threads are currently running, it is safe to initialize multi threading.\n PyGILState_STATE gilState;\n if (version >= PythonVersion_34) {\n // in 3.4 due to http://bugs.python.org/issue20891,\n // we need to create our thread state manually\n // before we can call PyGILState_Ensure() before we\n // can call PyEval_InitThreads().\n\n // Don't require this function unless we need it.\n auto threadNew = (PyThreadState_NewFunc*)GetProcAddress(module, "PyThreadState_New");\n if (threadNew != nullptr) {\n threadNew(head);\n }\n }\n\n if (version >= PythonVersion_32) {\n // in 3.2 due to the new GIL and later we can't call Py_InitThreads\n // without a thread being initialized.\n // So we use PyGilState_Ensure here to first\n // initialize the current thread, and then we use\n // Py_InitThreads to bring up multi-threading.\n // Some context here: http://bugs.python.org/issue11329\n // http://pytools.codeplex.com/workitem/834\n gilState = gilEnsure();\n }\n else {\n gilState = PyGILState_LOCKED; // prevent compiler warning\n }\n\n if (showDebugInfo) {\n std::cout << "Called initThreads()" << std::endl << std::flush;\n }\n // Initialize threads in our secondary thread (this is NOT ideal because\n // this thread will be the thread head), but is still better than not being\n // able to attach if the main thread is not actually running any code.\n initThreads();\n\n if (version >= PythonVersion_32) {\n // we will release the GIL here\n gilRelease(gilState);\n } else {\n releaseLock();\n }\n }\n }\n ResumeThreads(suspendedThreads);\n }\n\n\n if (intervalCheck != nullptr) {\n *intervalCheck = saveIntervalCheck;\n } else if (setSwitchInterval != nullptr) {\n setSwitchInterval(saveLongIntervalCheck);\n }\n\n }\n\n if (g_heap != nullptr) {\n HeapDestroy(g_heap);\n g_heap = nullptr;\n }\n\n if (!threadsInited()) {\n std::cerr << "Unable to initialize threads in the given timeout! " << std::endl << std::flush;\n return 8;\n }\n\n GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done...\n\n pyRun_SimpleString(command);\n return 0;\n\n }\n\n\n\n\n // ======================================== Code related to setting tracing to existing threads.\n\n\n /**\n * This function is meant to be called to execute some arbitrary python code to be\n * run. It'll initialize threads as needed and then run the code with pyRun_SimpleString.\n *\n * @param command: the python code to be run\n * @param attachInfo: pointer to an int specifying whether we should show debug info (1) or not (0).\n **/\n DECLDIR int AttachAndRunPythonCode(const char *command, int *attachInfo )\n {\n\n int SHOW_DEBUG_INFO = 1;\n\n bool showDebugInfo = (*attachInfo & SHOW_DEBUG_INFO) != 0;\n\n if (showDebugInfo) {\n std::cout << "AttachAndRunPythonCode started (showing debug info). " << std::endl << std::flush;\n }\n\n ModuleInfo moduleInfo = GetPythonModule();\n if (moduleInfo.errorGettingModule != 0) {\n return moduleInfo.errorGettingModule;\n }\n HMODULE module = moduleInfo.module;\n int attached = DoAttach(module, moduleInfo.isDebug, command, showDebugInfo);\n\n if (attached != 0) {\n std::cerr << "Error when injecting code in target process. Error code (on windows): " << attached << std::endl << std::flush;\n }\n return attached;\n }\n\n\n DECLDIR int PrintDebugInfo() {\n PRINT("Getting debug info...");\n ModuleInfo moduleInfo = GetPythonModule();\n if (moduleInfo.errorGettingModule != 0) {\n PRINT("Error getting python module");\n return 0;\n }\n HMODULE module = moduleInfo.module;\n\n DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", 0);\n DEFINE_PROC(threadHead, PyInterpreterState_ThreadHead*, "PyInterpreterState_ThreadHead", 0);\n DEFINE_PROC(threadNext, PyThreadState_Next*, "PyThreadState_Next", 160);\n DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 0);\n DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", 0);\n\n auto head = interpHead();\n if (head == nullptr) {\n // this interpreter is loaded but not initialized.\n PRINT("Interpreter not initialized!");\n return 0;\n }\n\n auto version = GetPythonVersion(module);\n printf("Python version: %d\n", version);\n\n GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done...\n auto curThread = threadHead(head);\n if (curThread == nullptr) {\n PRINT("Thread head is NULL.")\n return 0;\n }\n\n for (auto curThread = threadHead(head); curThread != nullptr; curThread = threadNext(curThread)) {\n printf("Found thread id: %d\n", GetPythonThreadId(version, curThread));\n }\n\n PRINT("Finished getting debug info.")\n return 0;\n }\n\n\n /**\n * This function may be called to set a tracing function to existing python threads.\n **/\n DECLDIR int AttachDebuggerTracing(bool showDebugInfo, void* pSetTraceFunc, void* pTraceFunc, unsigned int threadId, void* pPyNone)\n {\n ModuleInfo moduleInfo = GetPythonModule();\n if (moduleInfo.errorGettingModule != 0) {\n return moduleInfo.errorGettingModule;\n }\n HMODULE module = moduleInfo.module;\n if (showDebugInfo) {\n std::cout << "Setting sys trace for existing threads." << std::endl << std::flush;\n }\n int attached = 0;\n PyObjectHolder traceFunc(moduleInfo.isDebug, reinterpret_cast<PyObject*>(pTraceFunc), true);\n PyObjectHolder setTraceFunc(moduleInfo.isDebug, reinterpret_cast<PyObject*>(pSetTraceFunc), true);\n PyObjectHolder pyNone(moduleInfo.isDebug, reinterpret_cast<PyObject*>(pPyNone), true);\n\n int temp = InternalSetSysTraceFunc(module, moduleInfo.isDebug, showDebugInfo, &traceFunc, &setTraceFunc, threadId, &pyNone);\n if (temp == 0) {\n // we've successfully attached the debugger\n return 0;\n } else {\n if (temp > attached) {\n //I.e.: the higher the value the more significant it is.\n attached = temp;\n }\n }\n\n if (showDebugInfo) {\n std::cout << "Setting sys trace for existing threads failed with code: " << attached << "." << std::endl << std::flush;\n }\n return attached;\n }\n\n}\n\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\attach.cpp
|
attach.cpp
|
C++
| 28,624 | 0.95 | 0.15625 | 0.286252 |
vue-tools
| 925 |
2024-05-17T19:29:19.994460
|
GPL-3.0
| false |
4857a11d438b00c91da9efdec93d1185
|
/* ****************************************************************************\n *\n * Copyright (c) Brainwy software Ltda.\n *\n * This source code is subject to terms and conditions of the Apache License, Version 2.0. A\n * copy of the license can be found in the License.html file at the root of this distribution. If\n * you cannot locate the Apache License, Version 2.0, please send an email to\n * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound\n * by the terms of the Apache License, Version 2.0.\n *\n * You must not remove this notice, or any other, from this software.\n *\n * ***************************************************************************/\n\n#ifndef _ATTACH_DLL_H_\n#define _ATTACH_DLL_H_\n\n#if defined DLL_EXPORT\n#define DECLDIR __declspec(dllexport)\n#else\n#define DECLDIR __declspec(dllimport)\n#endif\n\n\nextern "C"\n{\n DECLDIR int AttachAndRunPythonCode(const char *command, int *result );\n \n /*\n * Helper to print debug information from the current process\n */\n DECLDIR int PrintDebugInfo();\n \n /*\n Could be used with ctypes (note that the threading should be initialized, so, \n doing it in a thread as below is recommended):\n \n def check():\n \n import ctypes\n lib = ctypes.cdll.LoadLibrary(r'C:\...\attach_x86.dll')\n print 'result', lib.AttachDebuggerTracing(0)\n \n t = threading.Thread(target=check)\n t.start()\n t.join()\n */\n DECLDIR int AttachDebuggerTracing(\n bool showDebugInfo, \n void* pSetTraceFunc, // Actually PyObject*, but we don't want to include it here.\n void* pTraceFunc, // Actually PyObject*, but we don't want to include it here.\n unsigned int threadId,\n void* pPyNone // Actually PyObject*, but we don't want to include it here.\n );\n}\n\n#endif
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\attach.h
|
attach.h
|
C
| 1,902 | 0.95 | 0.035714 | 0.553191 |
vue-tools
| 426 |
2024-01-17T23:26:02.029830
|
BSD-3-Clause
| false |
292bb980a09474013c1a5108647cbd3d
|
:: This script compiles the attach and inject DLLs for x86 and x64 architectures.\n\nsetlocal\n@cd /d %~dp0\n\n@set VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe\n@echo Using vswhere at %VSWHERE%\n@for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -prerelease -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set VSDIR=%%i\n@echo Using Visual C++ at %VSDIR%\n \ncall "%VSDIR%\VC\Auxiliary\Build\vcvarsall.bat" x86 -vcvars_spectre_libs=spectre\n\ncl -DUNICODE -D_UNICODE /EHsc /Zi /O1 /W3 /LD /MD /Qspectre attach.cpp /link /PROFILE /GUARD:CF /CETCOMPAT /out:attach_x86.dll\ncopy attach_x86.dll ..\attach_x86.dll /Y\ncopy attach_x86.pdb ..\attach_x86.pdb /Y\n\ncl -DUNICODE -D_UNICODE /EHsc /Zi /O1 /W3 /LD /MD /D BITS_32 /Qspectre run_code_on_dllmain.cpp /link /PROFILE /GUARD:CF /CETCOMPAT /out:run_code_on_dllmain_x86.dll\ncopy run_code_on_dllmain_x86.dll ..\run_code_on_dllmain_x86.dll /Y\ncopy run_code_on_dllmain_x86.pdb ..\run_code_on_dllmain_x86.pdb /Y\n\ncl /EHsc /Zi /O1 /W3 /Qspectre inject_dll.cpp /link /PROFILE /GUARD:CF /CETCOMPAT /out:inject_dll_x86.exe\ncopy inject_dll_x86.exe ..\inject_dll_x86.exe /Y\ncopy inject_dll_x86.pdb ..\inject_dll_x86.pdb /Y\n\ncall "%VSDIR%\VC\Auxiliary\Build\vcvarsall.bat" x86_amd64 -vcvars_spectre_libs=spectre\n\ncl -DUNICODE -D_UNICODE /EHsc /Zi /O1 /W3 /LD /MD /Qspectre attach.cpp /link /PROFILE /GUARD:CF /CETCOMPAT /out:attach_amd64.dll\ncopy attach_amd64.dll ..\attach_amd64.dll /Y\ncopy attach_amd64.pdb ..\attach_amd64.pdb /Y\n\ncl -DUNICODE -D_UNICODE /EHsc /Zi /O1 /W3 /LD /MD /D BITS_64 /Qspectre run_code_on_dllmain.cpp /link /PROFILE /GUARD:CF /CETCOMPAT /out:run_code_on_dllmain_amd64.dll\ncopy run_code_on_dllmain_amd64.dll ..\run_code_on_dllmain_amd64.dll /Y\ncopy run_code_on_dllmain_amd64.pdb ..\run_code_on_dllmain_amd64.pdb /Y\n\ncl /EHsc /Zi /O1 /W3 /Qspectre inject_dll.cpp /link /PROFILE /GUARD:CF /CETCOMPAT /out:inject_dll_amd64.exe\ncopy inject_dll_amd64.exe ..\inject_dll_amd64.exe /Y\ncopy inject_dll_amd64.pdb ..\inject_dll_amd64.pdb /Y\n\ndel *.exe\ndel *.lib\ndel *.obj\ndel *.pdb\ndel *.dll\ndel *.exp
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\compile_windows.bat
|
compile_windows.bat
|
Other
| 2,203 | 0.85 | 0.046512 | 0 |
awesome-app
| 720 |
2024-10-20T20:10:29.489834
|
GPL-3.0
| false |
ffa44d983ae77a86fde82ae9ffc39bb2
|
#include <iostream>\n#include <windows.h>\n#include <stdio.h>\n#include <conio.h>\n#include <tchar.h>\n#include <tlhelp32.h>\n\n#pragma comment(lib, "kernel32.lib")\n#pragma comment(lib, "user32.lib")\n\n// Helper to free data when we leave the scope.\nclass DataToFree {\npublic:\n HANDLE hProcess;\n HANDLE snapshotHandle;\n \n LPVOID remoteMemoryAddr;\n int remoteMemorySize;\n \n DataToFree(){\n this->hProcess = nullptr;\n this->snapshotHandle = nullptr;\n \n this->remoteMemoryAddr = nullptr;\n this->remoteMemorySize = 0;\n }\n \n ~DataToFree() {\n if(this->hProcess != nullptr){\n \n if(this->remoteMemoryAddr != nullptr && this->remoteMemorySize != 0){\n VirtualFreeEx(this->hProcess, this->remoteMemoryAddr, this->remoteMemorySize, MEM_RELEASE);\n this->remoteMemoryAddr = nullptr;\n this->remoteMemorySize = 0;\n }\n \n CloseHandle(this->hProcess);\n this->hProcess = nullptr;\n }\n\n if(this->snapshotHandle != nullptr){\n CloseHandle(this->snapshotHandle);\n this->snapshotHandle = nullptr;\n }\n }\n};\n\n\n/**\n * All we do here is load a dll in a remote program (in a remote thread).\n *\n * Arguments must be the pid and the dll name to run.\n *\n * i.e.: inject_dll.exe <pid> <dll path>\n */\nint wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] )\n{\n std::cout << "Running executable to inject dll." << std::endl;\n \n // Helper to clear resources.\n DataToFree dataToFree;\n \n if(argc != 3){\n std::cout << "Expected 2 arguments (pid, dll name)." << std::endl;\n return 1;\n }\n \n const int pid = _wtoi(argv[1]);\n if(pid == 0){\n std::cout << "Invalid pid." << std::endl;\n return 2;\n }\n \n const int MAX_PATH_SIZE_PADDED = MAX_PATH + 1;\n char dllPath[MAX_PATH_SIZE_PADDED];\n memset(&dllPath[0], '\0', MAX_PATH_SIZE_PADDED);\n size_t pathLen = 0;\n wcstombs_s(&pathLen, dllPath, argv[2], MAX_PATH);\n \n const bool inheritable = false;\n const HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, inheritable, pid);\n if(hProcess == nullptr || hProcess == INVALID_HANDLE_VALUE){\n std::cout << "Unable to open process with pid: " << pid << ". Error code: " << GetLastError() << "." << std::endl;\n return 3;\n }\n dataToFree.hProcess = hProcess;\n std::cout << "OpenProcess with pid: " << pid << std::endl;\n \n const LPVOID remoteMemoryAddr = VirtualAllocEx(hProcess, nullptr, MAX_PATH_SIZE_PADDED, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n if(remoteMemoryAddr == nullptr){\n std::cout << "Error. Unable to allocate memory in pid: " << pid << ". Error code: " << GetLastError() << "." << std::endl;\n return 4;\n }\n dataToFree.remoteMemorySize = MAX_PATH_SIZE_PADDED;\n dataToFree.remoteMemoryAddr = remoteMemoryAddr;\n \n std::cout << "VirtualAllocEx in pid: " << pid << std::endl;\n \n const bool written = WriteProcessMemory(hProcess, remoteMemoryAddr, dllPath, pathLen, nullptr);\n if(!written){\n std::cout << "Error. Unable to write to memory in pid: " << pid << ". Error code: " << GetLastError() << "." << std::endl;\n return 5;\n }\n std::cout << "WriteProcessMemory in pid: " << pid << std::endl;\n \n const LPVOID loadLibraryAddress = (LPVOID) GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");\n if(loadLibraryAddress == nullptr){\n std::cout << "Error. Unable to get LoadLibraryA address. Error code: " << GetLastError() << "." << std::endl;\n return 6;\n }\n std::cout << "loadLibraryAddress: " << pid << std::endl;\n \n const HANDLE remoteThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE) loadLibraryAddress, remoteMemoryAddr, 0, nullptr);\n if (remoteThread == nullptr) {\n std::cout << "Error. Unable to CreateRemoteThread. Error code: " << GetLastError() << "." << std::endl;\n return 7;\n }\n \n // We wait for the load to finish before proceeding to get the function to actually do the attach.\n std::cout << "Waiting for LoadLibraryA to complete." << std::endl;\n DWORD result = WaitForSingleObject(remoteThread, 5 * 1000);\n \n if(result == WAIT_TIMEOUT) {\n std::cout << "WaitForSingleObject(LoadLibraryA thread) timed out." << std::endl;\n return 8;\n \n } else if(result == WAIT_FAILED) {\n std::cout << "WaitForSingleObject(LoadLibraryA thread) failed. Error code: " << GetLastError() << "." << std::endl;\n return 9;\n }\n \n std::cout << "Ok, finished dll injection." << std::endl;\n return 0;\n}
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\inject_dll.cpp
|
inject_dll.cpp
|
C++
| 4,925 | 0.95 | 0.120301 | 0.165138 |
vue-tools
| 702 |
2024-11-27T06:50:26.040747
|
BSD-3-Clause
| false |
888a9b234eab47b3398f61b4db517adc
|
#ifndef _PY_WIN_HELPERS_HPP_\n#define _PY_WIN_HELPERS_HPP_\n\nbool IsPythonModule(HMODULE module, bool &isDebug) {\n wchar_t mod_name[MAX_PATH];\n isDebug = false;\n if (GetModuleBaseName(GetCurrentProcess(), module, mod_name, MAX_PATH)) {\n if (_wcsnicmp(mod_name, L"python", 6) == 0) {\n if (wcslen(mod_name) >= 10 && _wcsnicmp(mod_name + 8, L"_d", 2) == 0) {\n isDebug = true;\n }\n \n // Check if the module has Py_IsInitialized.\n DEFINE_PROC_NO_CHECK(isInit, Py_IsInitialized*, "Py_IsInitialized", 0);\n DEFINE_PROC_NO_CHECK(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 51);\n DEFINE_PROC_NO_CHECK(gilRelease, PyGILState_Release*, "PyGILState_Release", 51);\n if (isInit == nullptr || gilEnsure == nullptr || gilRelease == nullptr) {\n return false;\n }\n \n\n return true;\n }\n }\n return false;\n}\n\n\nstruct ModuleInfo {\n HMODULE module;\n bool isDebug;\n int errorGettingModule; // 0 means ok, negative values some error (should never be positive).\n};\n\n\nModuleInfo GetPythonModule() {\n HANDLE hProcess = GetCurrentProcess();\n ModuleInfo moduleInfo;\n moduleInfo.module = nullptr;\n moduleInfo.isDebug = false;\n moduleInfo.errorGettingModule = 0;\n \n DWORD modSize = sizeof(HMODULE) * 1024;\n HMODULE* hMods = (HMODULE*)_malloca(modSize);\n if (hMods == nullptr) {\n std::cout << "hmods not allocated! " << std::endl << std::flush;\n moduleInfo.errorGettingModule = -1;\n return moduleInfo;\n }\n\n DWORD modsNeeded;\n while (!EnumProcessModules(hProcess, hMods, modSize, &modsNeeded)) {\n // try again w/ more space...\n _freea(hMods);\n hMods = (HMODULE*)_malloca(modsNeeded);\n if (hMods == nullptr) {\n std::cout << "hmods not allocated (2)! " << std::endl << std::flush;\n moduleInfo.errorGettingModule = -2;\n return moduleInfo;\n }\n modSize = modsNeeded;\n }\n \n for (size_t i = 0; i < modsNeeded / sizeof(HMODULE); i++) {\n bool isDebug;\n if (IsPythonModule(hMods[i], isDebug)) {\n moduleInfo.isDebug = isDebug;\n moduleInfo.module = hMods[i]; \n return moduleInfo;\n }\n }\n std::cout << "Unable to find python module. " << std::endl << std::flush;\n moduleInfo.errorGettingModule = -3;\n return moduleInfo;\n}\n\n#endif
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\py_win_helpers.hpp
|
py_win_helpers.hpp
|
Other
| 2,555 | 0.95 | 0.144737 | 0.076923 |
python-kit
| 698 |
2024-06-20T08:47:26.249353
|
Apache-2.0
| false |
124ebdf8de0e15381240bf33dfd39ab0
|
#ifndef _PY_RUN_CODE_IN_MEMORY_HPP_\n#define _PY_RUN_CODE_IN_MEMORY_HPP_\n\n#include <iostream>\n#include "attach.h"\n#include "stdafx.h"\n\n#include <windows.h>\n#include <stdio.h>\n#include <conio.h>\n#include <tchar.h>\n\n#include "../common/python.h"\n#include "../common/ref_utils.hpp"\n#include "../common/py_utils.hpp"\n#include "../common/py_settrace.hpp"\n\n#include "py_win_helpers.hpp"\n\n#pragma comment(lib, "kernel32.lib")\n#pragma comment(lib, "user32.lib")\n#pragma comment(lib, "advapi32.lib")\n\nDECLDIR int AttachAndRunPythonCode(const char *command, int *attachInfo );\n\n// NOTE: BUFSIZE must be the same from add_code_to_python_process.py\n#define BUFSIZE 2048\n\n// Helper to free data when we leave the scope.\nclass DataToFree {\n\npublic:\n\n HANDLE hMapFile;\n void* mapViewOfFile;\n char* codeToRun;\n\n DataToFree() {\n this->hMapFile = nullptr;\n this->mapViewOfFile = nullptr;\n this->codeToRun = nullptr;\n }\n\n ~DataToFree() {\n if (this->hMapFile != nullptr) {\n CloseHandle(this->hMapFile);\n this->hMapFile = nullptr;\n }\n if (this->mapViewOfFile != nullptr) {\n UnmapViewOfFile(this->mapViewOfFile);\n this->mapViewOfFile = nullptr;\n }\n if (this->codeToRun != nullptr) {\n delete this->codeToRun;\n this->codeToRun = nullptr;\n }\n }\n};\n\n\n\nextern "C"\n{\n /**\n * This method will read the code to be executed from the named shared memory\n * and execute it.\n */\n DECLDIR int RunCodeInMemoryInAttachedDll() {\n // PRINT("Attempting to run Python code from named shared memory.")\n //get the code to be run (based on https://docs.microsoft.com/en-us/windows/win32/memory/creating-named-shared-memory).\n HANDLE hMapFile;\n char* mapViewOfFile;\n\n DataToFree dataToFree;\n\n std::string namedSharedMemoryName("__pydevd_pid_code_to_run__");\n namedSharedMemoryName += std::to_string(GetCurrentProcessId());\n\n hMapFile = OpenFileMappingA(\n FILE_MAP_ALL_ACCESS, // read/write access\n FALSE, // do not inherit the name\n namedSharedMemoryName.c_str()); // name of mapping object\n\n if (hMapFile == nullptr) {\n std::cout << "Error opening named shared memory (OpenFileMapping): " << GetLastError() + " name: " << namedSharedMemoryName << std::endl;\n return 1;\n } else {\n // PRINT("Opened named shared memory.")\n }\n\n dataToFree.hMapFile = hMapFile;\n\n mapViewOfFile = reinterpret_cast < char* > (MapViewOfFile(hMapFile, // handle to map object\n FILE_MAP_ALL_ACCESS, // read/write permission\n 0,\n 0,\n BUFSIZE));\n\n if (mapViewOfFile == nullptr) {\n std::cout << "Error mapping view of named shared memory (MapViewOfFile): " << GetLastError() << std::endl;\n return 1;\n } else {\n // PRINT("Mapped view of file.")\n }\n dataToFree.mapViewOfFile = mapViewOfFile;\n // std::cout << "Will run contents: " << mapViewOfFile << std::endl;\n\n dataToFree.codeToRun = new char[BUFSIZE];\n memmove(dataToFree.codeToRun, mapViewOfFile, BUFSIZE);\n\n int attachInfo = 0;\n return AttachAndRunPythonCode(dataToFree.codeToRun, &attachInfo);\n }\n}\n\n#endif
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\run_code_in_memory.hpp
|
run_code_in_memory.hpp
|
Other
| 3,470 | 0.95 | 0.052174 | 0.32967 |
awesome-app
| 582 |
2023-10-08T17:28:50.204628
|
Apache-2.0
| false |
830335fd76c7efd0baf7d30dc474b8b2
|
#include <iostream>\n#include <thread>\n#include "attach.h"\n#include "stdafx.h"\n\n#include <windows.h>\n#include <stdio.h>\n#include <conio.h>\n#include <tchar.h>\n\ntypedef int (_RunCodeInMemoryInAttachedDll)();\n\nHINSTANCE globalDllInstance = NULL;\n\nclass NotificationHelper {\npublic:\n#pragma warning( push )\n#pragma warning( disable : 4722 )\n// disable c4722 here: Destructor never returns warning. Compiler sees ExitThread and assumes that\n// there is a potential memory leak.\n ~NotificationHelper(){\n std::string eventName("_pydevd_pid_event_");\n eventName += std::to_string(GetCurrentProcessId());\n\n // When we finish we need to set the event that the caller is waiting for and\n // unload the dll (if we don't exit this dll we won't be able to reattach later on).\n auto event = CreateEventA(nullptr, false, false, eventName.c_str());\n if (event != nullptr) {\n SetEvent(event);\n CloseHandle(event);\n }\n FreeLibraryAndExitThread(globalDllInstance, 0);\n }\n#pragma warning( pop )\n};\n\nDWORD WINAPI RunCodeInThread(LPVOID lpParam){\n NotificationHelper notificationHelper; // When we exit the scope the destructor should take care of the cleanup.\n \n#ifdef BITS_32\n HMODULE attachModule = GetModuleHandleA("attach_x86.dll");\n#else\n HMODULE attachModule = GetModuleHandleA("attach_amd64.dll");\n#endif\n\n if (attachModule == nullptr) {\n std::cout << "Error: unable to get attach_x86.dll or attach_amd64.dll module handle." << std::endl;\n return 900;\n }\n\n _RunCodeInMemoryInAttachedDll* runCode = reinterpret_cast < _RunCodeInMemoryInAttachedDll* > (GetProcAddress(attachModule, "RunCodeInMemoryInAttachedDll"));\n if (runCode == nullptr) {\n std::cout << "Error: unable to GetProcAddress(attachModule, RunCodeInMemoryInAttachedDll) from attach_x86.dll or attach_amd64.dll." << std::endl;\n return 901;\n }\n\n runCode();\n return 0;\n}\n\n/**\n * When the dll is loaded we create a thread that will call 'RunCodeInMemoryInAttachedDll'\n * in the attach dll (when completed we unload this library for a reattach to work later on).\n */\nBOOL WINAPI DllMain(\n _In_ HINSTANCE hinstDLL,\n _In_ DWORD fdwReason,\n _In_ LPVOID lpvReserved\n){\n if(fdwReason == DLL_PROCESS_ATTACH){\n globalDllInstance = hinstDLL;\n DWORD threadId;\n CreateThread(nullptr, 0, &RunCodeInThread, nullptr, 0, &threadId);\n }\n else if(fdwReason == DLL_PROCESS_DETACH){\n }\n return true;\n}\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\run_code_on_dllmain.cpp
|
run_code_on_dllmain.cpp
|
C++
| 2,594 | 0.95 | 0.115385 | 0.328358 |
react-lib
| 346 |
2024-01-25T10:50:36.572550
|
GPL-3.0
| false |
79b4e95748900b8d2399935046bccfb9
|
/* ****************************************************************************\n *\n * Copyright (c) Microsoft Corporation. \n *\n * This source code is subject to terms and conditions of the Apache License, Version 2.0. A \n * copy of the license can be found in the License.html file at the root of this distribution. If \n * you cannot locate the Apache License, Version 2.0, please send an email to \n * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound \n * by the terms of the Apache License, Version 2.0.\n *\n * You must not remove this notice, or any other, from this software.\n *\n * ***************************************************************************/\n\n// stdafx.cpp : source file that includes just the standard includes\n// PyDebugAttach.pch will be the pre-compiled header\n// stdafx.obj will contain the pre-compiled type information\n\n#include "stdafx.h"\n\n// TODO: reference any additional headers you need in STDAFX.H\n// and not in this file\n
|
.venv\Lib\site-packages\debugpy\_vendored\pydevd\pydevd_attach_to_process\windows\stdafx.cpp
|
stdafx.cpp
|
C++
| 1,021 | 0.8 | 0 | 1 |
python-kit
| 695 |
2024-03-14T00:05:52.154094
|
GPL-3.0
| false |
e7e858582f121e1d33cadbf67d06f6e6
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.