debuggee.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. # Copyright (c) Microsoft Corporation. All rights reserved.
  2. # Licensed under the MIT License. See LICENSE in the project root
  3. # for license information.
  4. import atexit
  5. import ctypes
  6. import os
  7. import signal
  8. import struct
  9. import subprocess
  10. import sys
  11. import threading
  12. from debugpy import launcher
  13. from debugpy.common import log, messaging
  14. from debugpy.launcher import output
  15. if sys.platform == "win32":
  16. from debugpy.launcher import winapi
  17. process = None
  18. """subprocess.Popen instance for the debuggee process."""
  19. job_handle = None
  20. """On Windows, the handle for the job object to which the debuggee is assigned."""
  21. wait_on_exit_predicates = []
  22. """List of functions that determine whether to pause after debuggee process exits.
  23. Every function is invoked with exit code as the argument. If any of the functions
  24. returns True, the launcher pauses and waits for user input before exiting.
  25. """
  26. def describe():
  27. return f"Debuggee[PID={process.pid}]"
  28. def spawn(process_name, cmdline, env, redirect_output):
  29. log.info(
  30. "Spawning debuggee process:\n\n"
  31. "Command line: {0!r}\n\n"
  32. "Environment variables: {1!r}\n\n",
  33. cmdline,
  34. env,
  35. )
  36. close_fds = set()
  37. try:
  38. if redirect_output:
  39. # subprocess.PIPE behavior can vary substantially depending on Python version
  40. # and platform; using our own pipes keeps it simple, predictable, and fast.
  41. stdout_r, stdout_w = os.pipe()
  42. stderr_r, stderr_w = os.pipe()
  43. close_fds |= {stdout_r, stdout_w, stderr_r, stderr_w}
  44. kwargs = dict(stdout=stdout_w, stderr=stderr_w)
  45. else:
  46. kwargs = {}
  47. if sys.platform != "win32" and sys.implementation.name != 'graalpy':
  48. # GraalPy does not support running code between fork and exec
  49. def preexec_fn():
  50. try:
  51. # Start the debuggee in a new process group, so that the launcher can
  52. # kill the entire process tree later.
  53. os.setpgrp()
  54. # Make the new process group the foreground group in its session, so
  55. # that it can interact with the terminal. The debuggee will receive
  56. # SIGTTOU when tcsetpgrp() is called, and must ignore it.
  57. old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
  58. try:
  59. tty = os.open("/dev/tty", os.O_RDWR)
  60. try:
  61. os.tcsetpgrp(tty, os.getpgrp())
  62. finally:
  63. os.close(tty)
  64. finally:
  65. signal.signal(signal.SIGTTOU, old_handler)
  66. except Exception:
  67. # Not an error - /dev/tty doesn't work when there's no terminal.
  68. log.swallow_exception(
  69. "Failed to set up process group", level="info"
  70. )
  71. kwargs.update(preexec_fn=preexec_fn)
  72. try:
  73. global process
  74. process = subprocess.Popen(cmdline, env=env, bufsize=0, **kwargs)
  75. except Exception as exc:
  76. raise messaging.MessageHandlingError(
  77. "Couldn't spawn debuggee: {0}\n\nCommand line:{1!r}".format(
  78. exc, cmdline
  79. )
  80. )
  81. log.info("Spawned {0}.", describe())
  82. if sys.platform == "win32":
  83. # Assign the debuggee to a new job object, so that the launcher can kill
  84. # the entire process tree later.
  85. try:
  86. global job_handle
  87. job_handle = winapi.kernel32.CreateJobObjectA(None, None)
  88. job_info = winapi.JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
  89. job_info_size = winapi.DWORD(ctypes.sizeof(job_info))
  90. winapi.kernel32.QueryInformationJobObject(
  91. job_handle,
  92. winapi.JobObjectExtendedLimitInformation,
  93. ctypes.pointer(job_info),
  94. job_info_size,
  95. ctypes.pointer(job_info_size),
  96. )
  97. job_info.BasicLimitInformation.LimitFlags |= (
  98. # Ensure that the job will be terminated by the OS once the
  99. # launcher exits, even if it doesn't terminate the job explicitly.
  100. winapi.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
  101. |
  102. # Allow the debuggee to create its own jobs unrelated to ours.
  103. winapi.JOB_OBJECT_LIMIT_BREAKAWAY_OK
  104. )
  105. winapi.kernel32.SetInformationJobObject(
  106. job_handle,
  107. winapi.JobObjectExtendedLimitInformation,
  108. ctypes.pointer(job_info),
  109. job_info_size,
  110. )
  111. process_handle = winapi.kernel32.OpenProcess(
  112. winapi.PROCESS_TERMINATE | winapi.PROCESS_SET_QUOTA,
  113. False,
  114. process.pid,
  115. )
  116. winapi.kernel32.AssignProcessToJobObject(job_handle, process_handle)
  117. except Exception:
  118. log.swallow_exception("Failed to set up job object", level="warning")
  119. atexit.register(kill)
  120. launcher.channel.send_event(
  121. "process",
  122. {
  123. "startMethod": "launch",
  124. "isLocalProcess": True,
  125. "systemProcessId": process.pid,
  126. "name": process_name,
  127. "pointerSize": struct.calcsize("P") * 8,
  128. },
  129. )
  130. if redirect_output:
  131. for category, fd, tee in [
  132. ("stdout", stdout_r, sys.stdout),
  133. ("stderr", stderr_r, sys.stderr),
  134. ]:
  135. output.CaptureOutput(describe(), category, fd, tee)
  136. close_fds.remove(fd)
  137. wait_thread = threading.Thread(target=wait_for_exit, name="wait_for_exit()")
  138. wait_thread.daemon = True
  139. wait_thread.start()
  140. finally:
  141. for fd in close_fds:
  142. try:
  143. os.close(fd)
  144. except Exception:
  145. log.swallow_exception(level="warning")
  146. def kill():
  147. if process is None:
  148. return
  149. try:
  150. if process.poll() is None:
  151. log.info("Killing {0}", describe())
  152. # Clean up the process tree
  153. if sys.platform == "win32":
  154. # On Windows, kill the job object.
  155. winapi.kernel32.TerminateJobObject(job_handle, 0)
  156. else:
  157. # On POSIX, kill the debuggee's process group.
  158. os.killpg(process.pid, signal.SIGKILL)
  159. except Exception:
  160. log.swallow_exception("Failed to kill {0}", describe())
  161. def wait_for_exit():
  162. try:
  163. code = process.wait()
  164. if sys.platform != "win32" and code < 0:
  165. # On POSIX, if the process was terminated by a signal, Popen will use
  166. # a negative returncode to indicate that - but the actual exit code of
  167. # the process is always an unsigned number, and can be determined by
  168. # taking the lowest 8 bits of that negative returncode.
  169. code &= 0xFF
  170. except Exception:
  171. log.swallow_exception("Couldn't determine process exit code")
  172. code = -1
  173. log.info("{0} exited with code {1}", describe(), code)
  174. output.wait_for_remaining_output()
  175. # Determine whether we should wait or not before sending "exited", so that any
  176. # follow-up "terminate" requests don't affect the predicates.
  177. should_wait = any(pred(code) for pred in wait_on_exit_predicates)
  178. try:
  179. launcher.channel.send_event("exited", {"exitCode": code})
  180. except Exception:
  181. pass
  182. if should_wait:
  183. _wait_for_user_input()
  184. try:
  185. launcher.channel.send_event("terminated")
  186. except Exception:
  187. pass
  188. def _wait_for_user_input():
  189. if sys.stdout and sys.stdin and sys.stdin.isatty():
  190. from debugpy.common import log
  191. try:
  192. import msvcrt
  193. except ImportError:
  194. can_getch = False
  195. else:
  196. can_getch = True
  197. if can_getch:
  198. log.debug("msvcrt available - waiting for user input via getch()")
  199. sys.stdout.write("Press any key to continue . . . ")
  200. sys.stdout.flush()
  201. msvcrt.getch()
  202. else:
  203. log.debug("msvcrt not available - waiting for user input via read()")
  204. sys.stdout.write("Press Enter to continue . . . ")
  205. sys.stdout.flush()
  206. sys.stdin.read(1)