attach_pid_injected.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. """Script injected into the debuggee process during attach-to-PID."""
  5. import os
  6. __file__ = os.path.abspath(__file__)
  7. _debugpy_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
  8. def attach(setup):
  9. log = None
  10. try:
  11. import sys
  12. if "threading" not in sys.modules:
  13. try:
  14. def on_warn(msg):
  15. print(msg, file=sys.stderr)
  16. def on_exception(msg):
  17. print(msg, file=sys.stderr)
  18. def on_critical(msg):
  19. print(msg, file=sys.stderr)
  20. pydevd_attach_to_process_path = os.path.join(
  21. _debugpy_dir,
  22. "debugpy",
  23. "_vendored",
  24. "pydevd",
  25. "pydevd_attach_to_process",
  26. )
  27. assert os.path.exists(pydevd_attach_to_process_path)
  28. sys.path.insert(0, pydevd_attach_to_process_path)
  29. # NOTE: that it's not a part of the pydevd PYTHONPATH
  30. import attach_script
  31. attach_script.fix_main_thread_id(
  32. on_warn=on_warn, on_exception=on_exception, on_critical=on_critical
  33. )
  34. # NOTE: At this point it should be safe to remove this.
  35. sys.path.remove(pydevd_attach_to_process_path)
  36. except:
  37. import traceback
  38. traceback.print_exc()
  39. raise
  40. sys.path.insert(0, _debugpy_dir)
  41. try:
  42. import debugpy
  43. import debugpy.server
  44. from debugpy.common import json, log
  45. import pydevd
  46. finally:
  47. assert sys.path[0] == _debugpy_dir
  48. del sys.path[0]
  49. py_db = pydevd.get_global_debugger()
  50. if py_db is not None:
  51. py_db.dispose_and_kill_all_pydevd_threads(wait=False)
  52. if setup["log_to"] is not None:
  53. debugpy.log_to(setup["log_to"])
  54. log.info("Configuring injected debugpy: {0}", json.repr(setup))
  55. if setup["mode"] == "listen":
  56. debugpy.listen(setup["address"])
  57. elif setup["mode"] == "connect":
  58. debugpy.connect(
  59. setup["address"], access_token=setup["adapter_access_token"]
  60. )
  61. else:
  62. raise AssertionError(repr(setup))
  63. except:
  64. import traceback
  65. traceback.print_exc()
  66. if log is None:
  67. raise
  68. else:
  69. log.reraise_exception()
  70. log.info("debugpy injected successfully")