servers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. from __future__ import annotations
  5. import os
  6. import subprocess
  7. import sys
  8. import threading
  9. import time
  10. import debugpy
  11. from debugpy import adapter
  12. from debugpy.common import json, log, messaging, sockets
  13. from debugpy.adapter import components, sessions
  14. import traceback
  15. import io
  16. access_token = None
  17. """Access token used to authenticate with the servers."""
  18. listener = None
  19. """Listener socket that accepts server connections."""
  20. _lock = threading.RLock()
  21. _connections = []
  22. """All servers that are connected to this adapter, in order in which they connected.
  23. """
  24. _connections_changed = threading.Event()
  25. class Connection(object):
  26. """A debug server that is connected to the adapter.
  27. Servers that are not participating in a debug session are managed directly by the
  28. corresponding Connection instance.
  29. Servers that are participating in a debug session are managed by that sessions's
  30. Server component instance, but Connection object remains, and takes over again
  31. once the session ends.
  32. """
  33. disconnected: bool
  34. process_replaced: bool
  35. """Whether this is a connection to a process that is being replaced in situ
  36. by another process, e.g. via exec().
  37. """
  38. server: Server | None
  39. """The Server component, if this debug server belongs to Session.
  40. """
  41. pid: int | None
  42. ppid: int | None
  43. channel: messaging.JsonMessageChannel
  44. def __init__(self, sock):
  45. from debugpy.adapter import sessions
  46. self.disconnected = False
  47. self.process_replaced = False
  48. self.server = None
  49. self.pid = None
  50. stream = messaging.JsonIOStream.from_socket(sock, str(self))
  51. self.channel = messaging.JsonMessageChannel(stream, self)
  52. self.channel.start()
  53. try:
  54. self.authenticate()
  55. info = self.channel.request("pydevdSystemInfo")
  56. process_info = info("process", json.object())
  57. self.pid = process_info("pid", int)
  58. self.ppid = process_info("ppid", int, optional=True)
  59. if self.ppid == ():
  60. self.ppid = None
  61. self.channel.name = stream.name = str(self)
  62. with _lock:
  63. # The server can disconnect concurrently before we get here, e.g. if
  64. # it was force-killed. If the disconnect() handler has already run,
  65. # don't register this server or report it, since there's nothing to
  66. # deregister it.
  67. if self.disconnected:
  68. return
  69. # An existing connection with the same PID and process_replaced == True
  70. # corresponds to the process that replaced itself with this one, so it's
  71. # not an error.
  72. if any(
  73. conn.pid == self.pid and not conn.process_replaced
  74. for conn in _connections
  75. ):
  76. raise KeyError(f"{self} is already connected to this adapter")
  77. is_first_server = len(_connections) == 0
  78. _connections.append(self)
  79. _connections_changed.set()
  80. except Exception:
  81. log.swallow_exception("Failed to accept incoming server connection:")
  82. self.channel.close()
  83. # If this was the first server to connect, and the main thread is inside
  84. # wait_until_disconnected(), we want to unblock it and allow it to exit.
  85. dont_wait_for_first_connection()
  86. # If we couldn't retrieve all the necessary info from the debug server,
  87. # or there's a PID clash, we don't want to track this debuggee anymore,
  88. # but we want to continue accepting connections.
  89. return
  90. parent_session = sessions.get(self.ppid)
  91. if parent_session is None:
  92. parent_session = sessions.get(self.pid)
  93. if parent_session is None:
  94. log.info("No active debug session for parent process of {0}.", self)
  95. else:
  96. if self.pid == parent_session.pid:
  97. parent_server = parent_session.server
  98. if not (parent_server and parent_server.connection.process_replaced):
  99. log.error("{0} is not expecting replacement.", parent_session)
  100. self.channel.close()
  101. return
  102. try:
  103. parent_session.client.notify_of_subprocess(self)
  104. return
  105. except Exception:
  106. # This might fail if the client concurrently disconnects from the parent
  107. # session. We still want to keep the connection around, in case the
  108. # client reconnects later. If the parent session was "launch", it'll take
  109. # care of closing the remaining server connections.
  110. log.swallow_exception(
  111. "Failed to notify parent session about {0}:", self
  112. )
  113. # If we got to this point, the subprocess notification was either not sent,
  114. # or not delivered successfully. For the first server, this is expected, since
  115. # it corresponds to the root process, and there is no other debug session to
  116. # notify. But subsequent server connections represent subprocesses, and those
  117. # will not start running user code until the client tells them to. Since there
  118. # isn't going to be a client without the notification, such subprocesses have
  119. # to be unblocked.
  120. if is_first_server:
  121. return
  122. log.info("No clients to wait for - unblocking {0}.", self)
  123. try:
  124. self.channel.request("initialize", {"adapterID": "debugpy"})
  125. self.channel.request("attach", {"subProcessId": self.pid})
  126. self.channel.request("configurationDone")
  127. self.channel.request("disconnect")
  128. except Exception:
  129. log.swallow_exception("Failed to unblock orphaned subprocess:")
  130. self.channel.close()
  131. def __str__(self):
  132. return "Server" + ("[?]" if self.pid is None else f"[pid={self.pid}]")
  133. def authenticate(self):
  134. if access_token is None and adapter.access_token is None:
  135. return
  136. auth = self.channel.request(
  137. "pydevdAuthorize", {"debugServerAccessToken": access_token}
  138. )
  139. if auth["clientAccessToken"] != adapter.access_token:
  140. self.channel.close()
  141. raise RuntimeError('Mismatched "clientAccessToken"; server not authorized.')
  142. def request(self, request):
  143. raise request.isnt_valid(
  144. "Requests from the debug server to the client are not allowed."
  145. )
  146. def event(self, event):
  147. pass
  148. def terminated_event(self, event):
  149. self.channel.close()
  150. def disconnect(self):
  151. with _lock:
  152. self.disconnected = True
  153. if self.server is not None:
  154. # If the disconnect happened while Server was being instantiated,
  155. # we need to tell it, so that it can clean up via Session.finalize().
  156. # It will also take care of deregistering the connection in that case.
  157. self.server.disconnect()
  158. elif self in _connections:
  159. _connections.remove(self)
  160. _connections_changed.set()
  161. def attach_to_session(self, session):
  162. """Attaches this server to the specified Session as a Server component.
  163. Raises ValueError if the server already belongs to some session.
  164. """
  165. with _lock:
  166. if self.server is not None:
  167. raise ValueError
  168. log.info("Attaching {0} to {1}", self, session)
  169. self.server = Server(session, self)
  170. class Server(components.Component):
  171. """Handles the debug server side of a debug session."""
  172. message_handler = components.Component.message_handler
  173. connection: Connection
  174. class Capabilities(components.Capabilities):
  175. PROPERTIES = {
  176. "supportsCompletionsRequest": False,
  177. "supportsConditionalBreakpoints": False,
  178. "supportsConfigurationDoneRequest": False,
  179. "supportsDataBreakpoints": False,
  180. "supportsDelayedStackTraceLoading": False,
  181. "supportsDisassembleRequest": False,
  182. "supportsEvaluateForHovers": False,
  183. "supportsExceptionInfoRequest": False,
  184. "supportsExceptionOptions": False,
  185. "supportsFunctionBreakpoints": False,
  186. "supportsGotoTargetsRequest": False,
  187. "supportsHitConditionalBreakpoints": False,
  188. "supportsLoadedSourcesRequest": False,
  189. "supportsLogPoints": False,
  190. "supportsModulesRequest": False,
  191. "supportsReadMemoryRequest": False,
  192. "supportsRestartFrame": False,
  193. "supportsRestartRequest": False,
  194. "supportsSetExpression": False,
  195. "supportsSetVariable": False,
  196. "supportsStepBack": False,
  197. "supportsStepInTargetsRequest": False,
  198. "supportsTerminateRequest": True,
  199. "supportsTerminateThreadsRequest": False,
  200. "supportsValueFormattingOptions": False,
  201. "exceptionBreakpointFilters": [],
  202. "additionalModuleColumns": [],
  203. "supportedChecksumAlgorithms": [],
  204. }
  205. def __init__(self, session, connection):
  206. assert connection.server is None
  207. with session:
  208. assert not session.server
  209. super().__init__(session, channel=connection.channel)
  210. self.connection = connection
  211. assert self.session.pid is None
  212. if self.session.launcher and self.session.launcher.pid != self.pid:
  213. log.info(
  214. "Launcher reported PID={0}, but server reported PID={1}",
  215. self.session.launcher.pid,
  216. self.pid,
  217. )
  218. self.session.pid = self.pid
  219. session.server = self
  220. @property
  221. def pid(self):
  222. """Process ID of the debuggee process, as reported by the server."""
  223. return self.connection.pid
  224. @property
  225. def ppid(self):
  226. """Parent process ID of the debuggee process, as reported by the server."""
  227. return self.connection.ppid
  228. def initialize(self, request):
  229. assert request.is_request("initialize")
  230. self.connection.authenticate()
  231. request = self.channel.propagate(request)
  232. request.wait_for_response()
  233. self.capabilities = self.Capabilities(self, request.response)
  234. # Generic request handler, used if there's no specific handler below.
  235. @message_handler
  236. def request(self, request):
  237. # Do not delegate requests from the server by default. There is a security
  238. # boundary between the server and the adapter, and we cannot trust arbitrary
  239. # requests sent over that boundary, since they may contain arbitrary code
  240. # that the client will execute - e.g. "runInTerminal". The adapter must only
  241. # propagate requests that it knows are safe.
  242. raise request.isnt_valid(
  243. "Requests from the debug server to the client are not allowed."
  244. )
  245. # Generic event handler, used if there's no specific handler below.
  246. @message_handler
  247. def event(self, event):
  248. self.client.propagate_after_start(event)
  249. @message_handler
  250. def initialized_event(self, event):
  251. # pydevd doesn't send it, but the adapter will send its own in any case.
  252. pass
  253. @message_handler
  254. def process_event(self, event):
  255. # If there is a launcher, it's handling the process event.
  256. if not self.launcher:
  257. self.client.propagate_after_start(event)
  258. @message_handler
  259. def continued_event(self, event):
  260. # https://github.com/microsoft/ptvsd/issues/1530
  261. #
  262. # DAP specification says that a step request implies that only the thread on
  263. # which that step occurred is resumed for the duration of the step. However,
  264. # for VS compatibility, pydevd can operate in a mode that resumes all threads
  265. # instead. This is set according to the value of "steppingResumesAllThreads"
  266. # in "launch" or "attach" request, which defaults to true. If explicitly set
  267. # to false, pydevd will only resume the thread that was stepping.
  268. #
  269. # To ensure that the client is aware that other threads are getting resumed in
  270. # that mode, pydevd sends a "continued" event with "allThreadsResumed": true.
  271. # when responding to a step request. This ensures correct behavior in VSCode
  272. # and other DAP-conformant clients.
  273. #
  274. # On the other hand, VS does not follow the DAP specification in this regard.
  275. # When it requests a step, it assumes that all threads will be resumed, and
  276. # does not expect to see "continued" events explicitly reflecting that fact.
  277. # If such events are sent regardless, VS behaves erratically. Thus, we have
  278. # to suppress them specifically for VS.
  279. if self.client.client_id not in ("visualstudio", "vsformac"):
  280. self.client.propagate_after_start(event)
  281. @message_handler
  282. def exited_event(self, event: messaging.Event):
  283. if event("pydevdReason", str, optional=True) == "processReplaced":
  284. # The parent process used some API like exec() that replaced it with another
  285. # process in situ. The connection will shut down immediately afterwards, but
  286. # we need to keep the corresponding session alive long enough to report the
  287. # subprocess to it.
  288. self.connection.process_replaced = True
  289. else:
  290. # If there is a launcher, it's handling the exit code.
  291. if not self.launcher:
  292. self.client.propagate_after_start(event)
  293. @message_handler
  294. def terminated_event(self, event):
  295. # Do not propagate this, since we'll report our own.
  296. self.channel.close()
  297. def detach_from_session(self):
  298. with _lock:
  299. self.is_connected = False
  300. self.channel.handlers = self.connection
  301. self.channel.name = self.channel.stream.name = str(self.connection)
  302. self.connection.server = None
  303. def disconnect(self):
  304. if self.connection.process_replaced:
  305. # Wait for the replacement server to connect to the adapter, and to report
  306. # itself to the client for this session if there is one.
  307. log.info("{0} is waiting for replacement subprocess.", self)
  308. session = self.session
  309. if not session.client or not session.client.is_connected:
  310. wait_for_connection(
  311. session, lambda conn: conn.pid == self.pid, timeout=60
  312. )
  313. else:
  314. self.wait_for(
  315. lambda: (
  316. not session.client
  317. or not session.client.is_connected
  318. or any(
  319. conn.pid == self.pid
  320. for conn in session.client.known_subprocesses
  321. )
  322. ),
  323. timeout=60,
  324. )
  325. with _lock:
  326. _connections.remove(self.connection)
  327. _connections_changed.set()
  328. super().disconnect()
  329. def serve(host="127.0.0.1", port=0):
  330. global listener
  331. listener = sockets.serve("Server", Connection, host, port)
  332. sessions.report_sockets()
  333. return sockets.get_address(listener)
  334. def is_serving():
  335. return listener is not None
  336. def stop_serving():
  337. global listener
  338. try:
  339. if listener is not None:
  340. listener.close()
  341. listener = None
  342. except Exception:
  343. log.swallow_exception(level="warning")
  344. sessions.report_sockets()
  345. def connections():
  346. with _lock:
  347. return list(_connections)
  348. def wait_for_connection(session, predicate, timeout=None):
  349. """Waits until there is a server matching the specified predicate connected to
  350. this adapter, and returns the corresponding Connection.
  351. If there is more than one server connection already available, returns the oldest
  352. one.
  353. """
  354. def wait_for_timeout():
  355. time.sleep(timeout)
  356. wait_for_timeout.timed_out = True
  357. with _lock:
  358. _connections_changed.set()
  359. wait_for_timeout.timed_out = timeout == 0
  360. if timeout:
  361. thread = threading.Thread(
  362. target=wait_for_timeout, name="servers.wait_for_connection() timeout"
  363. )
  364. thread.daemon = True
  365. thread.start()
  366. if timeout != 0:
  367. log.info("{0} waiting for connection from debug server...", session)
  368. while True:
  369. with _lock:
  370. _connections_changed.clear()
  371. conns = (conn for conn in _connections if predicate(conn))
  372. conn = next(conns, None)
  373. if conn is not None or wait_for_timeout.timed_out:
  374. return conn
  375. _connections_changed.wait()
  376. def wait_until_disconnected():
  377. """Blocks until all debug servers disconnect from the adapter.
  378. If there are no server connections, waits until at least one is established first,
  379. before waiting for it to disconnect.
  380. """
  381. while True:
  382. _connections_changed.wait()
  383. with _lock:
  384. _connections_changed.clear()
  385. if not len(_connections):
  386. return
  387. def dont_wait_for_first_connection():
  388. """Unblocks any pending wait_until_disconnected() call that is waiting on the
  389. first server to connect.
  390. """
  391. with _lock:
  392. _connections_changed.set()
  393. def inject(pid, debugpy_args, on_output):
  394. host, port = sockets.get_address(listener)
  395. cmdline = [
  396. sys.executable,
  397. os.path.dirname(debugpy.__file__),
  398. "--connect",
  399. host + ":" + str(port),
  400. ]
  401. if adapter.access_token is not None:
  402. cmdline += ["--adapter-access-token", adapter.access_token]
  403. cmdline += debugpy_args
  404. cmdline += ["--pid", str(pid)]
  405. log.info("Spawning attach-to-PID debugger injector: {0!r}", cmdline)
  406. try:
  407. injector = subprocess.Popen(
  408. cmdline,
  409. bufsize=0,
  410. stdin=subprocess.PIPE,
  411. stdout=subprocess.PIPE,
  412. stderr=subprocess.STDOUT,
  413. )
  414. except Exception as exc:
  415. log.swallow_exception(
  416. "Failed to inject debug server into process with PID={0}", pid
  417. )
  418. raise messaging.MessageHandlingError(
  419. "Failed to inject debug server into process with PID={0}: {1}".format(
  420. pid, exc
  421. )
  422. )
  423. # We need to capture the output of the injector - needed so that it doesn't
  424. # get blocked on a write() syscall (besides showing it to the user if it
  425. # is taking longer than expected).
  426. output_collected = []
  427. output_collected.append("--- Starting attach to pid: {0} ---\n".format(pid))
  428. def capture(stream):
  429. nonlocal output_collected
  430. try:
  431. while True:
  432. line = stream.readline()
  433. if not line:
  434. break
  435. line = line.decode("utf-8", "replace")
  436. output_collected.append(line)
  437. log.info("Injector[PID={0}] output: {1}", pid, line.rstrip())
  438. log.info("Injector[PID={0}] exited.", pid)
  439. except Exception:
  440. s = io.StringIO()
  441. traceback.print_exc(file=s)
  442. on_output("stderr", s.getvalue())
  443. threading.Thread(
  444. target=capture,
  445. name=f"Injector[PID={pid}] stdout",
  446. args=(injector.stdout,),
  447. daemon=True,
  448. ).start()
  449. def info_on_timeout():
  450. nonlocal output_collected
  451. taking_longer_than_expected = False
  452. initial_time = time.time()
  453. while True:
  454. time.sleep(1)
  455. returncode = injector.poll()
  456. if returncode is not None:
  457. if returncode != 0:
  458. # Something didn't work out. Let's print more info to the user.
  459. on_output(
  460. "stderr",
  461. "Attach to PID failed.\n\n",
  462. )
  463. old = output_collected
  464. output_collected = []
  465. contents = "".join(old)
  466. on_output("stderr", "".join(contents))
  467. break
  468. elapsed = time.time() - initial_time
  469. on_output(
  470. "stdout", "Attaching to PID: %s (elapsed: %.2fs).\n" % (pid, elapsed)
  471. )
  472. if not taking_longer_than_expected:
  473. if elapsed > 10:
  474. taking_longer_than_expected = True
  475. if sys.platform in ("linux", "linux2"):
  476. on_output(
  477. "stdout",
  478. "\nThe attach to PID is taking longer than expected.\n",
  479. )
  480. on_output(
  481. "stdout",
  482. "On Linux it's possible to customize the value of\n",
  483. )
  484. on_output(
  485. "stdout",
  486. "`PYDEVD_GDB_SCAN_SHARED_LIBRARIES` so that fewer libraries.\n",
  487. )
  488. on_output(
  489. "stdout",
  490. "are scanned when searching for the needed symbols.\n\n",
  491. )
  492. on_output(
  493. "stdout",
  494. "i.e.: set in your environment variables (and restart your editor/client\n",
  495. )
  496. on_output(
  497. "stdout",
  498. "so that it picks up the updated environment variable value):\n\n",
  499. )
  500. on_output(
  501. "stdout",
  502. "PYDEVD_GDB_SCAN_SHARED_LIBRARIES=libdl, libltdl, libc, libfreebl3\n\n",
  503. )
  504. on_output(
  505. "stdout",
  506. "-- the actual library may be different (the gdb output typically\n",
  507. )
  508. on_output(
  509. "stdout",
  510. "-- writes the libraries that will be used, so, it should be possible\n",
  511. )
  512. on_output(
  513. "stdout",
  514. "-- to test other libraries if the above doesn't work).\n\n",
  515. )
  516. if taking_longer_than_expected:
  517. # If taking longer than expected, start showing the actual output to the user.
  518. old = output_collected
  519. output_collected = []
  520. contents = "".join(old)
  521. if contents:
  522. on_output("stderr", contents)
  523. threading.Thread(
  524. target=info_on_timeout, name=f"Injector[PID={pid}] info on timeout", daemon=True
  525. ).start()