blob: 1899cc30f37faf166b143725f2455cdfbe1df804 [file]
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import asyncio
import contextlib
import functools
import logging
import os
import pathlib
import signal
from collections.abc import Awaitable, Callable, Generator, Sequence
from typing import Any, Final, final
from async_utils.command import AsyncCommand, CommandOutput
from daemon import constants, socket_utils
from daemon.handlers import (
aspace,
async_backtrace,
attach,
break_req,
console,
continue_req,
detach,
diagnose_hang,
driver_list,
evaluate,
finish,
get_state,
handles,
hello,
mem_read,
modules,
next_req,
pause,
stack_trace,
start,
step_in,
stop,
threads,
tracepoint,
variables,
wait_for_event,
watch_req,
)
from daemon.state import Process, Thread
from daemon.target_repo import TargetRepoError, TargetRepoManager
from ffx_cmd.lib import FfxCmd
from pydap.client import READER_STOPPED_EVENT
from pydap.dap_types import Breakpoint
from pydap.models import InitializeArguments, PauseArguments
from shared import cleanup, session
from shared.protocol import (
BaseRequest,
Response,
T_Resp,
TracepointInfo,
WatchpointInfo,
deserialize_request,
serialize,
)
from shared.protocol.start import StartRequest
from zxdb_dap import (
ZxdbDapClient,
ZxdbDetachArguments,
ZxdbPauseArguments,
)
logger = logging.getLogger(__name__)
# Constants imported from daemon.constants
MAX_EVENT_HISTORY_SIZE: Final[int] = 100
_DAP_READY_TIMEOUT_SECS = 30.0
_TEARDOWN_GRACE_PERIOD_SECS = 1.0
_SERVER_WAIT_CLOSED_TIMEOUT_SECS = 0.5
_MAX_EARLY_EXIT_OUTPUT_CHARS = 2048
def _ignore_sigusr1() -> None:
pass
async def _wait_for_client_disconnect(reader: asyncio.StreamReader) -> None:
with contextlib.suppress(OSError, EOFError):
while await reader.read(4096):
pass
def _consume_task_exception(task: asyncio.Task[None]) -> None:
if not task.cancelled():
exc = task.exception()
if exc is not None:
logger.warning("Session cleanup failed: %s", exc)
async def _send_uds_response(
writer: asyncio.StreamWriter, resp: Response[Any]
) -> bool:
try:
writer.write(serialize(resp).encode("utf-8"))
await writer.drain()
except OSError:
return False
return True
async def _await_task_deferring_cancel(
task: asyncio.Task[Any],
) -> asyncio.CancelledError | None:
current_task = asyncio.current_task()
deferred_cancel: asyncio.CancelledError | None = None
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError as exc:
if not task.cancelled() or (
current_task is not None and current_task.cancelling() > 0
):
deferred_cancel = exc
if not task.done():
task.cancel()
except Exception:
pass
if not task.cancelled():
task.exception()
return deferred_cancel
async def _await_dap_wait_task(
wait_task: asyncio.Task[CommandOutput],
timeout: float,
) -> bool:
try:
async with asyncio.timeout(timeout):
await asyncio.shield(wait_task)
return True
except TimeoutError:
return False
except asyncio.CancelledError:
if wait_task.cancelled():
return True
raise
except Exception as e:
logger.warning("Failed waiting for zxdb process exit: %s", e)
return True
async def _reap_dap_proc(
dap_proc: AsyncCommand,
dap_wait_task: asyncio.Task[CommandOutput] | None,
) -> None:
if (
dap_wait_task is not None
and dap_wait_task.done()
and not dap_wait_task.cancelled()
and dap_wait_task.exception() is None
):
return
try:
dap_proc.terminate()
except Exception as e:
logger.warning("Failed to terminate zxdb process: %s", e)
wait_task = (
dap_wait_task
if dap_wait_task is not None and not dap_wait_task.done()
else asyncio.create_task(dap_proc.run_to_completion())
)
if await _await_dap_wait_task(wait_task, _TEARDOWN_GRACE_PERIOD_SECS):
return
try:
dap_proc.kill()
except Exception as e:
logger.warning("Failed to kill zxdb process: %s", e)
if await _await_dap_wait_task(wait_task, _TEARDOWN_GRACE_PERIOD_SECS):
return
if not wait_task.done():
logger.warning(
"Timed out waiting for zxdb process to exit after SIGKILL; "
"cancelling wait task."
)
wait_task.cancel()
await asyncio.gather(wait_task, return_exceptions=True)
def _format_early_exit_message(output: CommandOutput) -> str:
details = "\n".join(
stripped
for stream in (output.stderr, output.stdout)
if (stripped := stream.strip())
)
if len(details) > _MAX_EARLY_EXIT_OUTPUT_CHARS:
details = f"...{details[-_MAX_EARLY_EXIT_OUTPUT_CHARS:]}"
if details:
return f"zxdb exited early with code {output.return_code}: {details}"
return f"zxdb exited early with code {output.return_code}"
class CommandHandlerRegistry:
def __init__(self) -> None:
self.handlers: dict[
str, Callable[[BaseRequest[Any]], Awaitable[Response[Any]]]
] = {}
def register(
self,
command: str,
handler: Callable[[BaseRequest[T_Resp]], Awaitable[Response[T_Resp]]],
) -> None:
self.handlers[command] = handler
async def handle(
self, command: str, req: BaseRequest[Any]
) -> Response[Any]:
if command in self.handlers:
try:
return await self.handlers[command](req)
except Exception as e:
return Response(success=False, message=f"Handler error: {e}")
return Response(success=False, message=f"Unknown command: {command}")
class DapEventWaiter:
"""Manages futures for tasks waiting for specific DAP events."""
def __init__(self) -> None:
self._waiters: dict[
tuple[str, int], list[asyncio.Future[dict[str, Any]]]
] = {}
def register_thread_stop(
self, thread_id: int
) -> asyncio.Future[dict[str, Any]]:
fut = asyncio.get_running_loop().create_future()
key = ("stopped", thread_id)
self._waiters.setdefault(key, []).append(fut)
return fut
def unregister_thread_stop(
self, thread_id: int, fut: asyncio.Future[dict[str, Any]]
) -> None:
key = ("stopped", thread_id)
if key in self._waiters:
if fut in self._waiters[key]:
self._waiters[key].remove(fut)
if not self._waiters[key]:
del self._waiters[key]
def notify_thread_stop(self, thread_id: int, event: dict[str, Any]) -> None:
key = ("stopped", thread_id)
if key in self._waiters:
for fut in self._waiters[key]:
if not fut.done():
fut.set_result(event)
del self._waiters[key]
@contextlib.contextmanager
def wait_for_thread_stop(
self, thread_id: int
) -> Generator[asyncio.Future[dict[str, Any]], None, None]:
"""Context manager to automatically register and unregister a waiter."""
fut = self.register_thread_stop(thread_id)
try:
yield fut
finally:
self.unregister_thread_stop(thread_id, fut)
def register_process_stop(
self, process_id: int
) -> asyncio.Future[dict[str, Any]]:
fut = asyncio.get_running_loop().create_future()
key = ("processStopped", process_id)
self._waiters.setdefault(key, []).append(fut)
return fut
def unregister_process_stop(
self, process_id: int, fut: asyncio.Future[dict[str, Any]]
) -> None:
key = ("processStopped", process_id)
if key in self._waiters:
if fut in self._waiters[key]:
self._waiters[key].remove(fut)
if not self._waiters[key]:
del self._waiters[key]
def notify_process_stop(
self, process_id: int, event: dict[str, Any]
) -> None:
key = ("processStopped", process_id)
if key in self._waiters:
for fut in self._waiters[key]:
if not fut.done():
fut.set_result(event)
del self._waiters[key]
@contextlib.contextmanager
def wait_for_process_stop(
self, process_id: int
) -> Generator[asyncio.Future[dict[str, Any]], None, None]:
"""Context manager to automatically register and unregister a process stop waiter."""
fut = self.register_process_stop(process_id)
try:
yield fut
finally:
self.unregister_process_stop(process_id, fut)
@final
class Daemon:
def __init__(
self,
port: int | None,
ready_fd: int | None = None,
session_id: str | None = None,
) -> None:
self.registry = CommandHandlerRegistry()
self.dap_client = ZxdbDapClient()
self.background_tasks: set[asyncio.Task[Any]] = set()
self.idle_readers: set[asyncio.Task[Any]] = set()
self.active_handlers: set[asyncio.Task[Any]] = set()
self.startup_handlers: set[asyncio.Task[Any]] = set()
self.event_queue: asyncio.Queue[Any] = asyncio.Queue()
self.event_waiter = DapEventWaiter()
self.active_breakpoints: dict[str, set[int]] = {}
self.active_watchpoints: dict[str, WatchpointInfo] = {}
self.tracepoints: dict[int, TracepointInfo] = {}
self.next_tracepoint_id: int = 1
# Maps zxdb breakpoint ids to watchpoint data_ids. zxdb reassigns ids on
# every setDataBreakpoints call, so this is rebuilt from each response.
# Used to route async `breakpoint` events; not exposed to clients.
self.watchpoint_ids_by_bp_id: dict[int, str] = {}
self.breakpoint_conditions: dict[tuple[str, int], str] = {}
self.active_function_breakpoints: dict[str, str | None] = {}
self.stop_event = asyncio.Event()
self.shutdown_complete_event = asyncio.Event()
self.dap_ready_event = asyncio.Event()
self.dap_initialized_event = asyncio.Event()
self._command_lock = asyncio.Lock()
self._cleanup_task: asyncio.Task[None] | None = None
# We use a regular dict to store events, keyed by sequence number which
# preserves insertion order. This is relevant because it allows us to
# efficiently prune old events by iterating from the beginning of the
# dict keys and breaking early when we reach a key that shouldn't be
# pruned yet.
self.all_events: dict[int, dict[str, Any]] = {}
self.latest_seq = 0
self.new_event_condition = asyncio.Condition()
self.zxdb_writer: asyncio.StreamWriter | None = None
self.zxdb_reader: asyncio.StreamReader | None = None
self._initial_port = port
self.port = port
self.connect_to_existing: bool | None = None
self.processes: dict[int, Process] = {}
self.threads: dict[int, Thread] = {}
self.next_target_id = 1
self.dap_proc: AsyncCommand | None = None
self._dap_wait_task: asyncio.Task[CommandOutput] | None = None
self.target_repo = TargetRepoManager(self.stop_event)
self.ready_fd = ready_fd
normalized_session_id = session.normalize_session_id(session_id)
self.session_id: str | None = normalized_session_id
self.socket_path: pathlib.Path
if normalized_session_id is not None:
self.socket_path = session.get_daemon_socket_path(
normalized_session_id
)
else:
self.socket_path = constants.UDS_PATH
self._socket_id: tuple[int, int] | None = None
# Statically register handlers.
handlers = [
# keep-sorted start
aspace,
async_backtrace,
attach,
break_req,
console,
continue_req,
detach,
diagnose_hang,
driver_list,
evaluate,
finish,
get_state,
handles,
hello,
mem_read,
modules,
next_req,
pause,
stack_trace,
start,
step_in,
stop,
threads,
tracepoint,
variables,
wait_for_event,
watch_req,
# keep-sorted end
]
for mod in handlers:
handler_fn = functools.partial(mod.handle, self)
self.registry.register(mod.COMMAND_NAME, handler_fn)
# TODO(https://fxbug.dev/509967647): This should be part of a thread object
# abstraction that we're keeping track of.
async def ensure_stopped(self, thread_id: int) -> None:
"""Ensures the thread is stopped. Returns immediately if it is,
otherwise pauses it and waits for the stopped event.
"""
if (thread := self.threads.get(thread_id)) and thread.is_stopped:
return
if not self.zxdb_writer:
raise Exception("Not connected to zxdb DAP server")
with self.event_waiter.wait_for_thread_stop(thread_id) as fut:
await self.dap_client.pause_thread(
PauseArguments(threadId=thread_id)
)
try:
await asyncio.wait_for(fut, timeout=10.0)
return
except asyncio.TimeoutError:
raise Exception(
f"Timed out waiting for thread {thread_id} to stop"
)
async def ensure_process_stopped(self, pid: int) -> None:
"""Ensures the process is stopped. Returns immediately if it is,
otherwise pauses it and waits for the processStopped event.
"""
if (proc := self.processes.get(pid)) and proc.all_threads_stopped:
return
if not self.zxdb_writer:
raise Exception("Not connected to zxdb DAP server")
with self.event_waiter.wait_for_process_stop(pid) as fut:
resp = await self.dap_client.zxdb_pause_process(
ZxdbPauseArguments(process_id=pid)
)
if not resp.success:
raise Exception(
resp.message or f"Failed to pause process {pid}"
)
try:
await asyncio.wait_for(fut, timeout=10.0)
return
except asyncio.TimeoutError:
raise Exception(f"Timed out waiting for process {pid} to stop")
def _check_already_running(self, req: StartRequest) -> Response[Any] | None:
if not self.dap_ready_event.is_set():
return None
if (
req.port is not None
and self.port is not None
and req.port != self.port
):
return Response(
success=False,
message=(
f"Daemon already running on port {self.port}, "
f"cannot switch to {req.port}"
),
)
if req.connect != self.connect_to_existing:
return Response(
success=False,
message=(
f"Daemon already running with "
f"connect_to_existing={self.connect_to_existing}, "
f"cannot switch to {req.connect}"
),
)
return Response(
success=True,
body={
"uds_path": str(self.socket_path),
"session_id": self.session_id,
},
message="Daemon already started",
)
def _reset_session_state(self) -> None:
while True:
try:
self.event_queue.get_nowait()
self.event_queue.task_done()
except asyncio.QueueEmpty:
break
self.clear_all_processes()
self.all_events.clear()
self.latest_seq = 0
self.dap_initialized_event.clear()
self.dap_ready_event.clear()
self.port = self._initial_port
self.connect_to_existing = None
async def _close_zxdb_streams(self) -> None:
if self.zxdb_writer is not None:
self.zxdb_writer.close()
with contextlib.suppress(OSError):
async with asyncio.timeout(_TEARDOWN_GRACE_PERIOD_SECS):
await self.zxdb_writer.wait_closed()
self.zxdb_writer = None
self.zxdb_reader = None
async def _cleanup_dap_proc(
self, dap_wait_task: asyncio.Task[CommandOutput] | None
) -> None:
if self.dap_proc is not None:
dap_proc = self.dap_proc
self.dap_proc = None
await _reap_dap_proc(dap_proc, dap_wait_task)
elif dap_wait_task is not None and not dap_wait_task.done():
dap_wait_task.cancel()
await asyncio.gather(dap_wait_task, return_exceptions=True)
async def _cleanup_session_resources_impl(self) -> None:
await self.dap_client.close()
dap_wait_task = self._dap_wait_task
self._dap_wait_task = None
tasks = tuple(
task for task in self.background_tasks if task is not dap_wait_task
)
for task in tasks:
task.cancel()
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
self.background_tasks.clear()
self._reset_session_state()
await self._close_zxdb_streams()
results = await asyncio.gather(
self._cleanup_dap_proc(dap_wait_task),
self.target_repo.stop(),
return_exceptions=True,
)
for res in results:
if isinstance(res, Exception):
logger.warning("Session resource cleanup step failed: %s", res)
elif isinstance(res, BaseException):
raise res
async def cleanup_session_resources(self) -> None:
if self._cleanup_task is None or self._cleanup_task.done():
self._cleanup_task = asyncio.create_task(
self._cleanup_session_resources_impl()
)
self._cleanup_task.add_done_callback(_consume_task_exception)
await asyncio.shield(self._cleanup_task)
async def _cleanup_failed_dap_start(
self,
*,
dap_wait_task: asyncio.Task[CommandOutput] | None,
stop_task: asyncio.Task[bool] | None,
) -> None:
dap_proc_to_reap = self.dap_proc
self.dap_proc = None
if (
dap_proc_to_reap is None
and dap_wait_task is not None
and not dap_wait_task.done()
):
dap_wait_task.cancel()
async def _finish_start_cleanup() -> None:
if stop_task is not None:
await asyncio.gather(stop_task, return_exceptions=True)
if dap_proc_to_reap is not None:
await _reap_dap_proc(dap_proc_to_reap, dap_wait_task)
elif dap_wait_task is not None and not dap_wait_task.done():
await asyncio.gather(dap_wait_task, return_exceptions=True)
cleanup_task = asyncio.create_task(_finish_start_cleanup())
await cleanup.await_shielded_cleanup(
cleanup_task, logger, "DAP startup cleanup failed"
)
def _build_dap_connect_args(self) -> Sequence[str]:
args = (
"debug",
"connect",
"--new-agent",
"--",
"--enable-debug-adapter",
f"--signal-when-ready={os.getpid()}",
)
if self.port is not None:
return (*args, "--debug-adapter-port", str(self.port))
return args
async def _start_dap_server(self) -> Response[Any] | None:
try:
await self.target_repo.ensure_serving()
except TargetRepoError as e:
return Response(success=False, message=str(e))
if self.stop_event.is_set():
return Response(success=False, message="Daemon stopping")
ffx_cmd = FfxCmd()
args = self._build_dap_connect_args()
loop = asyncio.get_running_loop()
signal_fut = loop.create_future()
def handle_sigusr1() -> None:
if not signal_fut.done():
signal_fut.set_result(True)
dap_wait_task: asyncio.Task[CommandOutput] | None = None
stop_task: asyncio.Task[bool] | None = None
dap_started = False
try:
loop.add_signal_handler(signal.SIGUSR1, handle_sigusr1)
try:
self.dap_proc = await ffx_cmd.start(*args)
except Exception as e:
return Response(
success=False, message=f"Failed to start zxdb: {e}"
)
if self.stop_event.is_set():
return Response(success=False, message="Daemon stopping")
dap_wait_task = asyncio.create_task(
self.dap_proc.run_to_completion()
)
stop_task = asyncio.create_task(self.stop_event.wait())
done, _ = await asyncio.wait(
(signal_fut, dap_wait_task, stop_task),
timeout=_DAP_READY_TIMEOUT_SECS,
return_when=asyncio.FIRST_COMPLETED,
)
if not done:
return Response(
success=False,
message=(
f"Timed out waiting {_DAP_READY_TIMEOUT_SECS}s for "
"zxdb debug adapter to become ready"
),
)
if stop_task in done and self.stop_event.is_set():
return Response(success=False, message="Daemon stopping")
if dap_wait_task in done:
err_msg = _format_early_exit_message(dap_wait_task.result())
print(err_msg)
return Response(success=False, message=err_msg)
if signal_fut in done:
print("Received SIGUSR1 from zxdb.")
# We don't cancel dap_wait_task here because we want it to
# keep consuming output from zxdb in the background to prevent
# unbounded memory growth.
self.background_tasks.add(dap_wait_task)
self._dap_wait_task = dap_wait_task
dap_started = True
return None
raise RuntimeError("Unexpected asyncio.wait completion state")
finally:
loop.add_signal_handler(signal.SIGUSR1, _ignore_sigusr1)
if not signal_fut.done():
signal_fut.cancel()
if stop_task is not None and not stop_task.done():
stop_task.cancel()
if dap_started:
if stop_task is not None:
await asyncio.gather(stop_task, return_exceptions=True)
else:
await self._cleanup_failed_dap_start(
dap_wait_task=dap_wait_task,
stop_task=stop_task,
)
def _cleanup_runtime_files(self) -> None:
socket_utils.cleanup_daemon_socket(
self.socket_path, self._socket_id, self.session_id
)
async def _bind_unix_server(self) -> asyncio.AbstractServer:
(
server,
self.socket_path,
self._socket_id,
) = await socket_utils.bind_daemon_unix_server(
self.handle_uds_client,
self.socket_path,
self.session_id,
)
return server
def _notify_ready_fd(self) -> None:
if self.ready_fd is None:
return
try:
os.write(self.ready_fd, b"1")
os.close(self.ready_fd)
except OSError as e:
print(f"Failed to write to ready-fd: {e}")
async def _teardown_resources(self) -> None:
startup_tasks = tuple(self.startup_handlers)
for task in startup_tasks:
task.cancel()
if startup_tasks:
await asyncio.gather(*startup_tasks, return_exceptions=True)
remaining_handlers = tuple(
task
for task in self.active_handlers
if task not in self.startup_handlers
)
if remaining_handlers:
_done, pending = await asyncio.wait(
remaining_handlers,
timeout=_TEARDOWN_GRACE_PERIOD_SECS,
)
for task in pending:
task.cancel()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
if self._cleanup_task is not None and not self._cleanup_task.done():
try:
await asyncio.shield(self._cleanup_task)
except Exception as e:
logger.warning("Session cleanup during teardown failed: %s", e)
if (
self.connect_to_existing
and self.zxdb_writer is not None
and self.dap_ready_event.is_set()
):
try:
args = ZxdbDetachArguments(all=True)
async with asyncio.timeout(_TEARDOWN_GRACE_PERIOD_SECS):
await self.dap_client.zxdb_detach(args)
except Exception:
pass
try:
await self.cleanup_session_resources()
except Exception as e:
logger.warning("Session cleanup during teardown failed: %s", e)
async def _shutdown_teardown(
self, server: asyncio.AbstractServer | None
) -> None:
async with self.new_event_condition:
self.new_event_condition.notify_all()
try:
await self._teardown_resources()
except Exception as e:
logger.warning("Failed to tear down daemon resources: %s", e)
if server is None:
return
try:
# Unlink the socket and clean up the empty session directory before
# closing the listener and setting shutdown_complete_event so a
# sequential `stop && start` observes the cleaned-up runtime directory
# without an ECONNREFUSED or inode-reuse window.
self._cleanup_runtime_files()
except (OSError, ValueError) as e:
logger.warning(
"Failed to clean up runtime files for %s: %s",
self.socket_path,
e,
)
server.close()
# Set shutdown_complete_event first to allow handle_uds_client to unblock
# and close client connection. In Python 3.12+, server.wait_closed() blocks
# until all connections drop; doing this out of order causes a mutual deadlock.
self.shutdown_complete_event.set()
if idle_readers := tuple(self.idle_readers):
for task in idle_readers:
task.cancel()
await asyncio.gather(*idle_readers, return_exceptions=True)
try:
await asyncio.wait_for(
server.wait_closed(), timeout=_SERVER_WAIT_CLOSED_TIMEOUT_SECS
)
except TimeoutError:
if hasattr(server, "abort_clients"):
server.abort_clients()
with contextlib.suppress(TimeoutError, Exception):
await asyncio.wait_for(
server.wait_closed(),
timeout=_SERVER_WAIT_CLOSED_TIMEOUT_SECS,
)
except Exception as e:
logger.warning("Failed waiting for server close: %s", e)
async def run(self) -> int:
server: asyncio.AbstractServer | None = None
loop = asyncio.get_running_loop()
registered_signals: list[signal.Signals] = []
try:
server = await self._bind_unix_server()
print(f"Daemon listening on {self.socket_path}")
for sig, handler in (
(signal.SIGINT, self.stop_event.set),
(signal.SIGTERM, self.stop_event.set),
(signal.SIGUSR1, _ignore_sigusr1),
):
loop.add_signal_handler(sig, handler)
registered_signals.append(sig)
self._notify_ready_fd()
# Wait for stop event (sent by handle_stop)
await self.stop_event.wait()
finally:
try:
self.stop_event.set()
await cleanup.await_shielded_cleanup(
asyncio.create_task(self._shutdown_teardown(server)),
logger,
"Daemon shutdown teardown failed",
)
finally:
for sig in registered_signals:
loop.remove_signal_handler(sig)
return 0
async def _connect_to_dap(self) -> bool:
connected = False
for _ in range(20):
if self.stop_event.is_set():
return False
try:
(
self.zxdb_reader,
self.zxdb_writer,
) = await asyncio.open_connection("localhost", self.port)
connected = True
print("Connected to DAP server.")
break
except Exception:
try:
await asyncio.wait_for(self.stop_event.wait(), timeout=1.0)
return False
except asyncio.TimeoutError:
pass
if not connected:
print("Failed to connect to DAP server after polling.")
return False
assert self.zxdb_reader is not None
assert self.zxdb_writer is not None
# Run DAP client
self.dap_client.run(
self.zxdb_reader, self.zxdb_writer, self.event_queue
)
self.background_tasks.add(asyncio.create_task(self._process_events()))
await self.dap_client.initialize(
InitializeArguments(adapterID="zxdb"),
)
# Wait for the "initialized" event from the DAP server.
try:
await asyncio.wait_for(
self.dap_initialized_event.wait(), timeout=5.0
)
print("Received 'initialized' event from DAP server.")
except asyncio.TimeoutError:
print("Timed out waiting for 'initialized' event from DAP server.")
return False
except Exception as e:
print(f"Error waiting for 'initialized' event: {e}")
return False
self.dap_ready_event.set()
return True
async def _dispatch_locked(self, req: BaseRequest[Any]) -> Response[Any]:
async with self._command_lock:
if self.stop_event.is_set():
return Response(
success=False, message="Daemon is shutting down"
)
if self._cleanup_task is not None and not self._cleanup_task.done():
await asyncio.shield(self._cleanup_task)
if self.stop_event.is_set():
return Response(
success=False, message="Daemon is shutting down"
)
return await self.registry.handle(req.command, req)
async def _run_start_with_disconnect_watch(
self,
req: BaseRequest[Any],
reader: asyncio.StreamReader,
) -> Response[Any] | None:
handler_task = asyncio.create_task(self._dispatch_locked(req))
disconnect_task = asyncio.create_task(
_wait_for_client_disconnect(reader)
)
try:
done, _ = await asyncio.wait(
(handler_task, disconnect_task),
return_when=asyncio.FIRST_COMPLETED,
)
if handler_task in done:
return handler_task.result()
return None
finally:
if not disconnect_task.done():
disconnect_task.cancel()
if not handler_task.done():
handler_task.cancel()
deferred_cancel = await _await_task_deferring_cancel(handler_task)
disconnect_cancel = await _await_task_deferring_cancel(
disconnect_task
)
if deferred_cancel is not None:
raise deferred_cancel
if disconnect_cancel is not None:
raise disconnect_cancel
async def handle_uds_client(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
# This function is only called when there is a new connection. Each
# connection is only expected to send a single request so there is no
# looping to do here. At the start of a new connection we store this
# task so that the main task can be sure that there are no dangling
# connections during shutdown.
current_task = asyncio.current_task()
assert current_task is not None
self.idle_readers.add(current_task)
try:
line = await reader.readline()
self.idle_readers.discard(current_task)
if not line:
return
req = deserialize_request(line.decode("utf-8"))
# To avoid deadlocks during shutdown, do not add the "stop" command
# handler task to active_handlers. The main loop in _run_dap_session
# waits for all active_handlers to complete before shutting down.
# If the stop handler task waits for shutdown inside active_handlers,
# it would wait for itself to complete.
if req.command != "stop":
self.active_handlers.add(current_task)
if req.command == start.COMMAND_NAME:
self.startup_handlers.add(current_task)
if req.ack_seq is not None:
# Note: this relies on the insertion order of dictionaries being preserved.
for seq in list(self.all_events.keys()):
if seq <= req.ack_seq:
del self.all_events[seq]
else:
break
resp: Response[Any]
if req.command != stop.COMMAND_NAME and self.stop_event.is_set():
resp = Response(
success=False, message="Daemon is shutting down"
)
elif req.command == start.COMMAND_NAME:
start_resp = await self._run_start_with_disconnect_watch(
req, reader
)
if start_resp is None:
return
resp = start_resp
elif req.command not in (
wait_for_event.COMMAND_NAME,
hello.COMMAND_NAME,
stop.COMMAND_NAME,
):
resp = await self._dispatch_locked(req)
else:
resp = await self.registry.handle(req.command, req)
# Add events that have transpired since |last_seen_seq|.
if req.last_seen_seq is not None:
resp.events = []
for seq in range(req.last_seen_seq + 1, self.latest_seq + 1):
if seq in self.all_events:
resp.events.append(self.all_events[seq])
if (
await _send_uds_response(writer, resp)
and req.command == stop.COMMAND_NAME
):
await self.shutdown_complete_event.wait()
except asyncio.CancelledError:
raise
except Exception as e:
await _send_uds_response(
writer, Response(success=False, message=f"Error: {e}")
)
finally:
self.idle_readers.discard(current_task)
self.active_handlers.discard(current_task)
self.startup_handlers.discard(current_task)
writer.close()
with contextlib.suppress(OSError):
await writer.wait_closed()
def get_or_create_process(self, process_id: int, name: str = "") -> Process:
"""Retrieves an existing Process or registers a new one."""
if process_id not in self.processes:
target_id = self.next_target_id
self.next_target_id += 1
self.processes[process_id] = Process(
id=process_id, name=name, target_id=target_id
)
elif name:
self.processes[process_id].name = name
return self.processes[process_id]
def resolve_process_id(
self, pid: int | None
) -> tuple[int | None, str | None]:
"""Resolves and validates a target process KOID against `self.processes`."""
if pid is not None:
if pid not in self.processes:
return None, f"Process {pid} not found"
return pid, None
if len(self.processes) == 1:
return next(iter(self.processes.keys())), None
if len(self.processes) > 1:
return (
None,
"Multiple processes active; please specify a PID with"
" --pid / -p",
)
return None, None
def scope_console_command(self, command: str, pid: int | None) -> str:
"""Prefixes `command` with `process <target_id>` when `pid` is known."""
if pid is not None and (proc := self.processes.get(pid)) is not None:
return f"process {proc.target_id} {command}"
return command
def get_or_create_thread(
self,
thread_id: int,
name: str = "",
process_id: int | None = None,
is_stopped: bool | None = None,
) -> Thread:
"""Retrieves an existing Thread or registers a new one with its owning Process."""
process = (
self.get_or_create_process(process_id)
if process_id is not None
else None
)
if thread_id not in self.threads:
thread = Thread(
id=thread_id,
name=name,
process=process,
is_stopped=is_stopped if is_stopped is not None else False,
)
self.threads[thread_id] = thread
if process:
process.threads[thread_id] = thread
else:
thread = self.threads[thread_id]
if name:
thread.name = name
if is_stopped is not None:
thread.is_stopped = is_stopped
if process and thread.process != process:
if thread.process:
thread.process.threads.pop(thread_id, None)
thread.process = process
process.threads[thread_id] = thread
return thread
def update_thread_cache(self, threads: list[Any]) -> None:
"""Synchronizes thread and process state with authoritative DAP thread list.
Inserts new threads and updates process associations, and prunes stale thread IDs.
"""
valid_thread_ids: set[int] = set()
for thread in threads:
thread_id = getattr(thread, "id", None)
if thread_id is not None:
valid_thread_ids.add(thread_id)
name = getattr(thread, "name", "")
process_id = getattr(thread, "process_id", None)
self.get_or_create_thread(
thread_id, name=name, process_id=process_id
)
stale_thread_ids = [
tid for tid in self.threads if tid not in valid_thread_ids
]
for tid in stale_thread_ids:
thread = self.threads.pop(tid, None)
if thread and thread.process:
thread.process.threads.pop(tid, None)
def clear_process(self, process_id: int) -> bool:
"""Clears cached state for a detached or exited process.
Returns True if any process-bound tracepoints were evicted.
"""
process = self.processes.pop(process_id, None)
if process:
for tid in list(process.threads.keys()):
self.threads.pop(tid, None)
prefix = f"{process_id}:"
removed_ids = [
data_id
for data_id in self.active_watchpoints
if data_id.startswith(prefix)
]
for data_id in removed_ids:
self.active_watchpoints.pop(data_id, None)
self.watchpoint_ids_by_bp_id = {
bp_id: data_id
for bp_id, data_id in self.watchpoint_ids_by_bp_id.items()
if data_id in self.active_watchpoints
}
removed_tp_ids = [
tp_id
for tp_id, tp in self.tracepoints.items()
if tp.data_id is not None and tp.data_id.startswith(prefix)
]
for tp_id in removed_tp_ids:
self.tracepoints.pop(tp_id, None)
return bool(removed_tp_ids)
def clear_all_processes(self, evict_tracepoints: bool = True) -> bool:
"""Clears all cached process and thread state.
When evict_tracepoints is True, also removes process-bound (dataId)
tracepoints. Returns True if any tracepoints were evicted.
"""
self.processes.clear()
self.threads.clear()
self.next_target_id = 1
self.active_watchpoints.clear()
self.watchpoint_ids_by_bp_id.clear()
if not evict_tracepoints:
return False
removed_tp_ids = [
tp_id
for tp_id, tp in self.tracepoints.items()
if tp.data_id is not None
]
for tp_id in removed_tp_ids:
self.tracepoints.pop(tp_id, None)
return bool(removed_tp_ids)
def set_watchpoints(
self,
watchpoints: dict[str, WatchpointInfo],
breakpoints: list[Breakpoint],
) -> None:
"""Replaces the active watchpoints after a successful setDataBreakpoints.
`breakpoints` is the response array, which DAP guarantees to be in the
same order as the request built from `watchpoints`. zxdb recreates every
data breakpoint on each call and assigns new ids, so the status of every
watchpoint and the id map are refreshed, not just the changed entry.
"""
self.watchpoint_ids_by_bp_id = {}
for wp, bp in zip(watchpoints.values(), breakpoints):
wp.verified = bp.verified
wp.message = bp.message
if bp.id is not None:
self.watchpoint_ids_by_bp_id[bp.id] = wp.data_id
self.active_watchpoints = watchpoints
def update_resumed_threads(
self,
thread_id: int | None,
single_thread: bool = False,
) -> None:
"""Updates thread stopped state when execution resumes."""
if single_thread and thread_id is None:
raise ValueError(
"Single thread resumed without providing thread_id!"
)
thread = self.threads.get(thread_id) if thread_id is not None else None
if single_thread:
if thread is not None:
thread.resume()
else:
# When single_thread is False, all threads in the system were
# resumed via a Continue request. Also iterate self.threads
# directly so threads recorded before their parent process is
# known (process_id=None) have their stopped state cleared.
for p in self.processes.values():
p.resume()
for t in self.threads.values():
t.resume()
def _handle_breakpoint_changed(self, body: dict[str, Any]) -> None:
"""Handles DAP `breakpoint` events with reason "changed".
zxdb sends these asynchronously when a breakpoint's install status
changes after the original setDataBreakpoints response, e.g. when
DebugAgent later fails to install a hardware watchpoint. Updates the
matching watchpoint so get-state reflects the current status.
"""
if body.get("reason") != "changed":
return
bp = body.get("breakpoint") or {}
bp_id = bp.get("id")
if bp_id is None:
return
data_id = self.watchpoint_ids_by_bp_id.get(bp_id)
wp = self.active_watchpoints.get(data_id) if data_id else None
if wp is None:
return
wp.verified = bool(bp.get("verified", False))
wp.message = bp.get("message")
# TODO(https://fxbug.dev/545555364): Support event validation in this _process_events function.
async def _process_events(self) -> None:
allowed_events = {
"stopped",
"processStopped",
"exited",
"terminated",
"thread",
"process",
"detached",
"zxdb.Tracepoint",
}
while True:
event = await self.event_queue.get()
if event.get("type") == READER_STOPPED_EVENT:
exc = event.get("exception")
if exc is not None:
logger.warning(
f"DAP reader background task stopped with error: {exc}"
)
break
# Internal daemon actions on all events
event_name = event.get("event")
body = event.get("body") or {}
match event_name:
case "initialized":
self.dap_initialized_event.set()
case "stopped":
thread_id = body.get("threadId")
if thread_id is not None:
thread = self.get_or_create_thread(thread_id)
thread.is_stopped = True
self.event_waiter.notify_thread_stop(thread_id, event)
case "processStopped":
pid = body.get("processId")
if pid is not None:
self.get_or_create_process(pid)
if threads := body.get("threads"):
for tid in threads:
thread = self.get_or_create_thread(
tid, process_id=pid
)
thread.is_stopped = True
self.event_waiter.notify_process_stop(pid, event)
case "thread":
thread_id = body.get("threadId")
reason = body.get("reason")
if reason == "exited" and thread_id is not None:
if thread_id in self.threads:
exited_thread = self.threads.pop(thread_id)
if exited_thread.process is not None:
exited_thread.process.threads.pop(
thread_id, None
)
else:
process_id = body.get("processId")
is_stopped = body.get("isStopped")
if thread_id is not None:
self.get_or_create_thread(
thread_id,
process_id=process_id,
is_stopped=is_stopped,
)
case "breakpoint":
self._handle_breakpoint_changed(body)
case "zxdb.Tracepoint":
tp_id = body.get("tracepointId")
if tp_id is not None and tp_id in self.tracepoints:
tp = self.tracepoints[tp_id]
tp.hit_count = body.get("hitCount", tp.hit_count + 1)
if body.get("autoDisabled", False):
tp.enabled = False
tp.auto_disabled = True
case "process":
pid = body.get("systemProcessId")
name = str(body.get("name") or "")
if pid is not None:
self.get_or_create_process(pid, name=name)
case "detached":
pid = body.get("pid") or body.get("processId")
evicted = (
self.clear_process(pid)
if pid is not None
else self.clear_all_processes()
)
if evicted and self.zxdb_writer:
with contextlib.suppress(Exception):
await tracepoint.sync_tracepoints_with_dap(self)
case "exited" | "terminated":
# These events carry no process ID, so one exit must not
# delete dataId tracepoints that belong to processes that
# are still alive. The server reports a tracepoint for a
# dead process as unverified on the next sync.
self.clear_all_processes(evict_tracepoints=False)
# Only enqueue and sequence allowed events for surfacing to the CLI client
if event.get("event") in allowed_events:
self.latest_seq += 1
event["seq"] = self.latest_seq
self.all_events[self.latest_seq] = event
# Enforce max size
if len(self.all_events) > MAX_EVENT_HISTORY_SIZE:
# Pop the oldest item. Dict keys are in insertion order.
oldest_seq = next(iter(self.all_events))
del self.all_events[oldest_seq]
async with self.new_event_condition:
self.new_event_condition.notify_all()