From bb1acbe5692cf0d0a636cf892b99c8f65f83ad0a Mon Sep 17 00:00:00 2001 From: Teja P C <39472754+PCTEJA@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:23:02 +0000 Subject: [PATCH 1/4] Fix subprocess patching for scripts run through a python shebang patch_args returned the arguments unchanged when the executable was a script whose first line is a shebang pointing at a python interpreter, so such subprocesses were never attached to the debugger. When the executable name is not a known python name, parse the file's shebang (the direct form, the /usr/bin/env form and the env -S form) and rewrite the args to run the script through that interpreter before the existing patching runs. The process creation hooks also replace the executable with the interpreter in that case, since they launch the executable separately from the args (for fork_exec, the executable list passed to it is replaced instead). --- .../pydevd/_pydev_bundle/pydev_monkey.py | 406 +++++++++- .../pydevd/tests_python/test_pydev_monkey.py | 735 ++++++++++++++++++ 2 files changed, 1129 insertions(+), 12 deletions(-) diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py index 09fcadec3..758b3f506 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py @@ -4,6 +4,7 @@ from _thread import _local import os import re +import shutil import sys from typing import Generator from _pydev_bundle._pydev_saved_modules import threading @@ -19,6 +20,7 @@ IS_PY313_OR_GREATER, ) from _pydev_bundle import pydev_log +from collections.abc import Mapping from contextlib import contextmanager from _pydevd_bundle import pydevd_constants, pydevd_defaults from _pydevd_bundle.pydevd_defaults import PydevdCustomization @@ -303,6 +305,278 @@ def is_python(path) -> bool: return False +def _which(command, path=None, cwd=None): + """ + shutil.which variant where relative PATH entries are resolved + against cwd (the child process working directory) when it is given, + so the result does not depend on this process's working directory. + """ + if cwd is None: + return shutil.which(command, path=path) + + if path is None: + path = os.environ.get("PATH", os.defpath) + for entry in path.split(os.pathsep): + if not os.path.isabs(entry): + entry = os.path.join(os.fsdecode(cwd), entry) + candidate = os.path.join(entry, command) + if os.path.isfile(candidate) and os.access(candidate, os.X_OK): + return os.path.abspath(candidate) + return None + + +def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool] | None: + """ + :return: + A tuple (interpreter, interpreter_args, resolved_path, via_env) + if the file at path starts with a shebang pointing at a python + interpreter, None otherwise. resolved_path is the path actually + read (the script resolved through PATH when path is a bare + name). Relative paths are resolved against cwd when it is given + (the child process working directory for subprocess launches). + """ + target = path + if os.path.dirname(os.fsdecode(path)): + if cwd is not None and not os.path.isabs(os.fsdecode(path)): + # Make it absolute: a path relative to the child's working + # directory would be resolved again (wrongly) once the + # child has changed into that directory. + target = os.path.abspath(os.path.join(os.fsdecode(cwd), os.fsdecode(path))) + if not os.path.isfile(target): + return None + elif cwd is not None: + # Resolve the bare name through PATH as the child process + # would (see _which). + target = _which(os.fsdecode(path), path=_get_env_path(env), cwd=cwd) + if target is None: + return None + else: + target = _which(os.fsdecode(path), path=_get_env_path(env)) + if target is None: + return None + + if not os.access(target, os.X_OK): + return None + + try: + with open(target, "rb") as stream: + first_line = stream.readline(1024) + except Exception: + return None + + if b"\r" in first_line: + # A carriage return is part of the interpreter name the kernel + # passes on (i.e.: CRLF scripts fail to launch natively): do + # not normalize it away. + return None + + if not first_line.startswith(b"#!"): + return None + first_line = first_line.strip() + + line = first_line[2:].decode("utf-8", "ignore").strip() + if not line: + return None + + parts = line.split(None, 1) + interpreter = parts[0] + rest = parts[1] if len(parts) > 1 else "" + via_env = False + + program_path = interpreter + if cwd is not None and not os.path.isabs(program_path): + program_path = os.path.join(os.fsdecode(cwd), program_path) + if not (os.path.isfile(program_path) and os.access(program_path, os.X_OK)): + # The program named by the shebang cannot be launched at all + # (i.e.: #!/nonexistent/env python3): preserve the native + # launch failure instead of rewriting it into a working one. + return None + + if os.path.basename(interpreter) == "env": + via_env = True + # i.e.: #!/usr/bin/env python3 or #!/usr/bin/env -S python3 ... + # Other env options or assignments change the launch semantics, + # and env -S applies its own quoting and variable expansion + # rules, so only the plain forms without quotes or $ are + # handled. + if '"' in rest or "'" in rest or "\\" in rest or "$" in rest: + return None + args = rest.split() + split_args = False + if args and args[0] == "-S": + split_args = True + args = args[1:] + if not args or args[0].startswith("-") or "=" in args[0]: + return None + interpreter = args[0] + args = args[1:] + if args and not split_args: + return None + if any(arg.startswith("#") for arg in args): + # env -S treats # as a comment start: leave such launches + # unchanged instead of passing the comment on as arguments. + return None + elif rest: + if rest.startswith("#"): + return None + # The kernel passes everything after the interpreter as a single + # argument (i.e.: #!/usr/bin/python3 -O). + args = [rest] + else: + args = [] + + if not is_python(interpreter): + return None + + return interpreter, args, os.fsdecode(target), via_env + + +def _get_env_path(env): + """ + :return: + The PATH to use for lookups in the child process environment + (a dict for execve/spawnve/posix_spawn, a list of "name=value" + entries for fork_exec), or None when the child inherits this + process's environment. + """ + if env is None: + return None + if isinstance(env, Mapping): + for key in ("PATH", b"PATH"): + try: + if key in env: + return os.fsdecode(env[key]) + except TypeError: + # i.e.: probing os.environ with a bytes key (or + # os.environb with a str key) raises TypeError. + continue + return os.defpath + try: + for entry in env: + entry = os.fsdecode(entry) + if entry.startswith("PATH="): + return entry[len("PATH=") :] + except Exception: + return None + return os.defpath + + +_SAME_AS_ENV = object() + + +def _get_shebang_executable(executable, original_args, new_args, env=None, cwd=None, file_env=_SAME_AS_ENV): + """ + If patch_args rewrote the args because the executable is a script with + a python shebang, the process must be launched through the interpreter + from the shebang instead of the script itself: return that interpreter + (resolved through the child PATH when it is a bare name), otherwise + return None. + """ + if new_args == original_args: + return None + + if file_env is _SAME_AS_ENV: + file_env = env + + try: + shebang_info = _parse_shebang(executable, cwd=cwd, env=file_env) + except Exception: + return None + if shebang_info is None: + return None + + interpreter, _interpreter_args, _script, via_env = shebang_info + if not os.path.dirname(interpreter): + if via_env: + # env searches PATH for the interpreter. + resolved = _which(interpreter, path=_get_env_path(env), cwd=cwd) + if resolved is None: + if env is not None: + # The interpreter cannot be resolved in the child's + # environment: do not rewrite the launch. + return None + resolved = interpreter + interpreter = resolved + else: + # A direct shebang with a bare interpreter name is resolved + # by the kernel relative to the working directory, not + # through PATH. + candidate = interpreter + if cwd is not None: + candidate = os.path.join(os.fsdecode(cwd), interpreter) + if not (os.path.isfile(candidate) and os.access(candidate, os.X_OK)): + return None + interpreter = os.path.abspath(candidate) + + if isinstance(executable, (str, bytes)): + return _get_str_type_compatible(executable, interpreter) + return interpreter + + +def _uses_path_search(original_name) -> bool: + # The "p" variants (execvp, execlpe, spawnvp, posix_spawnp, ...) + # search PATH for a bare executable name; the others treat it as a + # path relative to the current directory. + name = original_name[len("original_") :] + if name.endswith("e"): + name = name[:-1] + return name.endswith("p") + + +def _patch_args_for_launch( + executable, args, is_exec=False, env=None, cwd=None, search_path=True, file_env=_SAME_AS_ENV +): + """ + Patch args for a launch whose executable is given separately from the + args (the exec/spawn/fork_exec hooks). + + :return: + A tuple (new_args, new_executable), where new_executable is the + interpreter to launch instead of executable, or None when the + executable must be kept as is. When the patch_args rewrite was + driven by the shebang of args[0] but the executable being launched + is a different program (an explicit override), the original args + are returned unchanged. + """ + if file_env is _SAME_AS_ENV: + file_env = env + + # When the child's working directory is known, the shebang is parsed + # against it from the start: the file the child will run may differ + # from the one visible from this process. + new_args = patch_args(args, is_exec=is_exec, cwd=cwd, env=file_env) + if new_args == args or not args: + return new_args, None + + try: + shebang_info = _parse_shebang(args[0], cwd=cwd, env=file_env) + except Exception: + shebang_info = None + if shebang_info is None: + # Patched because args[0] names a python executable: the + # executable needs no replacement. + return new_args, None + + if executable is None: + return args, None + + executable_path = os.fsdecode(executable) + if not os.path.dirname(executable_path) and search_path: + executable_path = ( + _which(executable_path, path=_get_env_path(file_env), cwd=cwd) or executable_path + ) + elif cwd is not None and not os.path.isabs(executable_path): + executable_path = os.path.join(os.fsdecode(cwd), executable_path) + if os.path.abspath(executable_path) != os.path.abspath(shebang_info[2]): + return args, None + + replacement = _get_shebang_executable(executable, args, new_args, env=env, cwd=cwd, file_env=file_env) + if replacement is None: + return args, None + + return new_args, replacement + + class InvalidTypeInArgsException(Exception): pass @@ -379,7 +653,7 @@ def quote_args(args): return args -def patch_args(args, is_exec=False): +def patch_args(args, is_exec=False, cwd=None, env=None): """ :param list args: Arguments to patch. @@ -387,6 +661,14 @@ def patch_args(args, is_exec=False): :param bool is_exec: If it's an exec, the current process will be replaced (this means we have to keep the same ppid). + + :param str cwd: + The working directory the child process will run in, when known + (used to resolve a script's shebang as the child would see it). + + :param env: + The environment the child process will run with, when known + (used to resolve a bare script name through the child's PATH). """ try: pydev_log.debug("Patching args: %s", args) @@ -407,8 +689,21 @@ def patch_args(args, is_exec=False): return original_args if not is_python(unquoted_args[0]): - pydev_log.debug("Process is not python, returning.") - return original_args + shebang_info = _parse_shebang(unquoted_args[0], cwd=cwd, env=env) + if shebang_info is None: + pydev_log.debug("Process is not python, returning.") + return original_args + + # The executable is a script with a python shebang: rewrite the + # args to run it through that interpreter so it can be patched. + interpreter, interpreter_args, script, _via_env = shebang_info + fix_type = lambda s: _get_str_type_compatible(unquoted_args[0], s) + unquoted_args = ( + [fix_type(interpreter)] + + [fix_type(arg) for arg in interpreter_args] + + [fix_type(script)] + + unquoted_args[1:] + ) # Note: we create a copy as string to help with analyzing the arguments, but # the final list should have items from the unquoted_args as they were initially. @@ -738,7 +1033,11 @@ def new_execl(path, *args): os.execlpe(file, arg0, arg1, ..., env) """ if _get_apply_arg_patching(): - args = patch_args(args, is_exec=True) + args, executable = _patch_args_for_launch( + path, args, is_exec=True, search_path=_uses_path_search(original_name) + ) + if executable is not None: + path = executable send_process_created_message() send_process_about_to_be_replaced() @@ -754,7 +1053,11 @@ def new_execv(path, args): os.execvp(file, args) """ if _get_apply_arg_patching(): - args = patch_args(args, is_exec=True) + args, executable = _patch_args_for_launch( + path, args, is_exec=True, search_path=_uses_path_search(original_name) + ) + if executable is not None: + path = executable send_process_created_message() send_process_about_to_be_replaced() @@ -771,7 +1074,15 @@ def create_execve(original_name): def new_execve(path, args, env): if _get_apply_arg_patching(): - args = patch_args(args, is_exec=True) + args, executable = _patch_args_for_launch( + path, + args, + is_exec=True, + env=env, + search_path=_uses_path_search(original_name), + ) + if executable is not None: + path = executable send_process_created_message() send_process_about_to_be_replaced() @@ -787,7 +1098,11 @@ def new_spawnl(mode, path, *args): os.spawnlp(mode, file, arg0, arg1, ...) """ if _get_apply_arg_patching(): - args = patch_args(args) + args, executable = _patch_args_for_launch( + path, args, search_path=_uses_path_search(original_name) + ) + if executable is not None: + path = executable send_process_created_message() return getattr(os, original_name)(mode, path, *args) @@ -802,7 +1117,11 @@ def new_spawnv(mode, path, args): os.spawnvp(mode, file, args) """ if _get_apply_arg_patching(): - args = patch_args(args) + args, executable = _patch_args_for_launch( + path, args, search_path=_uses_path_search(original_name) + ) + if executable is not None: + path = executable send_process_created_message() return getattr(os, original_name)(mode, path, args) @@ -818,7 +1137,11 @@ def create_spawnve(original_name): def new_spawnve(mode, path, args, env): if _get_apply_arg_patching(): - args = patch_args(args) + args, executable = _patch_args_for_launch( + path, args, env=env, search_path=_uses_path_search(original_name) + ) + if executable is not None: + path = executable send_process_created_message() return getattr(os, original_name)(mode, path, args, env) @@ -833,7 +1156,18 @@ def create_posix_spawn(original_name): def new_posix_spawn(executable, args, env, **kwargs): if _get_apply_arg_patching(): - args = patch_args(args) + # posix_spawnp searches for the file using this process's + # PATH, not the child environment's: only the env-shebang + # interpreter resolution uses the child environment. + args, shebang_executable = _patch_args_for_launch( + executable, + args, + env=env, + search_path=_uses_path_search(original_name), + file_env=None, + ) + if shebang_executable is not None: + executable = shebang_executable send_process_created_message() return getattr(os, original_name)(executable, args, env, **kwargs) @@ -850,7 +1184,31 @@ def new_fork_exec(args, *other_args): import _posixsubprocess # @UnresolvedImport if _get_apply_arg_patching(): - args = patch_args(args) + # The first existing entry in the executable list is the + # program that will actually run (relative entries resolve + # against the child's working directory). + env_list = other_args[4] if len(other_args) > 4 else None + cwd = other_args[3] if len(other_args) > 3 else None + actual_executable = None + if other_args: + for candidate in other_args[0]: + candidate_path = candidate + if cwd is not None and not os.path.isabs(os.fsdecode(candidate)): + candidate_path = os.path.join( + os.fsdecode(cwd), os.fsdecode(candidate) + ) + if os.path.isfile(candidate_path): + actual_executable = candidate + break + args, executable = _patch_args_for_launch( + actual_executable, args, env=env_list, cwd=cwd + ) + if executable is not None and other_args: + if other_args[0] and isinstance(other_args[0][0], bytes) != isinstance( + executable, bytes + ): + executable = _get_str_type_compatible(other_args[0][0], executable) + other_args = ((executable,),) + other_args[1:] send_process_created_message() return getattr(_posixsubprocess, original_name)(args, *other_args) @@ -884,7 +1242,31 @@ def new_fork_exec(args, *other_args): import subprocess if _get_apply_arg_patching(): - args = patch_args(args) + # The first existing entry in the executable list is the + # program that will actually run (relative entries resolve + # against the child's working directory). + env_list = other_args[4] if len(other_args) > 4 else None + cwd = other_args[3] if len(other_args) > 3 else None + actual_executable = None + if other_args: + for candidate in other_args[0]: + candidate_path = candidate + if cwd is not None and not os.path.isabs(os.fsdecode(candidate)): + candidate_path = os.path.join( + os.fsdecode(cwd), os.fsdecode(candidate) + ) + if os.path.isfile(candidate_path): + actual_executable = candidate + break + args, executable = _patch_args_for_launch( + actual_executable, args, env=env_list, cwd=cwd + ) + if executable is not None and other_args: + if other_args[0] and isinstance(other_args[0][0], bytes) != isinstance( + executable, bytes + ): + executable = _get_str_type_compatible(other_args[0][0], executable) + other_args = ((executable,),) + other_args[1:] send_process_created_message() return getattr(subprocess, original_name)(args, *other_args) diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py index 55adac33f..7f0d08721 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py @@ -512,3 +512,738 @@ def test_monkey_patch_args_c_with_bytes() -> None: # The result should contain our patched debugpy setup somewhere result_str: str = b"".join(item.encode() if isinstance(item, str) else item for item in result).decode() assert "pydevd.settrace" in result_str + + +def _check_shebang_script(tmp_path, shebang, expected_prefix) -> None: + from _pydevd_bundle.pydevd_command_line_handling import get_pydevd_file + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text(shebang + "\nprint('hello')\n") + script.chmod(0o755) + + assert pydev_monkey.patch_args([str(script), "bar"]) == expected_prefix + [ + get_pydevd_file(), + "--port", + "0", + "--ppid", + str(os.getpid()), + "--client", + "127.0.0.1", + "--multiprocess", + "--protocol-quoted-line", + "--file", + str(script), + "bar", + ] + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_env_script(tmp_path) -> None: + _check_shebang_script(tmp_path, "#!/usr/bin/env python3", ["python3"]) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_direct_script(tmp_path) -> None: + _check_shebang_script(tmp_path, "#!/usr/bin/python3", ["/usr/bin/python3"]) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_env_split_script(tmp_path) -> None: + _check_shebang_script(tmp_path, "#!/usr/bin/env -S python3 -u", ["python3", "-u"]) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_direct_script_with_arg(tmp_path) -> None: + _check_shebang_script(tmp_path, "#!/usr/bin/python3 -O", ["/usr/bin/python3", "-O"]) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_env_unsupported_option_script(tmp_path) -> None: + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env -i python3\nprint('hello')\n") + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_env_split_quoted_script(tmp_path) -> None: + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text( + "#!/usr/bin/env -S python3 -W \"ignore::DeprecationWarning\"\nprint('hello')\n" + ) + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_non_executable_script(tmp_path) -> None: + # A script without execute permission cannot be launched directly, so + # it must not become launchable through the interpreter replacement. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o644) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_crlf_script(tmp_path) -> None: + # A CRLF shebang fails to launch natively (the kernel includes the + # carriage return in the interpreter name), so it must be left + # unchanged rather than normalized into a working launch. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_bytes(b"#!/usr/bin/env python3\r\nprint('hello')\r\n") + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_leading_whitespace_shebang_script(tmp_path) -> None: + # The shebang must be at the very start of the file: a leading + # space means the file is not a script at all natively. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text(" #!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_env_split_comment_script(tmp_path) -> None: + # env -S treats # as a comment start: such launches are left + # unchanged instead of passing the comment on as arguments. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env -S python3 # comment\nprint('hello')\n") + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_env_split_expansion_script(tmp_path) -> None: + # env -S expands ${...} from the environment: such launches are + # left unchanged instead of passing the expansion through literally. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env -S python3 -W ${WARNINGS}\nprint('hello')\n") + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_non_python_script(tmp_path) -> None: + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/bin/sh\necho hello\n") + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_script_on_path(tmp_path, monkeypatch) -> None: + from _pydevd_bundle.pydevd_command_line_handling import get_pydevd_file + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ.get("PATH", "")) + + # The script is referenced by bare name, so the patched args must use + # the resolved path for --file. + assert pydev_monkey.patch_args(["child_script", "bar"]) == [ + "python3", + get_pydevd_file(), + "--port", + "0", + "--ppid", + str(os.getpid()), + "--client", + "127.0.0.1", + "--multiprocess", + "--protocol-quoted-line", + "--file", + str(script), + "bar", + ] + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_script_with_bytes(tmp_path) -> None: + from _pydevd_bundle.pydevd_command_line_handling import get_pydevd_file + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + assert pydev_monkey.patch_args([os.fsencode(script), b"bar"]) == [ + b"python3", + get_pydevd_file(), + "--port", + "0", + "--ppid", + str(os.getpid()), + "--client", + "127.0.0.1", + "--multiprocess", + "--protocol-quoted-line", + "--file", + os.fsencode(script), + b"bar", + ] + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_script_with_executable_override(tmp_path) -> None: + # An explicit executable override targeting a different program must + # be respected end to end: that program runs with the original + # arguments unchanged. This is a regression guard (it also passes + # without the fix, where no patching happens at all). + import subprocess + + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('child')\n") + script.chmod(0o755) + + pydevd_dir = os.path.dirname(os.path.dirname(pydev_monkey.__file__)) + harness = tmp_path / "harness.py" + harness.write_text( + "import subprocess, sys\n" + "sys.path.insert(0, %r)\n" + "from _pydev_bundle import pydev_monkey\n" + "from pydevd import SetupHolder\n" + "SetupHolder.setup = {'client': '127.0.0.1', 'port': '0', 'multiprocess': True}\n" + "pydev_monkey.patch_new_process_functions()\n" + "out = subprocess.run([%r, 'hello'], executable='/bin/echo', capture_output=True, text=True)\n" + "print(out.stdout, end='')\n" % (pydevd_dir, str(script)) + ) + out = subprocess.run( + [sys.executable, str(harness)], capture_output=True, text=True, timeout=60 + ) + assert out.stdout == "hello\n" + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_script_with_child_cwd(tmp_path) -> None: + # The script the child will run is resolved against the child's + # working directory: an executable namesake in the parent directory + # must not make a non-executable namesake in the child directory + # launchable. Regression guard (also passes without the fix). + import subprocess + + parent_dir = tmp_path / "parent" + parent_dir.mkdir() + parent_script = parent_dir / "child_script" + parent_script.write_text("#!/usr/bin/env python3\nprint('parent')\n") + parent_script.chmod(0o755) + + child_dir = tmp_path / "child" + child_dir.mkdir() + child_script = child_dir / "child_script" + child_script.write_text("#!/usr/bin/env python3\nprint('child')\n") + child_script.chmod(0o644) + + pydevd_dir = os.path.dirname(os.path.dirname(pydev_monkey.__file__)) + harness = tmp_path / "harness.py" + harness.write_text( + "import os, subprocess, sys\n" + "sys.path.insert(0, %r)\n" + "from _pydev_bundle import pydev_monkey\n" + "from pydevd import SetupHolder\n" + "SetupHolder.setup = {'client': '127.0.0.1', 'port': '0', 'multiprocess': True}\n" + "pydev_monkey.patch_new_process_functions()\n" + "os.chdir(%r)\n" + "try:\n" + " subprocess.run(['./child_script', 'hello'], cwd=%r, capture_output=True, text=True, timeout=60)\n" + " print('NO ERROR')\n" + "except PermissionError:\n" + " print('PermissionError')\n" % (pydevd_dir, str(parent_dir), str(child_dir)) + ) + out = subprocess.run( + [sys.executable, str(harness)], capture_output=True, text=True, timeout=60 + ) + assert out.stdout.strip() == "PermissionError" + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_child_cwd_bare_name(tmp_path, monkeypatch) -> None: + # With a relative PATH entry, a bare script name resolves against + # the child's working directory: a non-executable namesake there + # must not become launchable because an executable namesake exists + # in the parent directory. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + parent_dir = tmp_path / "parent" + parent_dir.mkdir() + parent_script = parent_dir / "child_script" + parent_script.write_text("#!/usr/bin/env python3\nprint('parent')\n") + parent_script.chmod(0o755) + + child_dir = tmp_path / "child" + child_dir.mkdir() + child_script = child_dir / "child_script" + child_script.write_text("#!/usr/bin/env python3\nprint('child')\n") + child_script.chmod(0o644) + + monkeypatch.chdir(parent_dir) + monkeypatch.setenv("PATH", os.pathsep + os.environ.get("PATH", "")) + original_args: list[str] = ["child_script", "hello"] + assert pydev_monkey._patch_args_for_launch( + "child_script", original_args[:], cwd=str(child_dir) + ) == (original_args, None) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_child_cwd_options(tmp_path, monkeypatch) -> None: + # The args and the interpreter replacement are built from the + # shebang of the file in the child's working directory, not the + # parent directory namesake. + from _pydevd_bundle.pydevd_command_line_handling import get_pydevd_file + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + parent_dir = tmp_path / "parent" + parent_dir.mkdir() + parent_script = parent_dir / "child_script" + parent_script.write_text("#!/usr/bin/env python3\nprint('parent')\n") + parent_script.chmod(0o755) + + child_dir = tmp_path / "child" + child_dir.mkdir() + child_script = child_dir / "child_script" + child_script.write_text("#!/usr/bin/python3 -O\nprint('child')\n") + child_script.chmod(0o755) + + monkeypatch.chdir(parent_dir) + new_args, executable = pydev_monkey._patch_args_for_launch( + "./child_script", ["./child_script", "hello"], cwd=str(child_dir) + ) + assert executable == "/usr/bin/python3" + assert new_args == [ + "/usr/bin/python3", + "-O", + get_pydevd_file(), + "--port", + "0", + "--ppid", + str(os.getpid()), + "--client", + "127.0.0.1", + "--multiprocess", + "--protocol-quoted-line", + "--file", + str(child_script), + "hello", + ] + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_relative_child_cwd(tmp_path, monkeypatch) -> None: + # A relative child cwd must still produce an absolute --file: the + # child has already changed into that directory when it runs. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + parent_dir = tmp_path / "parent" + parent_dir.mkdir() + child_dir = tmp_path / "child" + child_dir.mkdir() + child_script = child_dir / "child_script" + child_script.write_text("#!/usr/bin/env python3\nprint('child')\n") + child_script.chmod(0o755) + + monkeypatch.chdir(tmp_path) + new_args, executable = pydev_monkey._patch_args_for_launch( + "./child_script", ["./child_script", "hello"], cwd="child" + ) + assert executable is not None + assert new_args[new_args.index("--file") + 1] == str(child_script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_child_cwd_interpreter(tmp_path) -> None: + # A relative PATH entry in the child's environment is resolved + # against the child's working directory when picking the + # interpreter, so a child-local python3 wins over the system one. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + child_dir = tmp_path / "child" + child_dir.mkdir() + child_script = child_dir / "child_script" + child_script.write_text("#!/usr/bin/env python3\nprint('child')\n") + child_script.chmod(0o755) + fake_python = child_dir / "python3" + fake_python.write_text("#!/bin/sh\n") + fake_python.chmod(0o755) + + new_args, executable = pydev_monkey._patch_args_for_launch( + str(child_script), + [str(child_script), "hello"], + env={"PATH": "." + os.pathsep + "/usr/bin" + os.pathsep + "/bin"}, + cwd=str(child_dir), + ) + assert executable == str(fake_python) + assert new_args[0] == "python3" + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_script_only_in_child_cwd(tmp_path) -> None: + # A script that exists only in the child's working directory must + # still be attached: the executable list entries are relative and + # have to be resolved against the child cwd to find it. + import subprocess + + parent_dir = tmp_path / "parent" + parent_dir.mkdir() + child_dir = tmp_path / "child" + child_dir.mkdir() + child_script = child_dir / "child_script" + child_script.write_text("#!/usr/bin/env python3\nprint('CHILD RAN')\n") + child_script.chmod(0o755) + + pydevd_dir = os.path.dirname(os.path.dirname(pydev_monkey.__file__)) + harness = tmp_path / "harness.py" + harness.write_text( + "import os, subprocess, sys\n" + "sys.path.insert(0, %r)\n" + "from _pydev_bundle import pydev_monkey\n" + "from pydevd import SetupHolder\n" + "SetupHolder.setup = {'client': '127.0.0.1', 'port': '0', 'multiprocess': True}\n" + "pydev_monkey.patch_new_process_functions()\n" + "os.chdir(%r)\n" + "out = subprocess.run(['./child_script', 'hello'], cwd=%r, capture_output=True, text=True, timeout=60)\n" + "print('STDOUT:', out.stdout)\n" + "print('STDERR:', out.stderr)\n" % (pydevd_dir, str(parent_dir), str(child_dir)) + ) + out = subprocess.run( + [sys.executable, str(harness)], capture_output=True, text=True, timeout=60 + ) + # The child entered pydevd (which then fails to connect, as there is + # no debug server in this harness) instead of running the script + # directly. + assert "CHILD RAN" not in out.stdout + assert "pydevd" in out.stdout + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_no_path_search(tmp_path, monkeypatch) -> None: + # Non-PATH-searching APIs (execv, spawnv, posix_spawn) treat a bare + # executable name as a path relative to the current directory: it + # must not be resolved through PATH even when a same-named python + # script exists there. + import shutil + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + on_path_script = bin_dir / "child_script" + on_path_script.write_text("#!/usr/bin/env python3\nprint('on path')\n") + on_path_script.chmod(0o755) + monkeypatch.setenv("PATH", str(bin_dir) + os.pathsep + os.environ.get("PATH", "")) + monkeypatch.chdir(tmp_path) + + original_args: list[str] = ["child_script", "hello"] + assert pydev_monkey._patch_args_for_launch( + "child_script", original_args[:], search_path=False + ) == (original_args, None) + + # The PATH-searching variants do resolve and replace it. + new_args, executable = pydev_monkey._patch_args_for_launch( + "child_script", original_args[:], search_path=True + ) + assert executable == shutil.which("python3") + assert new_args != original_args + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_posix_spawn_no_path_search(tmp_path) -> None: + # Through the hook: os.posix_spawn with a bare name that exists + # only on PATH raises FileNotFoundError, exactly as it does + # natively (it does not search PATH). + import subprocess + + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + on_path_script = bin_dir / "zz_child_script_1929" + on_path_script.write_text("#!/usr/bin/env python3\nprint('on path')\n") + on_path_script.chmod(0o755) + + pydevd_dir = os.path.dirname(os.path.dirname(pydev_monkey.__file__)) + harness = tmp_path / "harness.py" + harness.write_text( + "import os, sys\n" + "sys.path.insert(0, %r)\n" + "from _pydev_bundle import pydev_monkey\n" + "from pydevd import SetupHolder\n" + "SetupHolder.setup = {'client': '127.0.0.1', 'port': '0', 'multiprocess': True}\n" + "pydev_monkey.patch_new_process_functions()\n" + "os.chdir(%r)\n" + "try:\n" + " pid = os.posix_spawn('zz_child_script_1929', ['zz_child_script_1929', 'hello'], os.environ)\n" + " os.waitpid(pid, 0)\n" + " print('SPAWNED')\n" + "except FileNotFoundError:\n" + " print('FileNotFoundError')\n" + % (pydevd_dir, str(tmp_path)) + ) + env = dict(os.environ) + env["PATH"] = str(bin_dir) + os.pathsep + env.get("PATH", "") + out = subprocess.run( + [sys.executable, str(harness)], + capture_output=True, + text=True, + timeout=60, + env=env, + ) + assert out.stdout.strip() == "FileNotFoundError" + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_direct_bare_interpreter(tmp_path, monkeypatch) -> None: + # A direct shebang with a bare interpreter name (#!python3) is + # resolved by the kernel relative to the working directory, not + # through PATH. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!python3\nprint('hello')\n") + script.chmod(0o755) + + original_args: list[str] = [str(script), "hello"] + + # No python3 in the working directory: the launch is preserved + # (it fails natively), even though python3 exists on PATH. + monkeypatch.chdir(tmp_path) + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:] + ) == (original_args, None) + + # A python3 in the child's working directory is the interpreter + # that runs. + local_python = tmp_path / "python3" + local_python.write_text("#!/bin/sh\n") + local_python.chmod(0o755) + new_args = pydev_monkey.patch_args(original_args[:]) + assert pydev_monkey._get_shebang_executable( + str(script), original_args, new_args, cwd=str(tmp_path) + ) == str(local_python) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_missing_env_script(tmp_path) -> None: + # When the env program named by the shebang does not exist, the + # native launch fails: the args must be left unchanged rather + # than rewritten into a working interpreter launch. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/nonexistent/env python3\nprint('hello')\n") + script.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + assert pydev_monkey._patch_args_for_launch(str(script), check[:]) == (check, None) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_child_path_only(tmp_path, monkeypatch) -> None: + # A bare script name that only resolves through the child's PATH + # (not the parent's) must still be attached. + import shutil + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + script = bin_dir / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + monkeypatch.setenv("PATH", "/usr/bin" + os.pathsep + "/bin") + assert shutil.which("child_script") is None + + child_env = {"PATH": str(bin_dir) + os.pathsep + "/usr/bin" + os.pathsep + "/bin"} + new_args, executable = pydev_monkey._patch_args_for_launch( + str(script), ["child_script", "hello"], env=child_env + ) + assert executable == shutil.which("python3") + assert new_args[new_args.index("--file") + 1] == str(script) + + +def test_get_env_path_environ(monkeypatch) -> None: + # os.environ is a mapping (not a dict): its PATH must be read as + # such instead of falling back to os.defpath. + monkeypatch.setenv("PATH", "/some/bin" + os.pathsep + "/usr/bin") + assert pydev_monkey._get_env_path(os.environ) == "/some/bin" + os.pathsep + "/usr/bin" + assert pydev_monkey._get_env_path({"PATH": "/a"}) == "/a" + assert pydev_monkey._get_env_path([b"PATH=/b", b"OTHER=1"]) == "/b" + assert pydev_monkey._get_env_path({}) == os.defpath + assert pydev_monkey._get_env_path(None) is None + + +def test_get_env_path_environ_key_types(monkeypatch) -> None: + # Probing a mapping with the wrong key type must not raise: + # os.environ rejects bytes keys and os.environb rejects str keys. + monkeypatch.delenv("PATH", raising=False) + assert pydev_monkey._get_env_path(os.environ) == os.defpath + if hasattr(os, "environb"): + monkeypatch.setenv("PATH", "/some/bin") + assert pydev_monkey._get_env_path(os.environb) == "/some/bin" + monkeypatch.delenv("PATH", raising=False) + assert pydev_monkey._get_env_path(os.environb) == os.defpath + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_spawnp_parent_path(tmp_path, monkeypatch) -> None: + # posix_spawnp resolves the file through this process's PATH, not + # the child environment's: a script only present in the child PATH + # must not be selected (the native launch fails), while the child + # PATH still resolves the env-shebang interpreter once the script + # itself is found. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + script = bin_dir / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + child_env = {"PATH": str(bin_dir) + os.pathsep + "/usr/bin" + os.pathsep + "/bin"} + + monkeypatch.setenv("PATH", "/nonexistent") + original_args: list[str] = ["child_script", "hello"] + assert pydev_monkey._patch_args_for_launch( + "child_script", original_args[:], env=child_env, search_path=True, file_env=None + ) == (original_args, None) + + monkeypatch.setenv("PATH", str(bin_dir) + os.pathsep + "/usr/bin") + new_args, executable = pydev_monkey._patch_args_for_launch( + "child_script", original_args[:], env=child_env, search_path=True, file_env=None + ) + assert executable == pydev_monkey._which("python3", path=child_env["PATH"]) + assert new_args[new_args.index("--file") + 1] == str(script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_executable(tmp_path) -> None: + import shutil + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + original_args: list[str] = [str(script), "bar"] + new_args = pydev_monkey.patch_args(original_args[:]) + assert new_args != original_args + # The interpreter is a bare name in the shebang, so the executable to + # launch must be resolved through PATH. + assert pydev_monkey._get_shebang_executable( + str(script), original_args, new_args + ) == shutil.which("python3") + # Unchanged args mean no executable replacement. + assert ( + pydev_monkey._get_shebang_executable(str(script), original_args, original_args) + is None + ) + # An explicit executable override targeting a different program must + # be respected: no replacement when the actual executable is not the + # shebang script. + assert pydev_monkey._get_shebang_executable(__file__, original_args, new_args) is None + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_executable_child_env(tmp_path) -> None: + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + fake_python = bin_dir / "python3" + fake_python.write_text("#!/bin/sh\n") + fake_python.chmod(0o755) + + original_args: list[str] = [str(script), "bar"] + new_args = pydev_monkey.patch_args(original_args[:]) + assert new_args != original_args + + # The interpreter is resolved through the child's PATH, not ours. + assert pydev_monkey._get_shebang_executable( + str(script), original_args, new_args, env={"PATH": str(bin_dir)} + ) == str(fake_python) + + # When the interpreter cannot be resolved in the child's environment, + # the launch is preserved unchanged. + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:], env={"PATH": "/nonexistent"} + ) == (original_args, None) From 379089dc4b292b7ffd8b7ec60ed54320e9643bfb Mon Sep 17 00:00:00 2001 From: Teja P C <39472754+PCTEJA@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:21:55 +0000 Subject: [PATCH 2/4] Address review feedback on shebang subprocess patching Launch env shebang scripts through the env program instead of resolving the interpreter, reuse os.get_exec_path for child environment PATH handling, patch based on the executable actually selected for a launch when it differs from args[0], share one fork_exec patching helper between both hooks, and select the first viable entry of the fork_exec executable list. --- .../pydevd/_pydev_bundle/pydev_monkey.py | 738 ++++++++++++--- .../pydevd/tests_python/test_pydev_monkey.py | 893 +++++++++++++++++- 2 files changed, 1471 insertions(+), 160 deletions(-) diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py index 758b3f506..d9d2d6dea 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py @@ -3,8 +3,10 @@ from _thread import _local import os +import platform import re import shutil +import struct import sys from typing import Generator from _pydev_bundle._pydev_saved_modules import threading @@ -325,15 +327,18 @@ def _which(command, path=None, cwd=None): return None -def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool] | None: +def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, str] | None: """ :return: - A tuple (interpreter, interpreter_args, resolved_path, via_env) - if the file at path starts with a shebang pointing at a python - interpreter, None otherwise. resolved_path is the path actually - read (the script resolved through PATH when path is a bare - name). Relative paths are resolved against cwd when it is given - (the child process working directory for subprocess launches). + A tuple (interpreter, interpreter_args, resolved_path, via_env, + program) if the file at path starts with a shebang pointing at a + python interpreter, None otherwise. resolved_path is the path + actually read (the script resolved through PATH when path is a + bare name). Relative paths are resolved against cwd when it is + given (the child process working directory for subprocess + launches). program is the program named by the shebang itself + (the interpreter for a direct shebang, the env program for an + env shebang). """ target = path if os.path.dirname(os.fsdecode(path)): @@ -364,6 +369,12 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool] except Exception: return None + if len(first_line.rstrip(b"\n")) >= _SHEBANG_WINDOW: + # The kernel reads the shebang from a fixed-size buffer + # (512 bytes on macOS, 256 elsewhere): a longer first line + # cannot be launched as a script at all. + return None + if b"\r" in first_line: # A carriage return is part of the interpreter name the kernel # passes on (i.e.: CRLF scripts fail to launch natively): do @@ -380,6 +391,7 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool] parts = line.split(None, 1) interpreter = parts[0] + program = interpreter rest = parts[1] if len(parts) > 1 else "" via_env = False @@ -428,37 +440,43 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool] if not is_python(interpreter): return None - return interpreter, args, os.fsdecode(target), via_env + return interpreter, args, os.fsdecode(target), via_env, program def _get_env_path(env): """ :return: The PATH to use for lookups in the child process environment - (a dict for execve/spawnve/posix_spawn, a list of "name=value" + (a mapping for execve/spawnve/posix_spawn, a list of "name=value" entries for fork_exec), or None when the child inherits this process's environment. """ if env is None: return None - if isinstance(env, Mapping): - for key in ("PATH", b"PATH"): - try: - if key in env: - return os.fsdecode(env[key]) - except TypeError: - # i.e.: probing os.environ with a bytes key (or - # os.environb with a str key) raises TypeError. - continue - return os.defpath + if not isinstance(env, Mapping): + # os.get_exec_path expects a mapping: adapt fork_exec's list of + # "name=value" entries (keeping str/bytes as they are). + try: + adapted = {} + for entry in env: + if isinstance(entry, bytes): + key, sep, value = entry.partition(b"=") + else: + key, sep, value = entry.partition("=") + if sep: + adapted[key] = value + env = adapted + except Exception: + return None try: - for entry in env: - entry = os.fsdecode(entry) - if entry.startswith("PATH="): - return entry[len("PATH=") :] - except Exception: - return None - return os.defpath + return os.pathsep.join(os.get_exec_path(env)) + except (TypeError, ValueError): + # A mapping holding both str and bytes PATH keys is rejected by + # os.get_exec_path: fall back to the str entry, as before. + try: + return os.fsdecode(env["PATH"]) + except Exception: + return os.defpath _SAME_AS_ENV = object() @@ -467,10 +485,13 @@ def _get_env_path(env): def _get_shebang_executable(executable, original_args, new_args, env=None, cwd=None, file_env=_SAME_AS_ENV): """ If patch_args rewrote the args because the executable is a script with - a python shebang, the process must be launched through the interpreter - from the shebang instead of the script itself: return that interpreter - (resolved through the child PATH when it is a bare name), otherwise - return None. + a python shebang, the process must be launched through the program + from the shebang instead of the script itself: return that program, + otherwise return None. For a direct shebang that program is the + interpreter itself. For an env shebang it is the env program: env + then looks the interpreter up in the child process's PATH and + working directory when it actually runs, so no interpreter + resolution is duplicated here. """ if new_args == original_args: return None @@ -485,32 +506,33 @@ def _get_shebang_executable(executable, original_args, new_args, env=None, cwd=N if shebang_info is None: return None - interpreter, _interpreter_args, _script, via_env = shebang_info - if not os.path.dirname(interpreter): - if via_env: - # env searches PATH for the interpreter. - resolved = _which(interpreter, path=_get_env_path(env), cwd=cwd) - if resolved is None: - if env is not None: - # The interpreter cannot be resolved in the child's - # environment: do not rewrite the launch. - return None - resolved = interpreter - interpreter = resolved - else: - # A direct shebang with a bare interpreter name is resolved - # by the kernel relative to the working directory, not - # through PATH. - candidate = interpreter - if cwd is not None: - candidate = os.path.join(os.fsdecode(cwd), interpreter) - if not (os.path.isfile(candidate) and os.access(candidate, os.X_OK)): - return None - interpreter = os.path.abspath(candidate) + interpreter, _interpreter_args, _script, via_env, program = shebang_info + launch_program = program if via_env else interpreter + if not os.path.dirname(launch_program): + # A bare program name in a shebang is resolved by the kernel + # relative to the working directory, not through PATH. + candidate = launch_program + if cwd is not None: + candidate = os.path.join(os.fsdecode(cwd), launch_program) + if not (os.path.isfile(candidate) and os.access(candidate, os.X_OK)): + return None + launch_program = os.path.abspath(candidate) if isinstance(executable, (str, bytes)): - return _get_str_type_compatible(executable, interpreter) - return interpreter + return _get_str_type_compatible(executable, launch_program) + return launch_program + + +def _prepend_shebang_program(new_args, shebang_info): + """ + For an env shebang, the patched args must run through the env + program so that it performs the interpreter lookup at exec time: + insert it ahead of the interpreter named by the shebang. + """ + if not shebang_info[3]: + return new_args + program = _get_str_type_compatible(new_args[0], shebang_info[4]) + return [program] + list(new_args) def _uses_path_search(original_name) -> bool: @@ -523,6 +545,185 @@ def _uses_path_search(original_name) -> bool: return name.endswith("p") +def _resolve_launch_file(executable, cwd=None, search_path=True, env=None): + """ + :return: + The file the selected executable refers to for this launch, or + None when there is no such file. A bare name is searched through + PATH only for the PATH-searching variants; otherwise it is a + path relative to the child's working directory. + """ + path = os.fsdecode(executable) + if os.path.dirname(path): + if cwd is not None and not os.path.isabs(path): + # Make it absolute: the result is resolved further against + # the same cwd downstream, which must not apply it twice. + path = os.path.abspath(os.path.join(os.fsdecode(cwd), path)) + return path if os.path.isfile(path) else None + if search_path: + return _which(path, path=_get_env_path(env), cwd=cwd) + candidate = path + if cwd is not None: + candidate = os.path.join(os.fsdecode(cwd), path) + return os.path.abspath(candidate) if os.path.isfile(candidate) else None + + +_PATCH_UNSAFE = object() + + +def _has_unsupported_python_shebang(path): + """ + Whether the file at path has a shebang that _parse_shebang could + not handle but that still points at a python interpreter (i.e.: + an env form with quoted arguments or unsupported options): such + a launch is a python script launch that cannot be patched safely, + which is different from an executable that is not a python script + at all. + """ + try: + with open(path, "rb") as stream: + first_line = stream.readline(1024) + except Exception: + return False + if not first_line.startswith(b"#!"): + return False + tokens = first_line[2:].split() + if not tokens: + return False + # env -S applies its own quoting rules: strip quote characters so + # a quoted interpreter name (i.e.: p"ython3") is still recognized. + tokens = [token.replace(b'"', b"").replace(b"'", b"").replace(b"\\", b"") for token in tokens] + if is_python(os.fsdecode(tokens[0])): + return True + if os.path.basename(os.fsdecode(tokens[0])) == "env": + return any(is_python(os.fsdecode(token)) for token in tokens[1:]) + return False + + +def _shebang_interpreter_is_script(shebang_info, cwd=None, env=None): + """ + Whether launching through this shebang would run a script before + the interpreter: the interpreter itself is a script, or (for an + env shebang) the env program is one. Such a launch cannot be + patched faithfully: the kernel would run that script with the + debugger bootstrap arguments instead of the original ones. + """ + def _is_script(path): + if not path or not os.path.isfile(path): + return False + try: + with open(path, "rb") as stream: + return stream.read(2) == b"#!" + except Exception: + return False + + def _kernel_path(program): + # A shebang program with a directory part is used as given + # (relative to the working directory); a bare one is resolved + # by the kernel relative to the working directory too. + if os.path.dirname(program) and os.path.isabs(program): + return program + if cwd is not None: + return os.path.join(os.fsdecode(cwd), program) + return program + + interpreter = shebang_info[0] + if os.path.dirname(interpreter): + path = interpreter + if cwd is not None and not os.path.isabs(path): + path = os.path.join(os.fsdecode(cwd), path) + elif shebang_info[3]: + # env searches PATH for the interpreter. + path = _which(interpreter, path=_get_env_path(env), cwd=cwd) + else: + path = _kernel_path(interpreter) + if _is_script(path): + return True + if shebang_info[3]: + return _is_script(_kernel_path(shebang_info[4])) + return False + + +def _patch_args_for_selected_executable( + executable, args, is_exec=False, env=None, cwd=None, search_path=True, file_env=_SAME_AS_ENV +): + """ + Patch a launch based on the executable actually selected for it + rather than on args[0], which may name something else entirely + (i.e.: an explicit executable= override, or a custom argv[0]). + + :return: + A tuple (new_args, new_executable) when the selected executable + is a script with a python shebang and the launch was patched, + _PATCH_UNSAFE when it is such a script but the launch cannot + be patched safely (the caller must preserve the original + launch), and None when it is not such a script at all. + """ + if executable is None: + return None + + if file_env is _SAME_AS_ENV: + file_env = env + + is_shebang_script = False + try: + resolved = _resolve_launch_file(executable, cwd=cwd, search_path=search_path, env=file_env) + if resolved is None: + return None + + shebang_info = _parse_shebang(resolved, cwd=cwd, env=file_env) + if shebang_info is None: + if _has_unsupported_python_shebang(resolved): + return _PATCH_UNSAFE + return None + is_shebang_script = True + + if _shebang_interpreter_is_script(shebang_info, cwd=cwd, env=env): + return _PATCH_UNSAFE + + base = args[0] if args else executable + + # Build the candidate from the parsed shebang instead of the + # script path: patch_args keys its shebang handling off + # is_python(args[0]), and a script whose name happens to + # contain "python" would otherwise be mistaken for an + # interpreter and lose the script as the --file target. + if isinstance(base, bytes): + fix_type = os.fsencode + else: + fix_type = lambda s: s + candidate_args = ( + [fix_type(shebang_info[0])] + + [fix_type(arg) for arg in shebang_info[1]] + + [fix_type(shebang_info[2])] + + list(args[1:]) + ) + new_args = patch_args(candidate_args, is_exec=is_exec, cwd=cwd, env=file_env) + if new_args == candidate_args: + return _PATCH_UNSAFE + + # If the interpreter is itself a script, patch_args expands + # that second shebang level too and the rewrite retargets to + # the interpreter script: the executable selected below would + # no longer match the rewritten args, so the launch is left + # unchanged instead. + decoded_args = [os.fsdecode(arg) for arg in new_args] + if "--file" not in decoded_args or decoded_args[decoded_args.index("--file") + 1] != shebang_info[2]: + return _PATCH_UNSAFE + + replacement = _get_shebang_executable( + resolved, candidate_args, new_args, env=env, cwd=cwd, file_env=file_env + ) + if replacement is None: + return _PATCH_UNSAFE + + return _prepend_shebang_program(new_args, shebang_info), replacement + except Exception: + # Never break a launch because patching it failed (i.e.: a + # path that cannot be represented in the args' type). + return _PATCH_UNSAFE if is_shebang_script else None + + def _patch_args_for_launch( executable, args, is_exec=False, env=None, cwd=None, search_path=True, file_env=_SAME_AS_ENV ): @@ -532,11 +733,13 @@ def _patch_args_for_launch( :return: A tuple (new_args, new_executable), where new_executable is the - interpreter to launch instead of executable, or None when the - executable must be kept as is. When the patch_args rewrite was - driven by the shebang of args[0] but the executable being launched - is a different program (an explicit override), the original args - are returned unchanged. + program to launch instead of executable, or None when the + executable must be kept as is. The executable actually selected + for the launch determines what runs: when it is a script with a + python shebang the launch is patched based on it even if + args[0] names something else, and when it is a different program + than the one args[0] describes (an explicit override) the + original args are returned unchanged. """ if file_env is _SAME_AS_ENV: file_env = env @@ -545,36 +748,59 @@ def _patch_args_for_launch( # against it from the start: the file the child will run may differ # from the one visible from this process. new_args = patch_args(args, is_exec=is_exec, cwd=cwd, env=file_env) - if new_args == args or not args: - return new_args, None + if new_args != args and args: + try: + shebang_info = _parse_shebang(args[0], cwd=cwd, env=file_env) + except Exception: + shebang_info = None + if shebang_info is None: + # Patched because args[0] names a python executable: the + # executable needs no replacement, unless the executable + # actually selected is a python shebang script. When it is + # one but cannot be patched safely, the original launch is + # preserved instead of the args[0]-based rewrite. + selected = _patch_args_for_selected_executable( + executable, args, is_exec=is_exec, env=env, cwd=cwd, search_path=search_path, file_env=file_env + ) + if isinstance(selected, tuple): + return selected + return (args, None) if selected is _PATCH_UNSAFE else (new_args, None) - try: - shebang_info = _parse_shebang(args[0], cwd=cwd, env=file_env) - except Exception: - shebang_info = None - if shebang_info is None: - # Patched because args[0] names a python executable: the - # executable needs no replacement. - return new_args, None + if executable is None: + return args, None - if executable is None: - return args, None + executable_path = os.fsdecode(executable) + if not os.path.dirname(executable_path) and search_path: + executable_path = ( + _which(executable_path, path=_get_env_path(file_env), cwd=cwd) or executable_path + ) + elif cwd is not None and not os.path.isabs(executable_path): + executable_path = os.path.join(os.fsdecode(cwd), executable_path) + if os.path.abspath(executable_path) != os.path.abspath(shebang_info[2]): + # The selected executable is a different program than the + # one args[0] describes: patch based on it when it is a + # python shebang script, otherwise respect it unchanged. + selected = _patch_args_for_selected_executable( + executable, args, is_exec=is_exec, env=env, cwd=cwd, search_path=search_path, file_env=file_env + ) + return selected if isinstance(selected, tuple) else (args, None) - executable_path = os.fsdecode(executable) - if not os.path.dirname(executable_path) and search_path: - executable_path = ( - _which(executable_path, path=_get_env_path(file_env), cwd=cwd) or executable_path - ) - elif cwd is not None and not os.path.isabs(executable_path): - executable_path = os.path.join(os.fsdecode(cwd), executable_path) - if os.path.abspath(executable_path) != os.path.abspath(shebang_info[2]): - return args, None + if _shebang_interpreter_is_script(shebang_info, cwd=cwd, env=env): + return args, None + + replacement = _get_shebang_executable(executable, args, new_args, env=env, cwd=cwd, file_env=file_env) + if replacement is None: + return args, None - replacement = _get_shebang_executable(executable, args, new_args, env=env, cwd=cwd, file_env=file_env) - if replacement is None: - return args, None + return _prepend_shebang_program(new_args, shebang_info), replacement - return new_args, replacement + selected = _patch_args_for_selected_executable( + executable, args, is_exec=is_exec, env=env, cwd=cwd, search_path=search_path, file_env=file_env + ) + if isinstance(selected, tuple): + return selected + + return new_args, None class InvalidTypeInArgsException(Exception): @@ -688,15 +914,20 @@ def patch_args(args, is_exec=False, cwd=None, env=None): if not unquoted_args: return original_args - if not is_python(unquoted_args[0]): - shebang_info = _parse_shebang(unquoted_args[0], cwd=cwd, env=env) - if shebang_info is None: - pydev_log.debug("Process is not python, returning.") - return original_args + # A file with a python shebang is a script even when its name + # happens to look like an interpreter (is_python matches names + # containing "python"), so the shebang is checked first: a real + # interpreter binary has no shebang and falls through to the + # is_python handling below. + shebang_info = _parse_shebang(unquoted_args[0], cwd=cwd, env=env) + if shebang_info is None and not is_python(unquoted_args[0]): + pydev_log.debug("Process is not python, returning.") + return original_args + if shebang_info is not None: # The executable is a script with a python shebang: rewrite the # args to run it through that interpreter so it can be patched. - interpreter, interpreter_args, script, _via_env = shebang_info + interpreter, interpreter_args, script, _via_env, _program = shebang_info fix_type = lambda s: _get_str_type_compatible(unquoted_args[0], s) unquoted_args = ( [fix_type(interpreter)] @@ -1175,6 +1406,281 @@ def new_posix_spawn(executable, args, env, **kwargs): return new_posix_spawn +_SHEBANG_WINDOW = 512 if sys.platform == "darwin" else 256 + + +def _binfmt_misc_has_handlers(): + try: + entries = os.listdir("/proc/sys/fs/binfmt_misc") + except Exception: + return False + return any(entry not in ("register", "status") for entry in entries) + + +def _elf_candidate_is_viable(chunk, stream, size=None, cwd=None, check_interp=True): + """ + Whether an ELF file can be executed on this host. Only conclusive + failures count: a malformed header (bad class or data encoding, a + non-executable type, a missing or truncated program header table, + no loadable segment), a machine type this host cannot run + (compatibility types such as 32-bit x86 on x86_64 do run), or a + PT_INTERP loader that does not exist. Anything that cannot be + determined from the header is treated as viable. + """ + if len(chunk) < 20: + return False + ei_class, ei_data = chunk[4], chunk[5] + if ei_class not in (1, 2) or ei_data not in (1, 2): + return False + if len(chunk) < (64 if ei_class == 2 else 52): + # The probe reads up to 8192 bytes, so a shorter chunk is the + # whole file: its ELF header is conclusively truncated. + return False + endian = "<" if ei_data == 1 else ">" + if struct.unpack(endian + "H", chunk[16:18])[0] not in (2, 3): # ET_EXEC, ET_DYN + return False + machine = struct.unpack(endian + "H", chunk[18:20])[0] + host_machines = { + "x86_64": (62, 3), + "AMD64": (62, 3), + "aarch64": (183, 40), + "arm64": (183, 40), + "armv7l": (40,), + "i386": (3,), + "i686": (3,), + "riscv64": (243,), + "ppc64le": (21,), + "s390x": (22,), + "loongarch64": (258,), + } + host_machine = host_machines.get(platform.machine()) + if host_machine is not None and machine not in host_machine: + # A foreign machine type is only conclusively unexecutable + # when no binfmt_misc handler (i.e.: qemu) is registered to + # run it: with one, support cannot be ruled out here. + return _binfmt_misc_has_handlers() + try: + if ei_class == 2: + phoff = struct.unpack(endian + "Q", chunk[32:40])[0] + phentsize = struct.unpack(endian + "H", chunk[54:56])[0] + phnum = struct.unpack(endian + "H", chunk[56:58])[0] + phentsize_expected = 56 + offset_at = 8 + filesz_at = 32 + offset_fmt = endian + "Q" + else: + phoff = struct.unpack(endian + "I", chunk[28:32])[0] + phentsize = struct.unpack(endian + "H", chunk[42:44])[0] + phnum = struct.unpack(endian + "H", chunk[44:46])[0] + phentsize_expected = 32 + offset_at = 4 + filesz_at = 16 + offset_fmt = endian + "I" + if phnum == 0 or phentsize != phentsize_expected: + return False + if phnum == 0xFFFF: + # Extended program header numbering: the real count is in + # the section header table, which is not probed here. + return True + if phnum * phentsize > 65536: + # The kernel rejects larger program header tables. + return False + if size is not None and phoff + phnum * phentsize > size: + return False + found_load = False + for i in range(min(phnum, 64)): + entry_at = phoff + i * phentsize + if entry_at + phentsize <= len(chunk): + entry = chunk[entry_at : entry_at + phentsize] + else: + stream.seek(entry_at) + entry = stream.read(phentsize) + if len(entry) < filesz_at + struct.calcsize(offset_fmt): + return True + p_type = struct.unpack(endian + "I", entry[:4])[0] + if p_type == 1: # PT_LOAD + found_load = True + elif p_type == 3 and check_interp: # PT_INTERP + interp_at = struct.unpack(offset_fmt, entry[offset_at : offset_at + struct.calcsize(offset_fmt)])[0] + filesz = struct.unpack(offset_fmt, entry[filesz_at : filesz_at + struct.calcsize(offset_fmt)])[0] + stream.seek(interp_at) + raw_interp = stream.read(filesz if 0 < filesz <= 65536 else 512) + if b"\x00" not in raw_interp: + # The pathname could not be read in full: not a + # conclusive failure. + return True + interp = os.fsdecode(raw_interp.split(b"\x00", 1)[0]) + if not interp: + return True + if not os.path.isabs(interp): + base = os.fsdecode(cwd) if cwd is not None else os.getcwd() + interp = os.path.join(base, interp) + if not (os.path.isfile(interp) and os.access(interp, os.X_OK)): + return False + if not _loader_candidate_is_viable(interp): + return False + if phnum <= 64 and not found_load: + return False + return True + except Exception: + return True + + +def _loader_candidate_is_viable(path): + """ + Whether the PT_INTERP loader itself can be loaded: it must be a + binary in a format this platform executes (a script loader fails), + with a conclusively valid header. Its own PT_INTERP, if any, is + not honored by the kernel and is not checked. A loader that + cannot be read here is not a conclusive failure. + """ + try: + with open(path, "rb") as stream: + chunk = stream.read(8192) + if chunk.startswith(b"#!"): + return False + if sys.platform == "darwin": + return _binary_candidate_is_viable(chunk, stream) + if not chunk.startswith(b"\x7fELF"): + return False + try: + size = os.fstat(stream.fileno()).st_size + except Exception: + size = None + return _elf_candidate_is_viable(chunk, stream, size=size, check_interp=False) + except Exception: + return True + + +def _binary_candidate_is_viable(chunk, stream, cwd=None): + """ + Whether a file without a shebang is in a binary format this + platform's kernel executes: a plain text file fails with ENOEXEC, + and so does a binary for a different platform. + """ + if sys.platform == "darwin": + return chunk.startswith((b"\xfe\xed\xfa", b"\xce\xfa\xed", b"\xcf\xfa\xed", b"\xca\xfe\xba\xbe")) + if chunk.startswith(b"\x7fELF"): + try: + size = os.fstat(stream.fileno()).st_size + except Exception: + size = None + return _elf_candidate_is_viable(chunk, stream, size=size, cwd=cwd) + # Not a natively executable format: conclusively unexecutable + # only when no binfmt_misc handler (i.e.: Wine for PE binaries) + # is registered that could run it. + return _binfmt_misc_has_handlers() + + +def _execve_candidate_is_viable(candidate_path, cwd=None, _depth=0): + """ + Whether an execve of this file can succeed at all, which is what + makes fork_exec move on to the next entry in the executable list. + A file that is not executable fails, and so does a script whose + shebang program cannot itself be executed (the kernel reports the + missing interpreter as the exec failure, recursing through nested + shebangs) and a text file without a shebang (ENOEXEC). A file that + cannot be read here (an execute-only binary still runs) is treated + as viable: its execve succeeds, even if the program it launches + then fails on its own. + """ + if not os.access(candidate_path, os.X_OK): + return False + try: + with open(candidate_path, "rb") as stream: + chunk = stream.read(8192) + if not chunk.startswith(b"#!"): + return _binary_candidate_is_viable(chunk, stream, cwd=cwd) + # The kernel parses the shebang from a fixed-size window + # (512 bytes on macOS, 256 elsewhere): a long optional + # argument is truncated, but an interpreter pathname that + # is not terminated within the window (by a blank, a + # newline, or a NUL) cannot be launched at all. + window = chunk[:_SHEBANG_WINDOW] + first_line = window.split(b"\n", 1)[0].split(b"\x00", 1)[0] + body = first_line[2:].lstrip(b" \t") + if ( + len(window) == _SHEBANG_WINDOW + and b"\n" not in window + and b"\x00" not in window + and b" " not in body + and b"\t" not in body + ): + return False + except Exception: + return True + if _depth >= 5: + # The kernel gives up on nested shebangs past a fixed depth. + return False + # The kernel takes the interpreter pathname up to the first blank: + # a carriage return before that blank is part of the pathname (and + # makes it not exist), while one after it lands in the argument + # passed to an existing interpreter, whose execve still succeeds. + line = first_line[2:].rstrip(b"\n").lstrip(b" \t") + end = len(line) + for sep in (b" ", b"\t"): + i = line.find(sep) + if i != -1: + end = min(end, i) + if end == 0: + return False + program = os.fsdecode(line[:end]) + if not os.path.isabs(program): + base = os.fsdecode(cwd) if cwd is not None else os.getcwd() + program = os.path.join(base, program) + if not os.path.isfile(program): + return False + return _execve_candidate_is_viable(program, cwd=cwd, _depth=_depth + 1) + + +def _select_fork_exec_executable(executable_list, cwd=None): + """ + The entry of fork_exec's executable list that will actually run: + fork_exec tries each entry in order until an execve succeeds, so + this is the first viable entry (relative entries resolve against + the child's working directory). When no entry is viable, the first + existing entry is returned so the launch fails as it would have + without patching. + """ + first_existing = None + for candidate in executable_list: + candidate_path = candidate + if cwd is not None and not os.path.isabs(os.fsdecode(candidate)): + candidate_path = os.path.join(os.fsdecode(cwd), os.fsdecode(candidate)) + if not os.path.isfile(candidate_path): + continue + if first_existing is None: + first_existing = candidate + if _execve_candidate_is_viable(candidate_path, cwd=cwd): + return candidate + return first_existing + + +def _patch_fork_exec_args(args, other_args): + """ + Shared patching for the fork_exec hooks: select the executable + that will actually run from the executable list and patch the + launch based on it, replacing the list with the program to launch + through when the selection is a python shebang script. + """ + env_list = other_args[4] if len(other_args) > 4 else None + cwd = other_args[3] if len(other_args) > 3 else None + actual_executable = None + if other_args: + actual_executable = _select_fork_exec_executable(other_args[0], cwd=cwd) + # The selected entry is a literal path (the list is already the + # result of the caller's PATH expansion): it must not be searched + # through PATH again, which could select a different file. + args, executable = _patch_args_for_launch( + actual_executable, args, env=env_list, cwd=cwd, search_path=False + ) + if executable is not None and other_args: + if other_args[0] and isinstance(other_args[0][0], bytes) != isinstance(executable, bytes): + executable = _get_str_type_compatible(other_args[0][0], executable) + other_args = ((executable,),) + other_args[1:] + return args, other_args + + def create_fork_exec(original_name): """ _posixsubprocess.fork_exec(args, executable_list, close_fds, ... (13 more)) @@ -1184,31 +1690,7 @@ def new_fork_exec(args, *other_args): import _posixsubprocess # @UnresolvedImport if _get_apply_arg_patching(): - # The first existing entry in the executable list is the - # program that will actually run (relative entries resolve - # against the child's working directory). - env_list = other_args[4] if len(other_args) > 4 else None - cwd = other_args[3] if len(other_args) > 3 else None - actual_executable = None - if other_args: - for candidate in other_args[0]: - candidate_path = candidate - if cwd is not None and not os.path.isabs(os.fsdecode(candidate)): - candidate_path = os.path.join( - os.fsdecode(cwd), os.fsdecode(candidate) - ) - if os.path.isfile(candidate_path): - actual_executable = candidate - break - args, executable = _patch_args_for_launch( - actual_executable, args, env=env_list, cwd=cwd - ) - if executable is not None and other_args: - if other_args[0] and isinstance(other_args[0][0], bytes) != isinstance( - executable, bytes - ): - executable = _get_str_type_compatible(other_args[0][0], executable) - other_args = ((executable,),) + other_args[1:] + args, other_args = _patch_fork_exec_args(args, other_args) send_process_created_message() return getattr(_posixsubprocess, original_name)(args, *other_args) @@ -1242,31 +1724,7 @@ def new_fork_exec(args, *other_args): import subprocess if _get_apply_arg_patching(): - # The first existing entry in the executable list is the - # program that will actually run (relative entries resolve - # against the child's working directory). - env_list = other_args[4] if len(other_args) > 4 else None - cwd = other_args[3] if len(other_args) > 3 else None - actual_executable = None - if other_args: - for candidate in other_args[0]: - candidate_path = candidate - if cwd is not None and not os.path.isabs(os.fsdecode(candidate)): - candidate_path = os.path.join( - os.fsdecode(cwd), os.fsdecode(candidate) - ) - if os.path.isfile(candidate_path): - actual_executable = candidate - break - args, executable = _patch_args_for_launch( - actual_executable, args, env=env_list, cwd=cwd - ) - if executable is not None and other_args: - if other_args[0] and isinstance(other_args[0][0], bytes) != isinstance( - executable, bytes - ): - executable = _get_str_type_compatible(other_args[0][0], executable) - other_args = ((executable,),) + other_args[1:] + args, other_args = _patch_fork_exec_args(args, other_args) send_process_created_message() return getattr(subprocess, original_name)(args, *other_args) diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py index 7f0d08721..c31a40aef 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py @@ -919,17 +919,21 @@ def test_shebang_launch_relative_child_cwd(tmp_path, monkeypatch) -> None: sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_shebang_launch_child_cwd_interpreter(tmp_path) -> None: - # A relative PATH entry in the child's environment is resolved - # against the child's working directory when picking the - # interpreter, so a child-local python3 wins over the system one. + # The interpreter lookup for an env shebang is left to env at exec + # time: a relative PATH entry in the child's environment is then + # resolved against the child's working directory by env itself, so + # a child-local python3 wins over the system one without the + # debugger resolving it first. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} child_dir = tmp_path / "child" child_dir.mkdir() child_script = child_dir / "child_script" child_script.write_text("#!/usr/bin/env python3\nprint('child')\n") child_script.chmod(0o755) + import shutil + fake_python = child_dir / "python3" - fake_python.write_text("#!/bin/sh\n") + shutil.copy(shutil.which("true"), fake_python) fake_python.chmod(0o755) new_args, executable = pydev_monkey._patch_args_for_launch( @@ -938,8 +942,8 @@ def test_shebang_launch_child_cwd_interpreter(tmp_path) -> None: env={"PATH": "." + os.pathsep + "/usr/bin" + os.pathsep + "/bin"}, cwd=str(child_dir), ) - assert executable == str(fake_python) - assert new_args[0] == "python3" + assert executable == "/usr/bin/env" + assert new_args[:2] == ["/usr/bin/env", "python3"] @pytest.mark.skipif( @@ -1011,7 +1015,7 @@ def test_shebang_launch_no_path_search(tmp_path, monkeypatch) -> None: new_args, executable = pydev_monkey._patch_args_for_launch( "child_script", original_args[:], search_path=True ) - assert executable == shutil.which("python3") + assert executable == shutil.which("env") assert new_args != original_args @@ -1130,7 +1134,8 @@ def test_shebang_launch_child_path_only(tmp_path, monkeypatch) -> None: new_args, executable = pydev_monkey._patch_args_for_launch( str(script), ["child_script", "hello"], env=child_env ) - assert executable == shutil.which("python3") + assert executable == shutil.which("env") + assert new_args[:2] == [shutil.which("env"), "python3"] assert new_args[new_args.index("--file") + 1] == str(script) @@ -1140,6 +1145,7 @@ def test_get_env_path_environ(monkeypatch) -> None: monkeypatch.setenv("PATH", "/some/bin" + os.pathsep + "/usr/bin") assert pydev_monkey._get_env_path(os.environ) == "/some/bin" + os.pathsep + "/usr/bin" assert pydev_monkey._get_env_path({"PATH": "/a"}) == "/a" + assert pydev_monkey._get_env_path({b"PATH": b"/b"}) == "/b" assert pydev_monkey._get_env_path([b"PATH=/b", b"OTHER=1"]) == "/b" assert pydev_monkey._get_env_path({}) == os.defpath assert pydev_monkey._get_env_path(None) is None @@ -1163,9 +1169,9 @@ def test_get_env_path_environ_key_types(monkeypatch) -> None: def test_shebang_launch_spawnp_parent_path(tmp_path, monkeypatch) -> None: # posix_spawnp resolves the file through this process's PATH, not # the child environment's: a script only present in the child PATH - # must not be selected (the native launch fails), while the child - # PATH still resolves the env-shebang interpreter once the script - # itself is found. + # must not be selected (the native launch fails). Once the script + # itself is found, the env program performs the interpreter lookup + # in the child environment at exec time. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} bin_dir = tmp_path / "bin" bin_dir.mkdir() @@ -1184,7 +1190,7 @@ def test_shebang_launch_spawnp_parent_path(tmp_path, monkeypatch) -> None: new_args, executable = pydev_monkey._patch_args_for_launch( "child_script", original_args[:], env=child_env, search_path=True, file_env=None ) - assert executable == pydev_monkey._which("python3", path=child_env["PATH"]) + assert executable == "/usr/bin/env" assert new_args[new_args.index("--file") + 1] == str(script) @@ -1202,11 +1208,12 @@ def test_shebang_executable(tmp_path) -> None: original_args: list[str] = [str(script), "bar"] new_args = pydev_monkey.patch_args(original_args[:]) assert new_args != original_args - # The interpreter is a bare name in the shebang, so the executable to - # launch must be resolved through PATH. + # The interpreter is a bare name in an env shebang, so the + # executable to launch is the env program, which resolves the + # interpreter through PATH when it runs. assert pydev_monkey._get_shebang_executable( str(script), original_args, new_args - ) == shutil.which("python3") + ) == shutil.which("env") # Unchanged args mean no executable replacement. assert ( pydev_monkey._get_shebang_executable(str(script), original_args, original_args) @@ -1237,13 +1244,859 @@ def test_shebang_executable_child_env(tmp_path) -> None: new_args = pydev_monkey.patch_args(original_args[:]) assert new_args != original_args - # The interpreter is resolved through the child's PATH, not ours. + # The executable to launch is the env program regardless of the + # child's PATH: env resolves the interpreter (here the child-local + # fake python) when it runs. assert pydev_monkey._get_shebang_executable( str(script), original_args, new_args, env={"PATH": str(bin_dir)} - ) == str(fake_python) + ) == "/usr/bin/env" - # When the interpreter cannot be resolved in the child's environment, - # the launch is preserved unchanged. - assert pydev_monkey._patch_args_for_launch( + # When the interpreter cannot be resolved in the child's + # environment, the launch still goes through env, which fails to + # find it exactly as the unpatched launch would. + new_args, executable = pydev_monkey._patch_args_for_launch( str(script), original_args[:], env={"PATH": "/nonexistent"} + ) + assert executable == "/usr/bin/env" + assert new_args[:2] == ["/usr/bin/env", "python3"] + assert new_args[new_args.index("--file") + 1] == str(script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_executable_mismatch_args(tmp_path) -> None: + # Shebang detection uses the executable actually selected for the + # launch, not args[0]: with a custom argv[0], or with args[0] + # naming a python executable, a launch of a python shebang script + # through its executable is still patched, based on the script. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + for argv0 in ("custom_name", "python3"): + new_args, executable = pydev_monkey._patch_args_for_launch( + str(script), [argv0, "hello"] + ) + assert executable == "/usr/bin/env" + assert new_args[:2] == ["/usr/bin/env", "python3"] + assert new_args[new_args.index("--file") + 1] == str(script) + assert new_args[-1] == "hello" + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_execve_executable_mismatch(tmp_path) -> None: + # End to end through os.execve, where the executable and argv[0] + # legitimately differ: the script named by the executable is the + # one that must be attached. + import subprocess + + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('CHILD RAN')\n") + script.chmod(0o755) + + pydevd_dir = os.path.dirname(os.path.dirname(pydev_monkey.__file__)) + harness = tmp_path / "harness.py" + harness.write_text( + "import os, sys\n" + "sys.path.insert(0, %r)\n" + "from _pydev_bundle import pydev_monkey\n" + "from pydevd import SetupHolder\n" + "SetupHolder.setup = {'client': '127.0.0.1', 'port': '0', 'multiprocess': True}\n" + "pydev_monkey.patch_new_process_functions()\n" + "os.execve(%r, ['custom_name', 'hello'], os.environ)\n" % (pydevd_dir, str(script)) + ) + out = subprocess.run( + [sys.executable, str(harness)], capture_output=True, text=True, timeout=60 + ) + assert "CHILD RAN" not in out.stdout + assert "CHILD RAN" not in out.stderr + assert "pydevd" in out.stdout + out.stderr + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_skips_script_with_missing_shebang_interpreter(tmp_path) -> None: + # fork_exec tries the executable list entries in order until one + # execve succeeds: a script whose shebang interpreter does not + # exist fails and is skipped in favor of a later entry, so the + # later entry is the one the patching must be based on. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + bad_dir = tmp_path / "bad" + bad_dir.mkdir() + bad_script = bad_dir / "child_script" + bad_script.write_text("#!/nonexistent/python3\nprint('bad')\n") + bad_script.chmod(0o755) + + good_dir = tmp_path / "good" + good_dir.mkdir() + good_script = good_dir / "child_script" + good_script.write_text("#!/usr/bin/env python3\nprint('good')\n") + good_script.chmod(0o755) + + assert pydev_monkey._select_fork_exec_executable( + [str(bad_script), str(good_script)] + ) == str(good_script) + # With no viable entry, the first existing entry is kept so the + # launch fails as it would have without patching. + assert pydev_monkey._select_fork_exec_executable([str(bad_script)]) == str(bad_script) + + other_args = ((str(bad_script), str(good_script)), True, (), None, None) + new_args, new_other_args = pydev_monkey._patch_fork_exec_args( + ["child_script", "hello"], other_args + ) + assert new_other_args[0] == ("/usr/bin/env",) + assert new_args[:2] == ["/usr/bin/env", "python3"] + assert new_args[new_args.index("--file") + 1] == str(good_script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_fallback_through_subprocess(tmp_path) -> None: + # End to end through subprocess: the executable list CPython builds + # from PATH starts with a script whose shebang interpreter is + # missing, and the working script behind it is the one that runs + # (and must be attached). + import subprocess + + bad_dir = tmp_path / "bad" + bad_dir.mkdir() + bad_script = bad_dir / "child_script" + bad_script.write_text("#!/nonexistent/python3\nprint('BAD RAN')\n") + bad_script.chmod(0o755) + + good_dir = tmp_path / "good" + good_dir.mkdir() + good_script = good_dir / "child_script" + good_script.write_text("#!/usr/bin/env python3\nprint('CHILD RAN')\n") + good_script.chmod(0o755) + + pydevd_dir = os.path.dirname(os.path.dirname(pydev_monkey.__file__)) + harness = tmp_path / "harness.py" + harness.write_text( + "import os, subprocess, sys\n" + "sys.path.insert(0, %r)\n" + "from _pydev_bundle import pydev_monkey\n" + "from pydevd import SetupHolder\n" + "SetupHolder.setup = {'client': '127.0.0.1', 'port': '0', 'multiprocess': True}\n" + "pydev_monkey.patch_new_process_functions()\n" + "env = dict(os.environ)\n" + "env['PATH'] = %r\n" + "out = subprocess.run(['child_script', 'hello'], executable='child_script', env=env, capture_output=True, text=True, timeout=60)\n" + "print('STDOUT:', out.stdout)\n" + "print('STDERR:', out.stderr)\n" + % ( + pydevd_dir, + str(bad_dir) + os.pathsep + str(good_dir) + os.pathsep + "/usr/bin" + os.pathsep + "/bin", + ) + ) + out = subprocess.run( + [sys.executable, str(harness)], capture_output=True, text=True, timeout=60 + ) + assert "CHILD RAN" not in out.stdout + assert "BAD RAN" not in out.stdout + assert "pydevd" in out.stdout + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_crlf_shebang_candidate_viability(tmp_path) -> None: + # A CRLF env shebang still execs env successfully (the carriage + # return lands in env's argument), so fork_exec stops there: the + # entry is viable even though it cannot be patched. A CRLF direct + # shebang puts the carriage return in the interpreter pathname + # itself, so that exec fails and the next entry is tried. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + crlf_env = tmp_path / "crlf_env_script" + crlf_env.write_bytes(b"#!/usr/bin/env python3\r\nprint('hello')\r\n") + crlf_env.chmod(0o755) + crlf_direct = tmp_path / "crlf_direct_script" + crlf_direct.write_bytes(b"#!/usr/bin/python3\r\nprint('hello')\r\n") + crlf_direct.chmod(0o755) + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('hello')\n") + good.chmod(0o755) + + assert pydev_monkey._select_fork_exec_executable( + [str(crlf_env), str(good)] + ) == str(crlf_env) + assert pydev_monkey._select_fork_exec_executable( + [str(crlf_direct), str(good)] + ) == str(good) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_executable_mismatch_relative_cwd(tmp_path, monkeypatch) -> None: + # The executable-based patching must apply a relative child cwd + # once: the script is found in the child's bin directory, not in a + # doubly-nested namesake. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + child_dir = tmp_path / "child" + bin_dir = child_dir / "bin" + bin_dir.mkdir(parents=True) + script = bin_dir / "task" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + monkeypatch.chdir(tmp_path) + new_args, executable = pydev_monkey._patch_args_for_launch( + "bin/task", ["custom_name", "hello"], cwd="child" + ) + assert executable == "/usr/bin/env" + assert new_args[new_args.index("--file") + 1] == str(script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_executable_mismatch_non_utf8_bytes(tmp_path) -> None: + # A script path that is not valid UTF-8 must not make the launch + # hooks raise: patch_args cannot represent such a path, so the + # original launch is preserved unchanged instead. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = os.fsencode(tmp_path) + b"/child_\xffscript" + with open(script, "wb") as stream: + stream.write(b"#!/usr/bin/env python3\nprint('hello')\n") + os.chmod(script, 0o755) + + original_args = [b"custom_name", b"hello"] + assert pydev_monkey._patch_args_for_launch(script, original_args[:]) == ( + original_args, + None, + ) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_with_nested_broken_shebang(tmp_path) -> None: + # Viability recurses through nested shebangs as the kernel does: + # a script whose interpreter is itself a script with a missing + # interpreter fails to exec and is skipped. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + wrapper = tmp_path / "wrapper_python" + wrapper.write_text("#!/nonexistent/python3\nprint('wrapper')\n") + wrapper.chmod(0o755) + bad = tmp_path / "bad_script" + bad.write_text("#!%s\nprint('bad')\n" % wrapper) + bad.chmod(0o755) + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + assert pydev_monkey._select_fork_exec_executable([str(bad), str(good)]) == str(good) + # A working nested shebang stays viable. + wrapper.write_text("#!/usr/bin/env python3\nprint('wrapper')\n") + assert pydev_monkey._select_fork_exec_executable([str(bad), str(good)]) == str(bad) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_non_utf8_shebang_program(tmp_path) -> None: + # A shebang program whose path is not valid UTF-8 is still the + # program the kernel would run: the entry is viable and must not + # be skipped for a later one. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + program = os.fsencode(tmp_path) + b"/env_\xff" + with open(program, "wb") as stream: + stream.write(b"#!/bin/sh\n") + os.chmod(program, 0o755) + script = tmp_path / "child_script" + script.write_bytes(b"#" + b"!" + program + b" python3\nprint('hello')\n") + script.chmod(0o755) + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + assert pydev_monkey._select_fork_exec_executable([str(script), str(good)]) == str(script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_selected_bare_candidate_is_literal(tmp_path, monkeypatch) -> None: + # The selected executable list entry is a literal path, already + # PATH-expanded by the caller: patching must not search PATH again + # and land on a different (broken) namesake. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + bad_dir = tmp_path / "bad" + bad_dir.mkdir() + bad_script = bad_dir / "task" + bad_script.write_text("#!/nonexistent/python3\nprint('bad')\n") + bad_script.chmod(0o755) + good_script = tmp_path / "task" + good_script.write_text("#!/usr/bin/env python3\nprint('good')\n") + good_script.chmod(0o755) + + monkeypatch.chdir(tmp_path) + env_list = ["PATH=" + str(bad_dir) + os.pathsep + "/usr/bin" + os.pathsep + "/bin"] + other_args = ((str(bad_script), "task"), True, (), str(tmp_path), env_list) + new_args, new_other_args = pydev_monkey._patch_fork_exec_args(["task", "hello"], other_args) + assert new_other_args[0] == ("/usr/bin/env",) + assert new_args[new_args.index("--file") + 1] == str(good_script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_executable_mismatch_python_named_script(tmp_path) -> None: + # A script whose name contains "python" must not be mistaken for + # an interpreter when the launch is patched from the selected + # executable: the script stays the --file target. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "python-task" + script.write_text("#!/usr/bin/python3\nprint('hello')\n") + script.chmod(0o755) + + new_args, executable = pydev_monkey._patch_args_for_launch( + str(script), ["custom_name", "hello"] + ) + assert executable == "/usr/bin/python3" + assert new_args[new_args.index("--file") + 1] == str(script) + assert new_args[-1] == "hello" + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_text_file_without_shebang(tmp_path, monkeypatch) -> None: + # An executable text file without a shebang fails with ENOEXEC, + # so fork_exec moves on: it is not a viable candidate, and neither + # is a malformed ELF header, while a real binary for this host is. + import shutil + + monkeypatch.setattr(pydev_monkey, "_binfmt_misc_has_handlers", lambda: False) + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + text_file = tmp_path / "text_candidate" + text_file.write_text("echo hello\n") + text_file.chmod(0o755) + fake_elf = tmp_path / "fake_elf_candidate" + fake_elf.write_bytes(b"\x7fELF\x02\x01\x01\x00" + b"\x00" * 64) + fake_elf.chmod(0o755) + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + assert pydev_monkey._select_fork_exec_executable([str(text_file), str(good)]) == str(good) + assert pydev_monkey._select_fork_exec_executable([str(fake_elf), str(good)]) == str(good) + true_binary = shutil.which("true") + if true_binary is not None: + binary_file = tmp_path / "binary_candidate" + shutil.copy(true_binary, binary_file) + binary_file.chmod(0o755) + assert pydev_monkey._select_fork_exec_executable( + [str(binary_file), str(good)] + ) == str(binary_file) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_python_named_script(tmp_path) -> None: + # A script whose name contains "python" is still a script when it + # has a python shebang: patch_args must keep it as the --file + # target instead of mistaking it for an interpreter. + from _pydevd_bundle.pydevd_command_line_handling import get_pydevd_file + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "python-task" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + assert pydev_monkey.patch_args([str(script), "bar"]) == [ + "python3", + get_pydevd_file(), + "--port", + "0", + "--ppid", + str(os.getpid()), + "--client", + "127.0.0.1", + "--multiprocess", + "--protocol-quoted-line", + "--file", + str(script), + "bar", + ] + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_malformed_native_elf(tmp_path) -> None: + # A header with this host's machine type but no executable type + # and no program headers is conclusively not executable, and a + # 32-bit x86 header is conclusively not a failure on x86_64 (the + # host runs compatibility binaries): viability follows the ELF + # header, not just the magic. + import platform + import struct + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + malformed = tmp_path / "malformed_candidate" + header = bytearray(64) + header[:4] = b"\x7fELF" + header[4] = 2 + header[5] = 1 + struct.pack_into(" None: + # A relative PT_INTERP loader is resolved against the child's + # working directory, like the kernel does in the fork_exec child: + # the same binary is viable from "/" and not from elsewhere. + import shutil + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + true_binary = shutil.which("true") + if true_binary is None: + pytest.skip("no true binary available") + data = open(true_binary, "rb").read() + absolute_interp = b"/lib64/ld-linux-x86-64.so.2\x00" + if absolute_interp not in data: + pytest.skip("unexpected loader path in true binary") + relative_interp = b"lib64/ld-linux-x86-64.so.2\x00\x00" + binary_file = tmp_path / "binary_candidate" + binary_file.write_bytes(data.replace(absolute_interp, relative_interp)) + binary_file.chmod(0o755) + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + assert pydev_monkey._select_fork_exec_executable( + [str(binary_file), str(good)], cwd="/" + ) == str(binary_file) + assert pydev_monkey._select_fork_exec_executable( + [str(binary_file), str(good)], cwd="/nonexistent" + ) == str(good) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_non_executable_elf_loader(tmp_path) -> None: + # A PT_INTERP loader that exists but is not executable makes the + # exec fail with EACCES, so the entry is not viable either. + import platform + import struct + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + loader = tmp_path / "fake_loader" + loader.write_bytes(b"\x7fELF\x02\x01\x01\x00" + b"\x00" * 64) + loader.chmod(0o644) + interp = os.fsencode(loader) + b"\x00" + header = bytearray(64) + header[:4] = b"\x7fELF" + header[4] = 2 + header[5] = 1 + struct.pack_into(" None: + # A loader whose ELF header is truncated (valid magic, class, + # type and machine, but shorter than a full header) cannot be + # loaded: the entry pointing at it is not viable. + import platform + import struct + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + loader = tmp_path / "truncated_loader" + loader_header = bytearray(20) + loader_header[:4] = b"\x7fELF" + loader_header[4] = 2 + loader_header[5] = 1 + struct.pack_into(" None: + # The kernel requires the program header entry size to be exact: + # an oversized e_phentsize is an ENOEXEC, not a viable binary. + import shutil + import struct + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + true_binary = shutil.which("true") + if true_binary is None: + pytest.skip("no true binary available") + data = bytearray(open(true_binary, "rb").read()) + if len(data) < 56 or data[:4] != b"\x7fELF" or data[4] != 2: + pytest.skip("unexpected true binary format") + struct.pack_into(" None: + # The kernel rejects ELF program header tables over 64 KiB: such + # a binary is not a viable candidate even when the file is large + # enough to hold the table it declares. + import platform + import struct + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + header = bytearray(64) + header[:4] = b"\x7fELF" + header[4] = 2 + header[5] = 1 + struct.pack_into(" None: + # A shebang line beyond the kernel's 256-byte buffer cannot be + # launched as a script at all: the args are left unchanged and + # the entry is not a viable fork_exec candidate. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text( + "#!" + "/" * pydev_monkey._SHEBANG_WINDOW + "usr/bin/python3\nprint('hello')\n" + ) + script.chmod(0o755) + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + assert pydev_monkey._select_fork_exec_executable([str(script), str(good)]) == str(good) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_shebang_long_argument(tmp_path) -> None: + # A shebang whose optional argument runs past the kernel's + # buffer is truncated by the kernel, not rejected: the entry is + # viable (unlike a pathname that is itself unterminated there, + # covered by test_monkey_patch_args_shebang_line_too_long). + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "long_arg_script" + script.write_text("#!/bin/true " + "x" * 300 + "\n") + script.chmod(0o755) + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + assert pydev_monkey._select_fork_exec_executable([str(script), str(good)]) == str(script) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_shebang_window_edges(tmp_path) -> None: + # The kernel's shebang window is 256 bytes and a NUL terminates + # the interpreter pathname: a pathname ending at the last window + # byte, or at a NUL, still launches. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + good = tmp_path / "good_script" + good.write_text("#!/usr/bin/env python3\nprint('good')\n") + good.chmod(0o755) + + edge = tmp_path / "edge_script" + edge.write_bytes(b"#!" + b"/" * 245 + b"bin/true\n") + edge.chmod(0o755) + assert pydev_monkey._select_fork_exec_executable([str(edge), str(good)]) == str(edge) + + nul = tmp_path / "nul_script" + nul.write_bytes(b"#!/bin/true\x00ignored\n") + nul.chmod(0o755) + assert pydev_monkey._select_fork_exec_executable([str(nul), str(good)]) == str(nul) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_candidate_foreign_elf_binfmt(tmp_path, monkeypatch) -> None: + # A foreign-architecture ELF is conclusively unexecutable only + # when no binfmt_misc handler (i.e.: qemu) is registered for it: + # with a handler present, the entry stays viable. + import platform + import shutil + import struct + + if platform.machine() != "x86_64" or sys.platform != "linux": + pytest.skip("test is written for an x86_64 Linux host") + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + true_binary = shutil.which("true") + if true_binary is None: + pytest.skip("no true binary available") + data = bytearray(open(true_binary, "rb").read()) + if len(data) < 20 or data[:4] != b"\x7fELF": + pytest.skip("unexpected true binary format") + struct.pack_into(" None: + # When the selected script's interpreter is itself a script, the + # rewrite would retarget to the interpreter script while the + # launch executable stayed the interpreter: such nested launches + # are left unchanged instead of being mismatched. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + wrapper = tmp_path / "python-wrapper" + wrapper.write_text("#!/usr/bin/python3\nprint('wrapper')\n") + wrapper.chmod(0o755) + script = tmp_path / "child_script" + script.write_text("#!%s\nprint('hello')\n" % wrapper) + script.chmod(0o755) + + for argv0 in ("custom_name", "python3", str(script)): + original_args: list[str] = [argv0, "hello"] + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:] + ) == (original_args, None) + + # The same holds when the interpreter script is not itself a + # python script. + wrapper.write_text("#!/bin/sh\necho wrapper\n") + for argv0 in ("custom_name", "python3", str(script)): + original_args = [argv0, "hello"] + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:] + ) == (original_args, None) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_executable_mismatch_unsupported_shebang(tmp_path) -> None: + # A selected script with a python shebang in an unsupported form + # (quoted env -S arguments) cannot be patched safely: with a + # python-like argv[0], the launch is preserved instead of handing + # the script the debugger bootstrap arguments. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text('#!/usr/bin/env -S python3 "-O"\nprint(\'hello\')\n') + script.chmod(0o755) + + original_args: list[str] = ["python3", "hello"] + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:] + ) == (original_args, None) + + # The python name can also appear after other env options and + # assignments in the shebang. + script.write_text("#!/usr/bin/env -S -u FOO python3\nprint('hello')\n") + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:] ) == (original_args, None) + + # And it can be quoted under env -S quoting rules. + script.write_text('#!/usr/bin/env -S p"ython3" -O\nprint(\'hello\')\n') + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:] + ) == (original_args, None) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_nested_interpreter_uses_launch_env(tmp_path, monkeypatch) -> None: + # The script-interpreter check must resolve the env-shebang + # interpreter through the launch environment, not the + # file-location environment: with posix_spawn-style arguments + # (file_env=None), a python3 shell wrapper that only exists in + # the child's PATH is the interpreter env will actually run. + import shutil + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + + parent_bin = tmp_path / "parent_bin" + parent_bin.mkdir() + parent_python = parent_bin / "python3" + shutil.copy(shutil.which("true"), parent_python) + parent_python.chmod(0o755) + + child_bin = tmp_path / "child_bin" + child_bin.mkdir() + wrapper = child_bin / "python3" + wrapper.write_text("#!/bin/sh\necho wrapper\n") + wrapper.chmod(0o755) + + monkeypatch.setenv("PATH", str(parent_bin) + os.pathsep + "/usr/bin" + os.pathsep + "/bin") + child_env = {"PATH": str(child_bin) + os.pathsep + "/usr/bin" + os.pathsep + "/bin"} + + for argv0 in (str(script), "custom_name"): + original_args: list[str] = [argv0, "hello"] + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:], env=child_env, file_env=None + ) == (original_args, None) + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_shebang_launch_script_env_program(tmp_path) -> None: + # An env program that is itself a script cannot be launched + # through faithfully either: the launch is preserved. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + fake_env = bin_dir / "env" + fake_env.write_text("#!/bin/sh\nexec \"$@\"\n") + fake_env.chmod(0o755) + script = tmp_path / "child_script" + script.write_text("#!%s -S python3 -O\nprint('hello')\n" % fake_env) + script.chmod(0o755) + + shebang_info = pydev_monkey._parse_shebang(str(script)) + assert shebang_info is not None and shebang_info[3] + + for argv0 in (str(script), "custom_name"): + original_args: list[str] = [argv0, "hello"] + assert pydev_monkey._patch_args_for_launch( + str(script), original_args[:] + ) == (original_args, None) From 2837e56b05a810906312682eafd561f4ac9a5471 Mon Sep 17 00:00:00 2001 From: Teja P C <39472754+PCTEJA@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:47:46 +0000 Subject: [PATCH 3/4] Address follow-up review feedback on shebang patching --- .../pydevd/_pydev_bundle/pydev_monkey.py | 357 ++++------- .../pydevd/tests_python/test_pydev_monkey.py | 575 +++++------------- 2 files changed, 263 insertions(+), 669 deletions(-) diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py index d9d2d6dea..2d6ce5fd4 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py @@ -3,10 +3,8 @@ from _thread import _local import os -import platform import re import shutil -import struct import sys from typing import Generator from _pydev_bundle._pydev_saved_modules import threading @@ -327,6 +325,37 @@ def _which(command, path=None, cwd=None): return None +def _binfmt_misc_has_handlers(): + try: + entries = os.listdir("/proc/sys/fs/binfmt_misc") + except Exception: + return False + return any(entry not in ("register", "status") for entry in entries) + + +def _shebang_program_is_launchable(path): + """ + Whether the file at path is in a format the kernel can execute + at all: a script (a #! line, whose own launch the caller checks + separately) or a native binary (an ELF or Mach-O magic). A plain + file in neither format fails with ENOEXEC, unless a binfmt_misc + handler is registered that could run it (i.e.: Wine for a PE + binary), which cannot be ruled out from the magic alone. A file + that cannot be read here (i.e.: an execute-only binary) is + treated as launchable, since its format cannot be determined. + """ + try: + with open(path, "rb") as stream: + magic = stream.read(4) + except Exception: + return True + if magic.startswith( + (b"#!", b"\x7fELF", b"\xfe\xed\xfa", b"\xce\xfa\xed", b"\xcf\xfa\xed", b"\xca\xfe\xba\xbe", b"\xca\xfe\xba\xbf") + ): + return True + return _binfmt_misc_has_handlers() + + def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, str] | None: """ :return: @@ -383,16 +412,29 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, if not first_line.startswith(b"#!"): return None - first_line = first_line.strip() - line = first_line[2:].decode("utf-8", "ignore").strip() + # Parse at the byte level, following the kernel: the shebang ends + # at the first newline or NUL, and blanks (space and tab) are the + # only separators. Any other byte stays part of the interpreter + # pathname or of the argument: a vertical tab or form feed is not + # a separator, and bytes that are not valid UTF-8 in the pathname + # make it a name that cannot be launched. Neither may be + # normalized into a valid python launch here. + line = first_line[2:].split(b"\n", 1)[0].split(b"\x00", 1)[0].strip(b" \t") if not line: return None - parts = line.split(None, 1) - interpreter = parts[0] + blank = len(line) + for sep in (b" ", b"\t"): + i = line.find(sep) + if i != -1: + blank = min(blank, i) + try: + interpreter = line[:blank].decode("utf-8") + rest = line[blank:].strip(b" \t").decode("utf-8") + except UnicodeDecodeError: + return None program = interpreter - rest = parts[1] if len(parts) > 1 else "" via_env = False program_path = interpreter @@ -403,6 +445,12 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, # (i.e.: #!/nonexistent/env python3): preserve the native # launch failure instead of rewriting it into a working one. return None + if not _shebang_program_is_launchable(program_path): + # The program is not in an executable format at all (i.e.: a + # plain text file without a shebang of its own): its exec + # fails with ENOEXEC, so preserve the native launch instead + # of rewriting it into one that cannot run either. + return None if os.path.basename(interpreter) == "env": via_env = True @@ -413,11 +461,21 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, # handled. if '"' in rest or "'" in rest or "\\" in rest or "$" in rest: return None - args = rest.split() - split_args = False - if args and args[0] == "-S": - split_args = True - args = args[1:] + # Without -S, env receives the rest as a single argument: it + # is split here on blanks (space and tab) only, like the + # kernel, and other whitespace stays part of a token (i.e.: a + # vertical tab used as a separator makes it one long name for + # env, not separate arguments, so such launches are left + # unchanged). env -S instead re-splits the argument it + # receives with its own rules, which treat all ASCII + # whitespace as a separator. + split_args = rest.startswith("-S") and (len(rest) == 2 or rest[2] in " \t\x0b\x0c") + if split_args: + args = [token for token in re.split("[ \t\x0b\x0c]+", rest[2:]) if token] + else: + args = [token for token in rest.replace("\t", " ").split(" ") if token] + if any(any(ch.isspace() for ch in token) for token in args): + return None if not args or args[0].startswith("-") or "=" in args[0]: return None interpreter = args[0] @@ -1409,271 +1467,64 @@ def new_posix_spawn(executable, args, env, **kwargs): _SHEBANG_WINDOW = 512 if sys.platform == "darwin" else 256 -def _binfmt_misc_has_handlers(): - try: - entries = os.listdir("/proc/sys/fs/binfmt_misc") - except Exception: - return False - return any(entry not in ("register", "status") for entry in entries) - - -def _elf_candidate_is_viable(chunk, stream, size=None, cwd=None, check_interp=True): - """ - Whether an ELF file can be executed on this host. Only conclusive - failures count: a malformed header (bad class or data encoding, a - non-executable type, a missing or truncated program header table, - no loadable segment), a machine type this host cannot run - (compatibility types such as 32-bit x86 on x86_64 do run), or a - PT_INTERP loader that does not exist. Anything that cannot be - determined from the header is treated as viable. - """ - if len(chunk) < 20: - return False - ei_class, ei_data = chunk[4], chunk[5] - if ei_class not in (1, 2) or ei_data not in (1, 2): - return False - if len(chunk) < (64 if ei_class == 2 else 52): - # The probe reads up to 8192 bytes, so a shorter chunk is the - # whole file: its ELF header is conclusively truncated. - return False - endian = "<" if ei_data == 1 else ">" - if struct.unpack(endian + "H", chunk[16:18])[0] not in (2, 3): # ET_EXEC, ET_DYN - return False - machine = struct.unpack(endian + "H", chunk[18:20])[0] - host_machines = { - "x86_64": (62, 3), - "AMD64": (62, 3), - "aarch64": (183, 40), - "arm64": (183, 40), - "armv7l": (40,), - "i386": (3,), - "i686": (3,), - "riscv64": (243,), - "ppc64le": (21,), - "s390x": (22,), - "loongarch64": (258,), - } - host_machine = host_machines.get(platform.machine()) - if host_machine is not None and machine not in host_machine: - # A foreign machine type is only conclusively unexecutable - # when no binfmt_misc handler (i.e.: qemu) is registered to - # run it: with one, support cannot be ruled out here. - return _binfmt_misc_has_handlers() - try: - if ei_class == 2: - phoff = struct.unpack(endian + "Q", chunk[32:40])[0] - phentsize = struct.unpack(endian + "H", chunk[54:56])[0] - phnum = struct.unpack(endian + "H", chunk[56:58])[0] - phentsize_expected = 56 - offset_at = 8 - filesz_at = 32 - offset_fmt = endian + "Q" - else: - phoff = struct.unpack(endian + "I", chunk[28:32])[0] - phentsize = struct.unpack(endian + "H", chunk[42:44])[0] - phnum = struct.unpack(endian + "H", chunk[44:46])[0] - phentsize_expected = 32 - offset_at = 4 - filesz_at = 16 - offset_fmt = endian + "I" - if phnum == 0 or phentsize != phentsize_expected: - return False - if phnum == 0xFFFF: - # Extended program header numbering: the real count is in - # the section header table, which is not probed here. - return True - if phnum * phentsize > 65536: - # The kernel rejects larger program header tables. - return False - if size is not None and phoff + phnum * phentsize > size: - return False - found_load = False - for i in range(min(phnum, 64)): - entry_at = phoff + i * phentsize - if entry_at + phentsize <= len(chunk): - entry = chunk[entry_at : entry_at + phentsize] - else: - stream.seek(entry_at) - entry = stream.read(phentsize) - if len(entry) < filesz_at + struct.calcsize(offset_fmt): - return True - p_type = struct.unpack(endian + "I", entry[:4])[0] - if p_type == 1: # PT_LOAD - found_load = True - elif p_type == 3 and check_interp: # PT_INTERP - interp_at = struct.unpack(offset_fmt, entry[offset_at : offset_at + struct.calcsize(offset_fmt)])[0] - filesz = struct.unpack(offset_fmt, entry[filesz_at : filesz_at + struct.calcsize(offset_fmt)])[0] - stream.seek(interp_at) - raw_interp = stream.read(filesz if 0 < filesz <= 65536 else 512) - if b"\x00" not in raw_interp: - # The pathname could not be read in full: not a - # conclusive failure. - return True - interp = os.fsdecode(raw_interp.split(b"\x00", 1)[0]) - if not interp: - return True - if not os.path.isabs(interp): - base = os.fsdecode(cwd) if cwd is not None else os.getcwd() - interp = os.path.join(base, interp) - if not (os.path.isfile(interp) and os.access(interp, os.X_OK)): - return False - if not _loader_candidate_is_viable(interp): - return False - if phnum <= 64 and not found_load: - return False - return True - except Exception: - return True - - -def _loader_candidate_is_viable(path): - """ - Whether the PT_INTERP loader itself can be loaded: it must be a - binary in a format this platform executes (a script loader fails), - with a conclusively valid header. Its own PT_INTERP, if any, is - not honored by the kernel and is not checked. A loader that - cannot be read here is not a conclusive failure. - """ - try: - with open(path, "rb") as stream: - chunk = stream.read(8192) - if chunk.startswith(b"#!"): - return False - if sys.platform == "darwin": - return _binary_candidate_is_viable(chunk, stream) - if not chunk.startswith(b"\x7fELF"): - return False - try: - size = os.fstat(stream.fileno()).st_size - except Exception: - size = None - return _elf_candidate_is_viable(chunk, stream, size=size, check_interp=False) - except Exception: - return True - - -def _binary_candidate_is_viable(chunk, stream, cwd=None): - """ - Whether a file without a shebang is in a binary format this - platform's kernel executes: a plain text file fails with ENOEXEC, - and so does a binary for a different platform. - """ - if sys.platform == "darwin": - return chunk.startswith((b"\xfe\xed\xfa", b"\xce\xfa\xed", b"\xcf\xfa\xed", b"\xca\xfe\xba\xbe")) - if chunk.startswith(b"\x7fELF"): - try: - size = os.fstat(stream.fileno()).st_size - except Exception: - size = None - return _elf_candidate_is_viable(chunk, stream, size=size, cwd=cwd) - # Not a natively executable format: conclusively unexecutable - # only when no binfmt_misc handler (i.e.: Wine for PE binaries) - # is registered that could run it. - return _binfmt_misc_has_handlers() - - -def _execve_candidate_is_viable(candidate_path, cwd=None, _depth=0): - """ - Whether an execve of this file can succeed at all, which is what - makes fork_exec move on to the next entry in the executable list. - A file that is not executable fails, and so does a script whose - shebang program cannot itself be executed (the kernel reports the - missing interpreter as the exec failure, recursing through nested - shebangs) and a text file without a shebang (ENOEXEC). A file that - cannot be read here (an execute-only binary still runs) is treated - as viable: its execve succeeds, even if the program it launches - then fails on its own. - """ - if not os.access(candidate_path, os.X_OK): - return False - try: - with open(candidate_path, "rb") as stream: - chunk = stream.read(8192) - if not chunk.startswith(b"#!"): - return _binary_candidate_is_viable(chunk, stream, cwd=cwd) - # The kernel parses the shebang from a fixed-size window - # (512 bytes on macOS, 256 elsewhere): a long optional - # argument is truncated, but an interpreter pathname that - # is not terminated within the window (by a blank, a - # newline, or a NUL) cannot be launched at all. - window = chunk[:_SHEBANG_WINDOW] - first_line = window.split(b"\n", 1)[0].split(b"\x00", 1)[0] - body = first_line[2:].lstrip(b" \t") - if ( - len(window) == _SHEBANG_WINDOW - and b"\n" not in window - and b"\x00" not in window - and b" " not in body - and b"\t" not in body - ): - return False - except Exception: - return True - if _depth >= 5: - # The kernel gives up on nested shebangs past a fixed depth. - return False - # The kernel takes the interpreter pathname up to the first blank: - # a carriage return before that blank is part of the pathname (and - # makes it not exist), while one after it lands in the argument - # passed to an existing interpreter, whose execve still succeeds. - line = first_line[2:].rstrip(b"\n").lstrip(b" \t") - end = len(line) - for sep in (b" ", b"\t"): - i = line.find(sep) - if i != -1: - end = min(end, i) - if end == 0: - return False - program = os.fsdecode(line[:end]) - if not os.path.isabs(program): - base = os.fsdecode(cwd) if cwd is not None else os.getcwd() - program = os.path.join(base, program) - if not os.path.isfile(program): - return False - return _execve_candidate_is_viable(program, cwd=cwd, _depth=_depth + 1) - - def _select_fork_exec_executable(executable_list, cwd=None): """ - The entry of fork_exec's executable list that will actually run: - fork_exec tries each entry in order until an execve succeeds, so - this is the first viable entry (relative entries resolve against - the child's working directory). When no entry is viable, the first - existing entry is returned so the launch fails as it would have - without patching. + The entry of fork_exec's executable list to base patching on: the + first entry that exists (relative entries resolve against the + child's working directory). fork_exec tries each entry in order + until an execve succeeds, but which entry that turns out to be + cannot be predicted reliably from this process: the child's cwd, + credentials, permissions, mounts or binfmt handlers may differ, + or change before the exec (i.e.: through preexec_fn). So no later + entry is ever substituted for the first existing one based on + probing: if that entry is not a patchable python shebang script, + the launch is left unchanged. """ - first_existing = None for candidate in executable_list: candidate_path = candidate if cwd is not None and not os.path.isabs(os.fsdecode(candidate)): candidate_path = os.path.join(os.fsdecode(cwd), os.fsdecode(candidate)) - if not os.path.isfile(candidate_path): - continue - if first_existing is None: - first_existing = candidate - if _execve_candidate_is_viable(candidate_path, cwd=cwd): + if os.path.isfile(candidate_path): return candidate - return first_existing + return None def _patch_fork_exec_args(args, other_args): """ Shared patching for the fork_exec hooks: select the executable - that will actually run from the executable list and patch the - launch based on it, replacing the list with the program to launch - through when the selection is a python shebang script. + from the executable list and patch the launch based on it, + replacing the list with the program to launch through when the + selection is a python shebang script. """ env_list = other_args[4] if len(other_args) > 4 else None cwd = other_args[3] if len(other_args) > 3 else None actual_executable = None + existing = [] if other_args: actual_executable = _select_fork_exec_executable(other_args[0], cwd=cwd) + for candidate in other_args[0]: + candidate_path = candidate + if cwd is not None and not os.path.isabs(os.fsdecode(candidate)): + candidate_path = os.path.join(os.fsdecode(cwd), os.fsdecode(candidate)) + if os.path.isfile(candidate_path): + existing.append(candidate) # The selected entry is a literal path (the list is already the # result of the caller's PATH expansion): it must not be searched # through PATH again, which could select a different file. - args, executable = _patch_args_for_launch( + new_args, executable = _patch_args_for_launch( actual_executable, args, env=env_list, cwd=cwd, search_path=False ) + if executable is not None and len(existing) > 1: + # Replacing the list with the single program to launch + # through would discard fork_exec's native fallback: with + # more than one existing entry, a later entry may be the one + # that runs when the first entry's exec fails in a way that + # cannot be predicted from here, so the launch is left + # unchanged instead. (A patch that keeps the list, i.e. one + # with no replacement executable, keeps the fallback and is + # applied as usual.) + return args, other_args + args = new_args if executable is not None and other_args: if other_args[0] and isinstance(other_args[0][0], bytes) != isinstance(executable, bytes): executable = _get_str_type_compatible(other_args[0][0], executable) diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py index c31a40aef..bc709072b 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py @@ -594,6 +594,30 @@ def test_monkey_patch_args_shebang_env_split_quoted_script(tmp_path) -> None: assert pydev_monkey.patch_args(check[:]) == check +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_text_interpreter_script(tmp_path, monkeypatch) -> None: + # The program named by the shebang must be in an executable + # format: a plain text file named like a python interpreter + # fails with ENOEXEC natively, so the launch is left unchanged + # instead of being rewritten to run through that file. (No + # binfmt_misc handler is registered that could run it either.) + monkeypatch.setattr(pydev_monkey, "_binfmt_misc_has_handlers", lambda: False) + + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + interpreter = tmp_path / "python3" + interpreter.write_text("echo not a real interpreter\n") + interpreter.chmod(0o755) + script = tmp_path / "child_script" + script.write_text("#!%s\nprint('hello')\n" % interpreter) + script.chmod(0o755) + + assert pydev_monkey._parse_shebang(str(script)) is None + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + @pytest.mark.skipif( sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) @@ -625,6 +649,75 @@ def test_monkey_patch_args_shebang_crlf_script(tmp_path) -> None: assert pydev_monkey.patch_args(check[:]) == check +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_non_utf8_interpreter_script(tmp_path) -> None: + # Bytes that are not valid UTF-8 in the interpreter pathname are + # part of the name the kernel tries to launch (and fails): they + # must not be dropped to normalize the shebang into a valid + # python launch. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_bytes(b"#!/usr/bin/python3\xff\nprint('hello')\n") + script.chmod(0o755) + + assert pydev_monkey._parse_shebang(str(script)) is None + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_vertical_tab_separator_script(tmp_path) -> None: + # The kernel separates the interpreter pathname from its argument + # with blanks (space and tab) only: a vertical tab or a form feed + # is part of the pathname, so such shebangs fail to launch + # natively and must be left unchanged instead of being split + # into a valid python launch. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + for sep in (b"\x0b", b"\x0c"): + script.write_bytes(b"#!/usr/bin/python3" + sep + b"-O\nprint('hello')\n") + script.chmod(0o755) + + assert pydev_monkey._parse_shebang(str(script)) is None + check: list[str] = [str(script), "bar"] + assert pydev_monkey.patch_args(check[:]) == check + + # A vertical tab right after #! is not a separator either. + script.write_bytes(b"#!\x0b/usr/bin/python3\nprint('hello')\n") + script.chmod(0o755) + assert pydev_monkey._parse_shebang(str(script)) is None + + # Space and tab stay valid separators. + script.write_bytes(b"#!/usr/bin/python3\t-O\nprint('hello')\n") + script.chmod(0o755) + assert pydev_monkey._parse_shebang(str(script)) is not None + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_monkey_patch_args_shebang_env_split_other_whitespace_script(tmp_path) -> None: + # env -S re-splits the argument it receives with its own rules, + # which treat all ASCII whitespace as a separator (verified + # against GNU env): a vertical tab or form feed between the + # interpreter and its flag is a valid env -S launch, unlike the + # direct and plain env forms above. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + for sep in (b"\x0b", b"\x0c"): + script.write_bytes(b"#!/usr/bin/env -S python3" + sep + b"-O\nprint('hello')\n") + script.chmod(0o755) + + shebang_info = pydev_monkey._parse_shebang(str(script)) + assert shebang_info is not None + assert shebang_info[0] == "python3" + assert shebang_info[1] == ["-O"] + + @pytest.mark.skipif( sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) @@ -1320,11 +1413,17 @@ def test_shebang_execve_executable_mismatch(tmp_path) -> None: @pytest.mark.skipif( sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) -def test_fork_exec_skips_script_with_missing_shebang_interpreter(tmp_path) -> None: - # fork_exec tries the executable list entries in order until one - # execve succeeds: a script whose shebang interpreter does not - # exist fails and is skipped in favor of a later entry, so the - # later entry is the one the patching must be based on. +def test_fork_exec_first_existing_candidate_is_not_skipped(tmp_path) -> None: + # Conservative fallback, documented: fork_exec tries the + # executable list entries in order until one execve succeeds, but + # which entry that is cannot be predicted reliably from the + # parent (the child's cwd, credentials, permissions, mounts or + # binfmt handlers may differ, or change before the exec). So + # patching is based on the first existing entry only and never + # probes ahead to a later one: here the first existing entry is a + # script whose shebang interpreter does not exist, and even + # though the later entry is a patchable python script, the launch + # is left unchanged, exactly as it would run without patching. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} bad_dir = tmp_path / "bad" bad_dir.mkdir() @@ -1340,28 +1439,65 @@ def test_fork_exec_skips_script_with_missing_shebang_interpreter(tmp_path) -> No assert pydev_monkey._select_fork_exec_executable( [str(bad_script), str(good_script)] + ) == str(bad_script) + # Only entries that do not exist at all are passed over. + assert pydev_monkey._select_fork_exec_executable( + [str(tmp_path / "missing"), str(good_script)] ) == str(good_script) - # With no viable entry, the first existing entry is kept so the - # launch fails as it would have without patching. - assert pydev_monkey._select_fork_exec_executable([str(bad_script)]) == str(bad_script) + assert pydev_monkey._select_fork_exec_executable([str(tmp_path / "missing")]) is None other_args = ((str(bad_script), str(good_script)), True, (), None, None) new_args, new_other_args = pydev_monkey._patch_fork_exec_args( ["child_script", "hello"], other_args ) + assert new_args == ["child_script", "hello"] + assert new_other_args == other_args + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Shebang execution is not supported on Windows." +) +def test_fork_exec_replacement_kept_only_without_fallback(tmp_path) -> None: + # Replacing the executable list with the program to launch + # through is only done when there is no native fallback to lose: + # with a second existing entry, fork_exec might run that entry + # when the first one's exec fails in a way that cannot be + # predicted from the parent, so a patch that would replace the + # list is dropped and the launch is left unchanged. With the + # script as the only existing entry, the same patch is applied. + SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} + script = tmp_path / "child_script" + script.write_text("#!/usr/bin/env python3\nprint('hello')\n") + script.chmod(0o755) + other = tmp_path / "other_script" + other.write_text("#!/usr/bin/env python3\nprint('other')\n") + other.chmod(0o755) + + other_args = ((str(script), str(other)), True, (), None, None) + new_args, new_other_args = pydev_monkey._patch_fork_exec_args( + ["child_script", "hello"], other_args + ) + assert new_args == ["child_script", "hello"] + assert new_other_args == other_args + + other_args = ((str(script), str(tmp_path / "missing")), True, (), None, None) + new_args, new_other_args = pydev_monkey._patch_fork_exec_args( + ["child_script", "hello"], other_args + ) assert new_other_args[0] == ("/usr/bin/env",) - assert new_args[:2] == ["/usr/bin/env", "python3"] - assert new_args[new_args.index("--file") + 1] == str(good_script) + assert new_args[new_args.index("--file") + 1] == str(script) @pytest.mark.skipif( sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) -def test_fork_exec_fallback_through_subprocess(tmp_path) -> None: +def test_fork_exec_conservative_fallback_through_subprocess(tmp_path) -> None: # End to end through subprocess: the executable list CPython builds # from PATH starts with a script whose shebang interpreter is # missing, and the working script behind it is the one that runs - # (and must be attached). + # natively. Patching does not probe ahead to it (see + # test_fork_exec_first_existing_candidate_is_not_skipped), so it + # runs unattached, exactly as the native launch would. import subprocess bad_dir = tmp_path / "bad" @@ -1398,37 +1534,11 @@ def test_fork_exec_fallback_through_subprocess(tmp_path) -> None: out = subprocess.run( [sys.executable, str(harness)], capture_output=True, text=True, timeout=60 ) - assert "CHILD RAN" not in out.stdout + assert "CHILD RAN" in out.stdout assert "BAD RAN" not in out.stdout - assert "pydevd" in out.stdout - - -@pytest.mark.skipif( - sys.platform == "win32", reason="Shebang execution is not supported on Windows." -) -def test_fork_exec_crlf_shebang_candidate_viability(tmp_path) -> None: - # A CRLF env shebang still execs env successfully (the carriage - # return lands in env's argument), so fork_exec stops there: the - # entry is viable even though it cannot be patched. A CRLF direct - # shebang puts the carriage return in the interpreter pathname - # itself, so that exec fails and the next entry is tried. - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - crlf_env = tmp_path / "crlf_env_script" - crlf_env.write_bytes(b"#!/usr/bin/env python3\r\nprint('hello')\r\n") - crlf_env.chmod(0o755) - crlf_direct = tmp_path / "crlf_direct_script" - crlf_direct.write_bytes(b"#!/usr/bin/python3\r\nprint('hello')\r\n") - crlf_direct.chmod(0o755) - good = tmp_path / "good_script" - good.write_text("#!/usr/bin/env python3\nprint('hello')\n") - good.chmod(0o755) - - assert pydev_monkey._select_fork_exec_executable( - [str(crlf_env), str(good)] - ) == str(crlf_env) - assert pydev_monkey._select_fork_exec_executable( - [str(crlf_direct), str(good)] - ) == str(good) + # The child ran through the plain interpreter, not pydevd: no + # pydevd bootstrap arguments appear in what it printed. + assert "--file" not in out.stdout @pytest.mark.skipif( @@ -1474,37 +1584,13 @@ def test_shebang_launch_executable_mismatch_non_utf8_bytes(tmp_path) -> None: ) -@pytest.mark.skipif( - sys.platform == "win32", reason="Shebang execution is not supported on Windows." -) -def test_fork_exec_candidate_with_nested_broken_shebang(tmp_path) -> None: - # Viability recurses through nested shebangs as the kernel does: - # a script whose interpreter is itself a script with a missing - # interpreter fails to exec and is skipped. - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - wrapper = tmp_path / "wrapper_python" - wrapper.write_text("#!/nonexistent/python3\nprint('wrapper')\n") - wrapper.chmod(0o755) - bad = tmp_path / "bad_script" - bad.write_text("#!%s\nprint('bad')\n" % wrapper) - bad.chmod(0o755) - good = tmp_path / "good_script" - good.write_text("#!/usr/bin/env python3\nprint('good')\n") - good.chmod(0o755) - - assert pydev_monkey._select_fork_exec_executable([str(bad), str(good)]) == str(good) - # A working nested shebang stays viable. - wrapper.write_text("#!/usr/bin/env python3\nprint('wrapper')\n") - assert pydev_monkey._select_fork_exec_executable([str(bad), str(good)]) == str(bad) - - @pytest.mark.skipif( sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_fork_exec_candidate_non_utf8_shebang_program(tmp_path) -> None: # A shebang program whose path is not valid UTF-8 is still the - # program the kernel would run: the entry is viable and must not - # be skipped for a later one. + # program the kernel would run: the entry is the first existing + # one and stays the selection. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} program = os.fsencode(tmp_path) + b"/env_\xff" with open(program, "wb") as stream: @@ -1520,31 +1606,6 @@ def test_fork_exec_candidate_non_utf8_shebang_program(tmp_path) -> None: assert pydev_monkey._select_fork_exec_executable([str(script), str(good)]) == str(script) -@pytest.mark.skipif( - sys.platform == "win32", reason="Shebang execution is not supported on Windows." -) -def test_fork_exec_selected_bare_candidate_is_literal(tmp_path, monkeypatch) -> None: - # The selected executable list entry is a literal path, already - # PATH-expanded by the caller: patching must not search PATH again - # and land on a different (broken) namesake. - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - bad_dir = tmp_path / "bad" - bad_dir.mkdir() - bad_script = bad_dir / "task" - bad_script.write_text("#!/nonexistent/python3\nprint('bad')\n") - bad_script.chmod(0o755) - good_script = tmp_path / "task" - good_script.write_text("#!/usr/bin/env python3\nprint('good')\n") - good_script.chmod(0o755) - - monkeypatch.chdir(tmp_path) - env_list = ["PATH=" + str(bad_dir) + os.pathsep + "/usr/bin" + os.pathsep + "/bin"] - other_args = ((str(bad_script), "task"), True, (), str(tmp_path), env_list) - new_args, new_other_args = pydev_monkey._patch_fork_exec_args(["task", "hello"], other_args) - assert new_other_args[0] == ("/usr/bin/env",) - assert new_args[new_args.index("--file") + 1] == str(good_script) - - @pytest.mark.skipif( sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) @@ -1565,40 +1626,6 @@ def test_shebang_launch_executable_mismatch_python_named_script(tmp_path) -> Non assert new_args[-1] == "hello" -@pytest.mark.skipif( - sys.platform == "win32", reason="Shebang execution is not supported on Windows." -) -def test_fork_exec_candidate_text_file_without_shebang(tmp_path, monkeypatch) -> None: - # An executable text file without a shebang fails with ENOEXEC, - # so fork_exec moves on: it is not a viable candidate, and neither - # is a malformed ELF header, while a real binary for this host is. - import shutil - - monkeypatch.setattr(pydev_monkey, "_binfmt_misc_has_handlers", lambda: False) - - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - text_file = tmp_path / "text_candidate" - text_file.write_text("echo hello\n") - text_file.chmod(0o755) - fake_elf = tmp_path / "fake_elf_candidate" - fake_elf.write_bytes(b"\x7fELF\x02\x01\x01\x00" + b"\x00" * 64) - fake_elf.chmod(0o755) - good = tmp_path / "good_script" - good.write_text("#!/usr/bin/env python3\nprint('good')\n") - good.chmod(0o755) - - assert pydev_monkey._select_fork_exec_executable([str(text_file), str(good)]) == str(good) - assert pydev_monkey._select_fork_exec_executable([str(fake_elf), str(good)]) == str(good) - true_binary = shutil.which("true") - if true_binary is not None: - binary_file = tmp_path / "binary_candidate" - shutil.copy(true_binary, binary_file) - binary_file.chmod(0o755) - assert pydev_monkey._select_fork_exec_executable( - [str(binary_file), str(good)] - ) == str(binary_file) - - @pytest.mark.skipif( sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) @@ -1630,268 +1657,21 @@ def test_monkey_patch_args_shebang_python_named_script(tmp_path) -> None: ] -@pytest.mark.skipif( - sys.platform == "win32", reason="Shebang execution is not supported on Windows." -) -def test_fork_exec_candidate_malformed_native_elf(tmp_path) -> None: - # A header with this host's machine type but no executable type - # and no program headers is conclusively not executable, and a - # 32-bit x86 header is conclusively not a failure on x86_64 (the - # host runs compatibility binaries): viability follows the ELF - # header, not just the magic. - import platform - import struct - - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - good = tmp_path / "good_script" - good.write_text("#!/usr/bin/env python3\nprint('good')\n") - good.chmod(0o755) - - malformed = tmp_path / "malformed_candidate" - header = bytearray(64) - header[:4] = b"\x7fELF" - header[4] = 2 - header[5] = 1 - struct.pack_into(" None: - # A relative PT_INTERP loader is resolved against the child's - # working directory, like the kernel does in the fork_exec child: - # the same binary is viable from "/" and not from elsewhere. - import shutil - - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - true_binary = shutil.which("true") - if true_binary is None: - pytest.skip("no true binary available") - data = open(true_binary, "rb").read() - absolute_interp = b"/lib64/ld-linux-x86-64.so.2\x00" - if absolute_interp not in data: - pytest.skip("unexpected loader path in true binary") - relative_interp = b"lib64/ld-linux-x86-64.so.2\x00\x00" - binary_file = tmp_path / "binary_candidate" - binary_file.write_bytes(data.replace(absolute_interp, relative_interp)) - binary_file.chmod(0o755) - good = tmp_path / "good_script" - good.write_text("#!/usr/bin/env python3\nprint('good')\n") - good.chmod(0o755) - - assert pydev_monkey._select_fork_exec_executable( - [str(binary_file), str(good)], cwd="/" - ) == str(binary_file) - assert pydev_monkey._select_fork_exec_executable( - [str(binary_file), str(good)], cwd="/nonexistent" - ) == str(good) - - -@pytest.mark.skipif( - sys.platform == "win32", reason="Shebang execution is not supported on Windows." -) -def test_fork_exec_candidate_non_executable_elf_loader(tmp_path) -> None: - # A PT_INTERP loader that exists but is not executable makes the - # exec fail with EACCES, so the entry is not viable either. - import platform - import struct - - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - loader = tmp_path / "fake_loader" - loader.write_bytes(b"\x7fELF\x02\x01\x01\x00" + b"\x00" * 64) - loader.chmod(0o644) - interp = os.fsencode(loader) + b"\x00" - header = bytearray(64) - header[:4] = b"\x7fELF" - header[4] = 2 - header[5] = 1 - struct.pack_into(" None: - # A loader whose ELF header is truncated (valid magic, class, - # type and machine, but shorter than a full header) cannot be - # loaded: the entry pointing at it is not viable. - import platform - import struct - - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - loader = tmp_path / "truncated_loader" - loader_header = bytearray(20) - loader_header[:4] = b"\x7fELF" - loader_header[4] = 2 - loader_header[5] = 1 - struct.pack_into(" None: - # The kernel requires the program header entry size to be exact: - # an oversized e_phentsize is an ENOEXEC, not a viable binary. - import shutil - import struct - - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - true_binary = shutil.which("true") - if true_binary is None: - pytest.skip("no true binary available") - data = bytearray(open(true_binary, "rb").read()) - if len(data) < 56 or data[:4] != b"\x7fELF" or data[4] != 2: - pytest.skip("unexpected true binary format") - struct.pack_into(" None: - # The kernel rejects ELF program header tables over 64 KiB: such - # a binary is not a viable candidate even when the file is large - # enough to hold the table it declares. - import platform - import struct - - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - header = bytearray(64) - header[:4] = b"\x7fELF" - header[4] = 2 - header[5] = 1 - struct.pack_into(" None: # A shebang line beyond the kernel's 256-byte buffer cannot be - # launched as a script at all: the args are left unchanged and - # the entry is not a viable fork_exec candidate. + # launched as a script at all: the args are left unchanged. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "child_script" script.write_text( "#!" + "/" * pydev_monkey._SHEBANG_WINDOW + "usr/bin/python3\nprint('hello')\n" ) script.chmod(0o755) - good = tmp_path / "good_script" - good.write_text("#!/usr/bin/env python3\nprint('good')\n") - good.chmod(0o755) check: list[str] = [str(script), "bar"] assert pydev_monkey.patch_args(check[:]) == check - assert pydev_monkey._select_fork_exec_executable([str(script), str(good)]) == str(good) @pytest.mark.skipif( @@ -1899,9 +1679,10 @@ def test_monkey_patch_args_shebang_line_too_long(tmp_path) -> None: ) def test_fork_exec_candidate_shebang_long_argument(tmp_path) -> None: # A shebang whose optional argument runs past the kernel's - # buffer is truncated by the kernel, not rejected: the entry is - # viable (unlike a pathname that is itself unterminated there, - # covered by test_monkey_patch_args_shebang_line_too_long). + # buffer is truncated by the kernel, not rejected: the entry + # stays the selection (unlike a pathname that is itself + # unterminated there, covered by + # test_monkey_patch_args_shebang_line_too_long). SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "long_arg_script" script.write_text("#!/bin/true " + "x" * 300 + "\n") @@ -1936,44 +1717,6 @@ def test_fork_exec_candidate_shebang_window_edges(tmp_path) -> None: assert pydev_monkey._select_fork_exec_executable([str(nul), str(good)]) == str(nul) -@pytest.mark.skipif( - sys.platform == "win32", reason="Shebang execution is not supported on Windows." -) -def test_fork_exec_candidate_foreign_elf_binfmt(tmp_path, monkeypatch) -> None: - # A foreign-architecture ELF is conclusively unexecutable only - # when no binfmt_misc handler (i.e.: qemu) is registered for it: - # with a handler present, the entry stays viable. - import platform - import shutil - import struct - - if platform.machine() != "x86_64" or sys.platform != "linux": - pytest.skip("test is written for an x86_64 Linux host") - SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} - true_binary = shutil.which("true") - if true_binary is None: - pytest.skip("no true binary available") - data = bytearray(open(true_binary, "rb").read()) - if len(data) < 20 or data[:4] != b"\x7fELF": - pytest.skip("unexpected true binary format") - struct.pack_into(" Date: Mon, 30 Nov 2026 20:39:59 -0600 Subject: [PATCH 4/4] Remove comments added with the follow-up shebang changes --- .../pydevd/_pydev_bundle/pydev_monkey.py | 27 ---------- .../pydevd/tests_python/test_pydev_monkey.py | 51 ------------------- 2 files changed, 78 deletions(-) diff --git a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py index 2d6ce5fd4..41257d6e9 100644 --- a/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/_pydev_bundle/pydev_monkey.py @@ -413,13 +413,6 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, if not first_line.startswith(b"#!"): return None - # Parse at the byte level, following the kernel: the shebang ends - # at the first newline or NUL, and blanks (space and tab) are the - # only separators. Any other byte stays part of the interpreter - # pathname or of the argument: a vertical tab or form feed is not - # a separator, and bytes that are not valid UTF-8 in the pathname - # make it a name that cannot be launched. Neither may be - # normalized into a valid python launch here. line = first_line[2:].split(b"\n", 1)[0].split(b"\x00", 1)[0].strip(b" \t") if not line: return None @@ -446,10 +439,6 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, # launch failure instead of rewriting it into a working one. return None if not _shebang_program_is_launchable(program_path): - # The program is not in an executable format at all (i.e.: a - # plain text file without a shebang of its own): its exec - # fails with ENOEXEC, so preserve the native launch instead - # of rewriting it into one that cannot run either. return None if os.path.basename(interpreter) == "env": @@ -461,14 +450,6 @@ def _parse_shebang(path, cwd=None, env=None) -> tuple[str, list[str], str, bool, # handled. if '"' in rest or "'" in rest or "\\" in rest or "$" in rest: return None - # Without -S, env receives the rest as a single argument: it - # is split here on blanks (space and tab) only, like the - # kernel, and other whitespace stays part of a token (i.e.: a - # vertical tab used as a separator makes it one long name for - # env, not separate arguments, so such launches are left - # unchanged). env -S instead re-splits the argument it - # receives with its own rules, which treat all ASCII - # whitespace as a separator. split_args = rest.startswith("-S") and (len(rest) == 2 or rest[2] in " \t\x0b\x0c") if split_args: args = [token for token in re.split("[ \t\x0b\x0c]+", rest[2:]) if token] @@ -1515,14 +1496,6 @@ def _patch_fork_exec_args(args, other_args): actual_executable, args, env=env_list, cwd=cwd, search_path=False ) if executable is not None and len(existing) > 1: - # Replacing the list with the single program to launch - # through would discard fork_exec's native fallback: with - # more than one existing entry, a later entry may be the one - # that runs when the first entry's exec fails in a way that - # cannot be predicted from here, so the launch is left - # unchanged instead. (A patch that keeps the list, i.e. one - # with no replacement executable, keeps the fallback and is - # applied as usual.) return args, other_args args = new_args if executable is not None and other_args: diff --git a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py index bc709072b..2f2df8535 100644 --- a/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py +++ b/src/debugpy/_vendored/pydevd/tests_python/test_pydev_monkey.py @@ -598,11 +598,6 @@ def test_monkey_patch_args_shebang_env_split_quoted_script(tmp_path) -> None: sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_monkey_patch_args_shebang_text_interpreter_script(tmp_path, monkeypatch) -> None: - # The program named by the shebang must be in an executable - # format: a plain text file named like a python interpreter - # fails with ENOEXEC natively, so the launch is left unchanged - # instead of being rewritten to run through that file. (No - # binfmt_misc handler is registered that could run it either.) monkeypatch.setattr(pydev_monkey, "_binfmt_misc_has_handlers", lambda: False) SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} @@ -653,10 +648,6 @@ def test_monkey_patch_args_shebang_crlf_script(tmp_path) -> None: sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_monkey_patch_args_shebang_non_utf8_interpreter_script(tmp_path) -> None: - # Bytes that are not valid UTF-8 in the interpreter pathname are - # part of the name the kernel tries to launch (and fails): they - # must not be dropped to normalize the shebang into a valid - # python launch. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "child_script" script.write_bytes(b"#!/usr/bin/python3\xff\nprint('hello')\n") @@ -671,11 +662,6 @@ def test_monkey_patch_args_shebang_non_utf8_interpreter_script(tmp_path) -> None sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_monkey_patch_args_shebang_vertical_tab_separator_script(tmp_path) -> None: - # The kernel separates the interpreter pathname from its argument - # with blanks (space and tab) only: a vertical tab or a form feed - # is part of the pathname, so such shebangs fail to launch - # natively and must be left unchanged instead of being split - # into a valid python launch. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "child_script" for sep in (b"\x0b", b"\x0c"): @@ -686,12 +672,10 @@ def test_monkey_patch_args_shebang_vertical_tab_separator_script(tmp_path) -> No check: list[str] = [str(script), "bar"] assert pydev_monkey.patch_args(check[:]) == check - # A vertical tab right after #! is not a separator either. script.write_bytes(b"#!\x0b/usr/bin/python3\nprint('hello')\n") script.chmod(0o755) assert pydev_monkey._parse_shebang(str(script)) is None - # Space and tab stay valid separators. script.write_bytes(b"#!/usr/bin/python3\t-O\nprint('hello')\n") script.chmod(0o755) assert pydev_monkey._parse_shebang(str(script)) is not None @@ -701,11 +685,6 @@ def test_monkey_patch_args_shebang_vertical_tab_separator_script(tmp_path) -> No sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_monkey_patch_args_shebang_env_split_other_whitespace_script(tmp_path) -> None: - # env -S re-splits the argument it receives with its own rules, - # which treat all ASCII whitespace as a separator (verified - # against GNU env): a vertical tab or form feed between the - # interpreter and its flag is a valid env -S launch, unlike the - # direct and plain env forms above. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "child_script" for sep in (b"\x0b", b"\x0c"): @@ -1414,16 +1393,6 @@ def test_shebang_execve_executable_mismatch(tmp_path) -> None: sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_fork_exec_first_existing_candidate_is_not_skipped(tmp_path) -> None: - # Conservative fallback, documented: fork_exec tries the - # executable list entries in order until one execve succeeds, but - # which entry that is cannot be predicted reliably from the - # parent (the child's cwd, credentials, permissions, mounts or - # binfmt handlers may differ, or change before the exec). So - # patching is based on the first existing entry only and never - # probes ahead to a later one: here the first existing entry is a - # script whose shebang interpreter does not exist, and even - # though the later entry is a patchable python script, the launch - # is left unchanged, exactly as it would run without patching. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} bad_dir = tmp_path / "bad" bad_dir.mkdir() @@ -1440,7 +1409,6 @@ def test_fork_exec_first_existing_candidate_is_not_skipped(tmp_path) -> None: assert pydev_monkey._select_fork_exec_executable( [str(bad_script), str(good_script)] ) == str(bad_script) - # Only entries that do not exist at all are passed over. assert pydev_monkey._select_fork_exec_executable( [str(tmp_path / "missing"), str(good_script)] ) == str(good_script) @@ -1458,13 +1426,6 @@ def test_fork_exec_first_existing_candidate_is_not_skipped(tmp_path) -> None: sys.platform == "win32", reason="Shebang execution is not supported on Windows." ) def test_fork_exec_replacement_kept_only_without_fallback(tmp_path) -> None: - # Replacing the executable list with the program to launch - # through is only done when there is no native fallback to lose: - # with a second existing entry, fork_exec might run that entry - # when the first one's exec fails in a way that cannot be - # predicted from the parent, so a patch that would replace the - # list is dropped and the launch is left unchanged. With the - # script as the only existing entry, the same patch is applied. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "child_script" script.write_text("#!/usr/bin/env python3\nprint('hello')\n") @@ -1495,9 +1456,6 @@ def test_fork_exec_conservative_fallback_through_subprocess(tmp_path) -> None: # End to end through subprocess: the executable list CPython builds # from PATH starts with a script whose shebang interpreter is # missing, and the working script behind it is the one that runs - # natively. Patching does not probe ahead to it (see - # test_fork_exec_first_existing_candidate_is_not_skipped), so it - # runs unattached, exactly as the native launch would. import subprocess bad_dir = tmp_path / "bad" @@ -1536,8 +1494,6 @@ def test_fork_exec_conservative_fallback_through_subprocess(tmp_path) -> None: ) assert "CHILD RAN" in out.stdout assert "BAD RAN" not in out.stdout - # The child ran through the plain interpreter, not pydevd: no - # pydevd bootstrap arguments appear in what it printed. assert "--file" not in out.stdout @@ -1589,8 +1545,6 @@ def test_shebang_launch_executable_mismatch_non_utf8_bytes(tmp_path) -> None: ) def test_fork_exec_candidate_non_utf8_shebang_program(tmp_path) -> None: # A shebang program whose path is not valid UTF-8 is still the - # program the kernel would run: the entry is the first existing - # one and stays the selection. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} program = os.fsencode(tmp_path) + b"/env_\xff" with open(program, "wb") as stream: @@ -1662,7 +1616,6 @@ def test_monkey_patch_args_shebang_python_named_script(tmp_path) -> None: ) def test_monkey_patch_args_shebang_line_too_long(tmp_path) -> None: # A shebang line beyond the kernel's 256-byte buffer cannot be - # launched as a script at all: the args are left unchanged. SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "child_script" script.write_text( @@ -1679,10 +1632,6 @@ def test_monkey_patch_args_shebang_line_too_long(tmp_path) -> None: ) def test_fork_exec_candidate_shebang_long_argument(tmp_path) -> None: # A shebang whose optional argument runs past the kernel's - # buffer is truncated by the kernel, not rejected: the entry - # stays the selection (unlike a pathname that is itself - # unterminated there, covered by - # test_monkey_patch_args_shebang_line_too_long). SetupHolder.setup = {"client": "127.0.0.1", "port": "0", "multiprocess": True} script = tmp_path / "long_arg_script" script.write_text("#!/bin/true " + "x" * 300 + "\n")