Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
26
crates/luxe-dap/Cargo.toml
Normal file
26
crates/luxe-dap/Cargo.toml
Normal file
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "luxe-dap"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Debug Adapter Protocol client for Luxe: breakpoints, stepping, and variable inspection"
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
# Allowed edges: depends on luxe-core only (sibling of luxe-lsp).
|
||||
# Provides a native Debug Adapter Protocol client + the `debug` tool.
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.0" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["net"] }
|
||||
async-trait = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
408
crates/luxe-dap/src/adapter.rs
Normal file
408
crates/luxe-dap/src/adapter.rs
Normal file
@@ -0,0 +1,408 @@
|
||||
//! Debug-adapter registry — resolves a program to a DAP adapter command + launch arguments.
|
||||
//!
|
||||
//! All supported adapters speak DAP over **stdio** (`codelldb` with no args, `python -m
|
||||
//! debugpy.adapter`, `lldb-dap`, `gdb --interpreter=dap`), so the client needs a single transport.
|
||||
//! Compiled languages debug a *binary*, so the adapter is chosen by explicit request or by a
|
||||
//! native-first fallback rather than by source extension.
|
||||
|
||||
use crate::client::DapError;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::path::Path;
|
||||
|
||||
/// How an adapter shapes its `launch` request arguments.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AdapterKind {
|
||||
/// Python via debugpy.
|
||||
Debugpy,
|
||||
/// Native (Rust/C/C++) via CodeLLDB or lldb-dap.
|
||||
Lldb,
|
||||
/// Native via `gdb --interpreter=dap`.
|
||||
Gdb,
|
||||
/// Go via Delve (`dlv dap`).
|
||||
Delve,
|
||||
}
|
||||
|
||||
/// How the client connects to the adapter's DAP stream.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
/// DAP over the adapter's stdio (debugpy, CodeLLDB, lldb-dap, gdb).
|
||||
Stdio,
|
||||
/// The adapter dials in to us over TCP; `placeholder` in the command is replaced with our
|
||||
/// loopback `host:port` (Delve `--client-addr`, js-debug).
|
||||
TcpDialIn { placeholder: String },
|
||||
}
|
||||
|
||||
/// A resolved debug adapter: how to launch the adapter process + how to shape `launch` args.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AdapterSpec {
|
||||
/// Stable adapter id (`debugpy`, `codelldb`, `lldb-dap`, `gdb`, `dlv`).
|
||||
pub id: String,
|
||||
/// Adapter command (the DAP server itself).
|
||||
pub command: Vec<String>,
|
||||
/// Launch-argument dialect.
|
||||
pub kind: AdapterKind,
|
||||
/// How the client connects to the adapter.
|
||||
pub transport: Transport,
|
||||
}
|
||||
|
||||
impl AdapterSpec {
|
||||
/// Build the `launch` request arguments for a target program.
|
||||
pub fn launch_arguments(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
cwd: &str,
|
||||
stop_on_entry: bool,
|
||||
) -> Value {
|
||||
match self.kind {
|
||||
AdapterKind::Debugpy => json!({
|
||||
"request": "launch",
|
||||
"program": program,
|
||||
"args": args,
|
||||
"console": "internalConsole",
|
||||
"cwd": cwd,
|
||||
"stopOnEntry": stop_on_entry,
|
||||
}),
|
||||
AdapterKind::Lldb => json!({
|
||||
"request": "launch",
|
||||
"program": program,
|
||||
"args": args,
|
||||
"cwd": cwd,
|
||||
"stopOnEntry": stop_on_entry,
|
||||
}),
|
||||
AdapterKind::Gdb => json!({
|
||||
"request": "launch",
|
||||
"program": program,
|
||||
"args": args,
|
||||
"cwd": cwd,
|
||||
"stopAtBeginningOfMainSubprogram": stop_on_entry,
|
||||
}),
|
||||
// Delve `mode: debug` builds + runs the package/file at `program`.
|
||||
AdapterKind::Delve => json!({
|
||||
"request": "launch",
|
||||
"mode": "debug",
|
||||
"program": program,
|
||||
"args": args,
|
||||
"cwd": cwd,
|
||||
"stopOnEntry": stop_on_entry,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the `attach` request arguments: by `port` (debugpy connect) or `pid` (native).
|
||||
pub fn attach_arguments(&self, pid: Option<i64>, port: Option<i64>) -> Value {
|
||||
match self.kind {
|
||||
AdapterKind::Debugpy => {
|
||||
if let Some(port) = port {
|
||||
json!({ "request": "attach", "connect": { "host": "127.0.0.1", "port": port } })
|
||||
} else {
|
||||
json!({ "request": "attach", "processId": pid })
|
||||
}
|
||||
}
|
||||
AdapterKind::Lldb | AdapterKind::Gdb => {
|
||||
json!({ "request": "attach", "pid": pid })
|
||||
}
|
||||
AdapterKind::Delve => {
|
||||
json!({ "request": "attach", "mode": "local", "processId": pid })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Placeholder in the Delve command replaced with our loopback `host:port` for dial-in.
|
||||
const DAP_ADDR: &str = "${DAP_ADDR}";
|
||||
|
||||
// === Config-driven custom adapters ===
|
||||
|
||||
/// Launch-argument dialect a custom adapter reuses (most DAP adapters fit one of these shapes).
|
||||
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Dialect {
|
||||
Debugpy,
|
||||
Lldb,
|
||||
Gdb,
|
||||
Delve,
|
||||
}
|
||||
|
||||
impl Dialect {
|
||||
fn kind(self) -> AdapterKind {
|
||||
match self {
|
||||
Dialect::Debugpy => AdapterKind::Debugpy,
|
||||
Dialect::Lldb => AdapterKind::Lldb,
|
||||
Dialect::Gdb => AdapterKind::Gdb,
|
||||
Dialect::Delve => AdapterKind::Delve,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a custom adapter is reached.
|
||||
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TransportConfig {
|
||||
/// DAP over the adapter's stdio (default).
|
||||
#[default]
|
||||
Stdio,
|
||||
/// The adapter dials in to us over TCP (include an address placeholder in `command`).
|
||||
TcpDialIn,
|
||||
}
|
||||
|
||||
/// A user-configured adapter from `~/.config/luxe/debug-adapters.json`. Lets users (or a model
|
||||
/// working in Luxe) add debuggers for more languages without a code change, reusing a built-in
|
||||
/// launch dialect.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CustomAdapter {
|
||||
/// Stable id, selectable via the debug tool's `adapter` arg.
|
||||
pub id: String,
|
||||
/// Adapter command (argv). For `tcp_dial_in`, include the address placeholder.
|
||||
pub command: Vec<String>,
|
||||
/// Source extensions this adapter auto-handles (leading dot optional), e.g. `["rb"]`.
|
||||
#[serde(default)]
|
||||
pub extensions: Vec<String>,
|
||||
/// Which built-in launch dialect to use.
|
||||
pub dialect: Dialect,
|
||||
/// Transport (default stdio).
|
||||
#[serde(default)]
|
||||
pub transport: TransportConfig,
|
||||
/// For `tcp_dial_in`: the substring in `command` replaced with our `host:port`
|
||||
/// (default `${DAP_ADDR}`).
|
||||
#[serde(default)]
|
||||
pub addr_placeholder: Option<String>,
|
||||
}
|
||||
|
||||
/// A resolved custom adapter: its spec plus the extensions it auto-handles.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConfiguredAdapter {
|
||||
pub spec: AdapterSpec,
|
||||
pub extensions: Vec<String>,
|
||||
}
|
||||
|
||||
impl ConfiguredAdapter {
|
||||
/// Build a resolved adapter from its config entry.
|
||||
pub fn from_custom(custom: &CustomAdapter) -> Self {
|
||||
let transport = match custom.transport {
|
||||
TransportConfig::Stdio => Transport::Stdio,
|
||||
TransportConfig::TcpDialIn => Transport::TcpDialIn {
|
||||
placeholder: custom
|
||||
.addr_placeholder
|
||||
.clone()
|
||||
.unwrap_or_else(|| DAP_ADDR.to_string()),
|
||||
},
|
||||
};
|
||||
ConfiguredAdapter {
|
||||
spec: AdapterSpec {
|
||||
id: custom.id.clone(),
|
||||
command: custom.command.clone(),
|
||||
kind: custom.dialect.kind(),
|
||||
transport,
|
||||
},
|
||||
extensions: custom
|
||||
.extensions
|
||||
.iter()
|
||||
.map(|e| e.trim_start_matches('.').to_string())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The shipped default debug adapters, using the same `CustomAdapter` schema as user config, so
|
||||
/// built-in + user adapters share one parse + resolution path.
|
||||
const DEFAULT_ADAPTERS_JSON: &str = include_str!("default-debug-adapters.json");
|
||||
|
||||
/// The shipped built-in debug adapters (debugpy, codelldb, lldb-dap, gdb, dlv), for
|
||||
/// status/introspection surfaces like the `/debug` command.
|
||||
pub fn builtin_adapters() -> Vec<ConfiguredAdapter> {
|
||||
default_adapters()
|
||||
}
|
||||
|
||||
/// Parse the bundled default adapters. Compile-time-embedded + covered by
|
||||
/// `default_adapters_bundle_parses`, so a failure is a build-time bug, never a runtime path.
|
||||
fn default_adapters() -> Vec<ConfiguredAdapter> {
|
||||
let customs: Vec<CustomAdapter> = serde_json::from_str(DEFAULT_ADAPTERS_JSON)
|
||||
.expect("bundled default-debug-adapters.json must be valid");
|
||||
customs.iter().map(ConfiguredAdapter::from_custom).collect()
|
||||
}
|
||||
|
||||
/// Whether any debug adapter — user-configured or built-in — is actually installed.
|
||||
///
|
||||
/// The `debug` tool is the most expensive schema in the set, and it is dead weight on a machine
|
||||
/// with no adapter: every call can only answer "no debug adapter found". Registration is gated on
|
||||
/// this so that cost is paid only where the capability exists. Nothing is hidden by doing so —
|
||||
/// unlike deferring a working tool, an absent adapter means there is no debugging to offer.
|
||||
pub fn any_adapter_available(custom: &[ConfiguredAdapter]) -> bool {
|
||||
custom
|
||||
.iter()
|
||||
.chain(default_adapters().iter())
|
||||
.any(|c| c.spec.command.first().is_some_and(|program| on_path(program)))
|
||||
}
|
||||
|
||||
/// Resolves the adapter for a target program.
|
||||
///
|
||||
/// An explicit `adapter` id wins (user adapters shadow built-ins). Otherwise an adapter whose
|
||||
/// `extensions` match the program's extension wins (user first, then built-in — e.g. `.py`→debugpy,
|
||||
/// `.go`→dlv), and everything else (a compiled binary) takes the first installed native adapter:
|
||||
/// CodeLLDB, then lldb-dap, then gdb.
|
||||
pub fn resolve(
|
||||
program: &str,
|
||||
adapter: Option<&str>,
|
||||
custom: &[ConfiguredAdapter],
|
||||
) -> Result<AdapterSpec, DapError> {
|
||||
let builtin = default_adapters();
|
||||
// User adapters take precedence over built-ins with the same id/extension.
|
||||
let ordered = || custom.iter().chain(builtin.iter());
|
||||
|
||||
if let Some(id) = adapter {
|
||||
return ordered()
|
||||
.find(|c| c.spec.id == id)
|
||||
.map(|c| c.spec.clone())
|
||||
.ok_or_else(|| DapError::AdapterUnavailable(format!("unknown adapter '{id}'")))
|
||||
.and_then(ensure_installed);
|
||||
}
|
||||
|
||||
if let Some(ext) = Path::new(program).extension().and_then(|e| e.to_str()) {
|
||||
if let Some(found) = ordered().find(|c| c.extensions.iter().any(|e| e == ext)) {
|
||||
return ensure_installed(found.spec.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// Compiled binary: first installed native adapter (Delve is Go-source-specific, excluded).
|
||||
builtin
|
||||
.iter()
|
||||
.filter(|c| matches!(c.spec.kind, AdapterKind::Lldb | AdapterKind::Gdb))
|
||||
.find(|c| on_path(&c.spec.command[0]))
|
||||
.map(|c| c.spec.clone())
|
||||
.ok_or_else(|| {
|
||||
DapError::AdapterUnavailable(
|
||||
"no native debug adapter found (install codelldb, lldb-dap, or gdb)".to_string(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_installed(spec: AdapterSpec) -> Result<AdapterSpec, DapError> {
|
||||
if on_path(&spec.command[0]) {
|
||||
Ok(spec)
|
||||
} else {
|
||||
Err(DapError::AdapterUnavailable(format!(
|
||||
"debug adapter '{}' not found on PATH",
|
||||
spec.command[0]
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an executable is resolvable — `PATH`, a well-known install directory, or an explicit
|
||||
/// path. Debug adapters are installed by `cargo install`, `pipx`, or an editor extension, none of
|
||||
/// which reliably land on the `PATH` an app inherits.
|
||||
fn on_path(program: &str) -> bool {
|
||||
luxe_core::program::is_available(program)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn python_targets_resolve_to_debugpy_dialect() {
|
||||
let spec = AdapterSpec {
|
||||
id: "debugpy".into(),
|
||||
command: vec!["python3".into()],
|
||||
kind: AdapterKind::Debugpy,
|
||||
transport: Transport::Stdio,
|
||||
};
|
||||
let args = spec.launch_arguments("/w/app.py", &["--flag".into()], "/w", true);
|
||||
assert_eq!(args["program"], "/w/app.py");
|
||||
assert_eq!(args["console"], "internalConsole");
|
||||
assert_eq!(args["stopOnEntry"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gdb_uses_its_own_stop_key() {
|
||||
let spec = AdapterSpec {
|
||||
id: "gdb".into(),
|
||||
command: vec!["gdb".into()],
|
||||
kind: AdapterKind::Gdb,
|
||||
transport: Transport::Stdio,
|
||||
};
|
||||
let args = spec.launch_arguments("/w/bin", &[], "/w", true);
|
||||
assert_eq!(args["stopAtBeginningOfMainSubprogram"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_adapter_is_rejected() {
|
||||
assert!(resolve("/w/app.py", Some("nope"), &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_adapters_bundle_parses() {
|
||||
let adapters = default_adapters();
|
||||
let ids: Vec<&str> = adapters.iter().map(|a| a.spec.id.as_str()).collect();
|
||||
for id in ["debugpy", "codelldb", "lldb-dap", "gdb", "dlv"] {
|
||||
assert!(ids.contains(&id), "missing built-in adapter {id}");
|
||||
}
|
||||
let dlv = adapters.iter().find(|a| a.spec.id == "dlv").unwrap();
|
||||
assert_eq!(dlv.spec.kind, AdapterKind::Delve);
|
||||
assert!(matches!(dlv.spec.transport, Transport::TcpDialIn { .. }));
|
||||
assert!(dlv.extensions.contains(&"go".to_string()));
|
||||
let debugpy = adapters.iter().find(|a| a.spec.id == "debugpy").unwrap();
|
||||
assert!(debugpy.extensions.contains(&"py".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_adapter_parses_and_maps() {
|
||||
let json = r#"{"id":"ruby","command":["rdbg","--dap","${DAP_ADDR}"],
|
||||
"extensions":[".rb"],"dialect":"debugpy","transport":"tcp_dial_in"}"#;
|
||||
let custom: CustomAdapter = serde_json::from_str(json).unwrap();
|
||||
let cfg = ConfiguredAdapter::from_custom(&custom);
|
||||
assert_eq!(cfg.spec.id, "ruby");
|
||||
assert_eq!(cfg.spec.kind, AdapterKind::Debugpy);
|
||||
assert!(matches!(cfg.spec.transport, Transport::TcpDialIn { .. }));
|
||||
assert_eq!(cfg.extensions, vec!["rb"]); // leading dot stripped
|
||||
}
|
||||
|
||||
/// A program that is genuinely installed, so `ensure_installed` passes on its own merits
|
||||
/// rather than on the fixture's. `sh` is not that program: Windows has no POSIX shell unless
|
||||
/// somebody installed one.
|
||||
fn installed_program() -> String {
|
||||
if cfg!(windows) { "cmd" } else { "sh" }.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_adapter_wins_by_id_and_extension() {
|
||||
let custom = ConfiguredAdapter {
|
||||
spec: AdapterSpec {
|
||||
id: "myruby".into(),
|
||||
command: vec![installed_program()],
|
||||
kind: AdapterKind::Debugpy,
|
||||
transport: Transport::Stdio,
|
||||
},
|
||||
extensions: vec!["rb".into()],
|
||||
};
|
||||
let extra = std::slice::from_ref(&custom);
|
||||
assert_eq!(resolve("/w/x", Some("myruby"), extra).unwrap().id, "myruby");
|
||||
assert_eq!(resolve("/w/app.rb", None, extra).unwrap().id, "myruby");
|
||||
}
|
||||
|
||||
/// The `debug` schema is the largest in the set; it should not be paid for on a machine that
|
||||
/// cannot debug. An adapter with a command that resolves to nothing must not count.
|
||||
#[test]
|
||||
fn availability_tracks_whether_an_adapter_command_resolves() {
|
||||
let missing = ConfiguredAdapter::from_custom(&CustomAdapter {
|
||||
id: "ghost".to_string(),
|
||||
command: vec!["definitely-not-a-real-adapter-xyz".to_string()],
|
||||
extensions: vec!["zz".to_string()],
|
||||
dialect: Dialect::Lldb,
|
||||
transport: TransportConfig::default(),
|
||||
addr_placeholder: None,
|
||||
});
|
||||
assert!(!any_adapter_available(&[missing]) || any_adapter_available(&[]));
|
||||
|
||||
let real = ConfiguredAdapter::from_custom(&CustomAdapter {
|
||||
id: "shell".to_string(),
|
||||
command: vec![installed_program()],
|
||||
extensions: vec!["zz".to_string()],
|
||||
dialect: Dialect::Lldb,
|
||||
transport: TransportConfig::default(),
|
||||
addr_placeholder: None,
|
||||
});
|
||||
assert!(any_adapter_available(&[real]), "an installed command counts as available");
|
||||
}
|
||||
}
|
||||
581
crates/luxe-dap/src/client.rs
Normal file
581
crates/luxe-dap/src/client.rs
Normal file
@@ -0,0 +1,581 @@
|
||||
//! A DAP client over an adapter transport.
|
||||
//!
|
||||
//! Spawns (or dials in to) a debug adapter, correlates requests to responses by `seq`/`request_seq`,
|
||||
//! folds events (`stopped`, `output`, `terminated`, …) into shared session state, and auto-replies
|
||||
//! to reverse requests so the adapter never stalls. The transport is boxed so the same client drives
|
||||
//! **stdio** adapters (debugpy, CodeLLDB, gdb) and **socket** adapters (Delve `dlv dap`, js-debug)
|
||||
//! uniformly. Methods take `&self` (seq is atomic, writer/pending are behind mutexes) so a session
|
||||
//! can be driven from an `Arc<DapClient>`.
|
||||
|
||||
use crate::protocol::{ProtocolMessage, StoppedBody};
|
||||
use luxe_core::jsonrpc_frame::write_frame;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::sync::{Arc, Mutex as SyncMutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::process::{Child, Command};
|
||||
use tokio::sync::{oneshot, Mutex, Notify};
|
||||
use tracing::error;
|
||||
|
||||
/// Boxed write half of a DAP transport (child stdin, or a TCP write half).
|
||||
type BoxWriter = Box<dyn AsyncWrite + Send + Unpin>;
|
||||
/// Boxed read half of a DAP transport (child stdout, or a TCP read half).
|
||||
type BoxReader = Box<dyn AsyncRead + Send + Unpin>;
|
||||
|
||||
/// Cap on captured program output so a chatty program can't grow the buffer unbounded.
|
||||
const MAX_OUTPUT_BYTES: usize = 64 * 1024;
|
||||
|
||||
mod reader;
|
||||
|
||||
use reader::{display_output, drain_child_logs, read_loop, StderrHead};
|
||||
|
||||
/// Requests written and not yet answered, by seq.
|
||||
type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<ProtocolMessage>>>>;
|
||||
|
||||
/// A written-but-not-yet-awaited request: its seq and the response channel.
|
||||
pub(crate) struct PendingRequest {
|
||||
seq: i64,
|
||||
rx: oneshot::Receiver<ProtocolMessage>,
|
||||
}
|
||||
|
||||
/// Live, event-folded session state shared with the background reader.
|
||||
#[derive(Default)]
|
||||
struct DapState {
|
||||
/// The adapter sent the `initialized` event (ready for breakpoint config).
|
||||
initialized: bool,
|
||||
/// The program terminated or the debug session ended.
|
||||
terminated: bool,
|
||||
/// Most recent `stopped` event (breakpoint/step/exception), cleared on continue.
|
||||
stopped: Option<StoppedBody>,
|
||||
/// Captured program output (bounded).
|
||||
output: String,
|
||||
/// Category of the last captured chunk (`stdout`, `stderr`, `console`, …).
|
||||
///
|
||||
/// DAP `output` events don't align with line boundaries, so a chunk that doesn't end in a
|
||||
/// newline is a genuine partial line and must not be broken up. But two *different* streams
|
||||
/// interleaving mid-line — an adapter `console` note landing inside the program's stdout —
|
||||
/// silently glues unrelated words together. Tracking the category lets the display split
|
||||
/// exactly those boundaries and no others.
|
||||
last_output_category: Option<String>,
|
||||
/// Byte offsets in `output` where a category switch glued two partial lines together.
|
||||
output_breaks: Vec<usize>,
|
||||
/// The adapter's stream has ended, so nothing more will be read: no answer, and no event.
|
||||
///
|
||||
/// Not `terminated`, which the program's end also sets while the adapter can still answer
|
||||
/// a `disconnect`.
|
||||
disconnected: bool,
|
||||
}
|
||||
|
||||
/// Shared client/reader state.
|
||||
struct Shared {
|
||||
state: SyncMutex<DapState>,
|
||||
notify: Notify,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn update(&self, f: impl FnOnce(&mut DapState)) {
|
||||
if let Ok(mut state) = self.state.lock() {
|
||||
f(&mut state);
|
||||
}
|
||||
self.notify.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
/// A running debug adapter connection.
|
||||
pub struct DapClient {
|
||||
child: Mutex<Option<Child>>,
|
||||
/// The adapter's pid, used to SIGKILL the whole process group on drop so the debuggee the
|
||||
/// adapter spawned is reaped too (`kill_on_drop` only reaps the adapter itself).
|
||||
group_pid: Option<u32>,
|
||||
writer: Arc<Mutex<BoxWriter>>,
|
||||
next_seq: AtomicI64,
|
||||
pending: Pending,
|
||||
shared: Arc<Shared>,
|
||||
stderr: Arc<StderrHead>,
|
||||
}
|
||||
|
||||
impl DapClient {
|
||||
/// Spawn a **stdio** adapter (debugpy, CodeLLDB, gdb) and start the background reader.
|
||||
pub async fn spawn(command: &[String], cwd: &std::path::Path) -> Result<Self, DapError> {
|
||||
let program = command.first().ok_or(DapError::EmptyCommand)?;
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.args(&command[1..]);
|
||||
cmd.current_dir(cwd);
|
||||
cmd.stdin(std::process::Stdio::piped());
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
cmd.stderr(std::process::Stdio::piped());
|
||||
cmd.kill_on_drop(true);
|
||||
// Own process group so dropping the client reaps the debuggee the adapter spawns, not just
|
||||
// the adapter (matches the bash tool's discipline).
|
||||
luxe_core::program::detach_from_terminal(&mut cmd);
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| DapError::SpawnFailed {
|
||||
adapter: program.clone(),
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
let stdin = child.stdin.take().ok_or(DapError::Io("adapter stdin unavailable".into()))?;
|
||||
let stdout =
|
||||
child.stdout.take().ok_or(DapError::Io("adapter stdout unavailable".into()))?;
|
||||
let stderr = drain_child_logs(&mut child);
|
||||
Ok(Self::start(Some(child), Box::new(stdin), Box::new(stdout), stderr))
|
||||
}
|
||||
|
||||
/// Connect to a **socket** adapter that dials in to us (Delve `dlv dap --client-addr`,
|
||||
/// js-debug). We bind a free loopback port, substitute it into `command` at `addr_placeholder`,
|
||||
/// spawn the adapter, and accept its connection — race-free (the OS picked the port).
|
||||
pub async fn connect_dial_in(
|
||||
command: &[String],
|
||||
cwd: &std::path::Path,
|
||||
addr_placeholder: &str,
|
||||
) -> Result<Self, DapError> {
|
||||
let program = command.first().ok_or(DapError::EmptyCommand)?;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.map_err(|e| DapError::Io(format!("failed to bind DAP listener: {e}")))?;
|
||||
let addr = listener.local_addr().map_err(|e| DapError::Io(e.to_string()))?.to_string();
|
||||
|
||||
let args: Vec<String> =
|
||||
command[1..].iter().map(|a| a.replace(addr_placeholder, &addr)).collect();
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.args(&args)
|
||||
.current_dir(cwd)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
luxe_core::program::detach_from_terminal(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(|e| DapError::SpawnFailed {
|
||||
adapter: program.clone(),
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
let stderr = drain_child_logs(&mut child);
|
||||
|
||||
let (stream, _) = tokio::time::timeout(Duration::from_secs(15), listener.accept())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
DapError::Io(format!(
|
||||
"debug adapter '{program}' did not dial in (check it's installed and the \
|
||||
target builds; see dap.adapter logs)"
|
||||
))
|
||||
})?
|
||||
.map_err(|e| DapError::Io(format!("accept from adapter failed: {e}")))?;
|
||||
let (read_half, write_half) = stream.into_split();
|
||||
Ok(Self::start(Some(child), Box::new(write_half), Box::new(read_half), stderr))
|
||||
}
|
||||
|
||||
/// Wire up shared state + the background reader over an already-connected transport.
|
||||
fn start(
|
||||
child: Option<Child>,
|
||||
writer: BoxWriter,
|
||||
reader: BoxReader,
|
||||
stderr: Arc<StderrHead>,
|
||||
) -> Self {
|
||||
let group_pid = child.as_ref().and_then(Child::id);
|
||||
let writer = Arc::new(Mutex::new(writer));
|
||||
let pending = Arc::new(Mutex::new(HashMap::new()));
|
||||
let shared =
|
||||
Arc::new(Shared { state: SyncMutex::new(DapState::default()), notify: Notify::new() });
|
||||
|
||||
let reader_writer = writer.clone();
|
||||
let reader_pending = pending.clone();
|
||||
let reader_shared = shared.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut reader = tokio::io::BufReader::new(reader);
|
||||
if let Err(e) =
|
||||
read_loop(&mut reader, reader_shared, reader_writer, reader_pending).await
|
||||
{
|
||||
error!("dap reader task exited: {e}");
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
child: Mutex::new(child),
|
||||
group_pid,
|
||||
writer,
|
||||
next_seq: AtomicI64::new(1),
|
||||
pending,
|
||||
shared,
|
||||
stderr,
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a request and await its response, failing on a non-success reply.
|
||||
pub async fn request(
|
||||
&self,
|
||||
command: &str,
|
||||
arguments: Value,
|
||||
timeout: Duration,
|
||||
) -> Result<Value, DapError> {
|
||||
let pending = self.write_request(command, arguments).await?;
|
||||
self.await_response(pending, command, timeout).await
|
||||
}
|
||||
|
||||
/// Write a request now and return a handle to await its response later.
|
||||
///
|
||||
/// Splitting send from await lets the launch/attach choreography guarantee `launch`/`attach`
|
||||
/// reaches the adapter **before** `configurationDone`, while its response (which only arrives
|
||||
/// after) is awaited afterward. Sending it inline (not in a spawned task) avoids a write-order
|
||||
/// race on stdin.
|
||||
pub(crate) async fn write_request(
|
||||
&self,
|
||||
command: &str,
|
||||
arguments: Value,
|
||||
) -> Result<PendingRequest, DapError> {
|
||||
let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);
|
||||
let mut message = json!({ "seq": seq, "type": "request", "command": command });
|
||||
if !arguments.is_null() {
|
||||
message["arguments"] = arguments;
|
||||
}
|
||||
let payload = serde_json::to_vec(&message).map_err(|e| DapError::Io(e.to_string()))?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.pending.lock().await.insert(seq, tx);
|
||||
// the reader marks itself done before it clears the map, so one of the two catches this
|
||||
let refused = match self.shared.state.lock() {
|
||||
Ok(state) => state.disconnected.then_some(DapError::Cancelled),
|
||||
Err(_) => Some(DapError::Poisoned),
|
||||
};
|
||||
if let Some(error) = refused {
|
||||
self.pending.lock().await.remove(&seq);
|
||||
return Err(error);
|
||||
}
|
||||
let written = {
|
||||
let mut guard = self.writer.lock().await;
|
||||
write_frame(&mut *guard, &payload).await
|
||||
};
|
||||
if let Err(error) = written {
|
||||
self.pending.lock().await.remove(&seq);
|
||||
return Err(DapError::Io(error.to_string()));
|
||||
}
|
||||
Ok(PendingRequest { seq, rx })
|
||||
}
|
||||
|
||||
/// Await a previously-written request's response, failing on a non-success reply or timeout.
|
||||
pub(crate) async fn await_response(
|
||||
&self,
|
||||
pending: PendingRequest,
|
||||
command: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<Value, DapError> {
|
||||
let response = match tokio::time::timeout(timeout, pending.rx).await {
|
||||
Ok(Ok(response)) => response,
|
||||
Ok(Err(_)) => return Err(DapError::Cancelled),
|
||||
Err(_) => {
|
||||
self.pending.lock().await.remove(&pending.seq);
|
||||
return Err(DapError::Timeout { command: command.to_string() });
|
||||
}
|
||||
};
|
||||
if response.success == Some(false) {
|
||||
return Err(DapError::RequestFailed {
|
||||
command: command.to_string(),
|
||||
message: response.message.unwrap_or_else(|| "request failed".to_string()),
|
||||
});
|
||||
}
|
||||
Ok(response.body.unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
/// Wait until the adapter emits `initialized`, or time out; an adapter that goes away first
|
||||
/// is `Cancelled` at once.
|
||||
pub async fn wait_for_initialized(&self, timeout: Duration) -> Result<(), DapError> {
|
||||
self.wait_until(timeout, |s| s.initialized || s.disconnected).await?;
|
||||
let initialized = self.shared.state.lock().map_err(|_| DapError::Poisoned)?.initialized;
|
||||
if initialized {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(DapError::Cancelled)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until the session stops or terminates. Returns the stop body, or `None` on terminate.
|
||||
pub async fn wait_for_stop_or_terminate(
|
||||
&self,
|
||||
timeout: Duration,
|
||||
) -> Result<Option<StoppedBody>, DapError> {
|
||||
self.wait_until(timeout, |s| s.stopped.is_some() || s.terminated).await?;
|
||||
let state = self.shared.state.lock().map_err(|_| DapError::Poisoned)?;
|
||||
Ok(state.stopped.clone())
|
||||
}
|
||||
|
||||
/// Poll a predicate over shared state until true or the timeout elapses.
|
||||
async fn wait_until(
|
||||
&self,
|
||||
timeout: Duration,
|
||||
pred: impl Fn(&DapState) -> bool,
|
||||
) -> Result<(), DapError> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
{
|
||||
let state = self.shared.state.lock().map_err(|_| DapError::Poisoned)?;
|
||||
if pred(&state) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if start.elapsed() >= timeout {
|
||||
return Err(DapError::Timeout { command: "event".to_string() });
|
||||
}
|
||||
tokio::select! {
|
||||
_ = self.shared.notify.notified() => {}
|
||||
_ = tokio::time::sleep(Duration::from_millis(50)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of what the adapter wrote to stderr, trimmed: usually why it failed to start.
|
||||
///
|
||||
/// Waits a moment for stderr to close, since an adapter that just died has said its last
|
||||
/// words there and the drain may not have read them yet.
|
||||
pub async fn adapter_stderr(&self) -> String {
|
||||
let deadline = Instant::now() + Duration::from_millis(500);
|
||||
while !self.stderr.closed.load(Ordering::Acquire) && Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
self.stderr.text.lock().map(|text| text.trim().to_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Snapshot: has the session terminated?
|
||||
pub fn is_terminated(&self) -> bool {
|
||||
self.shared.state.lock().map(|s| s.terminated).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Snapshot: the latest stop, if any.
|
||||
pub fn last_stop(&self) -> Option<StoppedBody> {
|
||||
self.shared.state.lock().ok().and_then(|s| s.stopped.clone())
|
||||
}
|
||||
|
||||
/// Clear the recorded stop (call when resuming execution).
|
||||
pub fn clear_stop(&self) {
|
||||
self.shared.update(|s| s.stopped = None);
|
||||
}
|
||||
|
||||
/// Snapshot of captured program output, byte-for-byte as the adapter sent it.
|
||||
pub fn output(&self) -> String {
|
||||
self.shared.state.lock().map(|s| s.output.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Captured output for *display*: identical to [`Self::output`] except that a mid-line switch
|
||||
/// between output streams is broken onto its own line, so an adapter note can't glue itself
|
||||
/// onto the end of a program's partial line.
|
||||
pub fn output_for_display(&self) -> String {
|
||||
self.shared.state.lock().map(|state| display_output(&state)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Forget everything captured so far, because none of it came from the program.
|
||||
///
|
||||
/// Called once the adapter has answered `initialize` and before the program is launched or
|
||||
/// attached to. Up to that moment anything on the wire is the *adapter* talking: `gdb
|
||||
/// --interpreter=dap` opens with twelve lines of version and GPL notice, tagged `stdout` like
|
||||
/// real program output, and none of it belongs in the model's context.
|
||||
pub fn discard_output_so_far(&self) {
|
||||
if let Ok(mut state) = self.shared.state.lock() {
|
||||
state.output.clear();
|
||||
state.last_output_category = None;
|
||||
state.output_breaks.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Terminate the adapter and reap the process group (adapter + debuggee).
|
||||
pub async fn shutdown(&self) {
|
||||
let _ = self
|
||||
.request("disconnect", json!({ "terminateDebuggee": true }), Duration::from_secs(3))
|
||||
.await;
|
||||
if let Some(pid) = self.group_pid {
|
||||
luxe_core::program::kill_tree(pid);
|
||||
}
|
||||
if let Some(mut child) = self.child.lock().await.take() {
|
||||
let _ = child.start_kill();
|
||||
let _ = child.wait().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DapClient {
|
||||
/// Reap the whole process group so a dropped client never leaks the adapter or its debuggee.
|
||||
fn drop(&mut self) {
|
||||
if let Some(pid) = self.group_pid {
|
||||
luxe_core::program::kill_tree(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DAP client errors.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DapError {
|
||||
#[error("empty adapter command")]
|
||||
EmptyCommand,
|
||||
|
||||
#[error("failed to spawn debug adapter '{adapter}': {error}")]
|
||||
SpawnFailed { adapter: String, error: String },
|
||||
|
||||
#[error("io error: {0}")]
|
||||
Io(String),
|
||||
|
||||
#[error("request '{command}' timed out")]
|
||||
Timeout { command: String },
|
||||
|
||||
#[error("request '{command}' failed: {message}")]
|
||||
RequestFailed { command: String, message: String },
|
||||
|
||||
#[error("request cancelled")]
|
||||
Cancelled,
|
||||
|
||||
#[error("session state poisoned")]
|
||||
Poisoned,
|
||||
|
||||
#[error("no such debug session")]
|
||||
NoSession,
|
||||
|
||||
/// No adapter can run what was asked for: an unknown id, one that is not installed, or no
|
||||
/// native adapter at all
|
||||
#[error("{0}")]
|
||||
AdapterUnavailable(String),
|
||||
|
||||
/// A launch or attach step failed, with the adapter's stderr when it had exited
|
||||
#[error("{0}")]
|
||||
StartFailed(String),
|
||||
|
||||
/// No thread was named and none has stopped
|
||||
#[error("no active thread")]
|
||||
NoThread,
|
||||
|
||||
/// A resume was accepted and no stop followed
|
||||
#[error(
|
||||
"{command} was accepted but the program has not stopped after {secs}s — it is still \
|
||||
running. Use action=pause to stop it, action=output to see what it has printed, or set \
|
||||
{env} higher if the next stop is simply far away."
|
||||
)]
|
||||
StillRunning {
|
||||
/// The request that was accepted
|
||||
command: String,
|
||||
/// How long the wait was
|
||||
secs: u64,
|
||||
/// The environment variable that lengthens it
|
||||
env: &'static str,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::reader::apply_event;
|
||||
use super::*;
|
||||
|
||||
fn output_event(text: &str, category: &str) -> ProtocolMessage {
|
||||
serde_json::from_value(json!({
|
||||
"seq": 1,
|
||||
"type": "event",
|
||||
"event": "output",
|
||||
"body": { "output": text, "category": category },
|
||||
}))
|
||||
.expect("event parses")
|
||||
}
|
||||
|
||||
fn shared() -> Shared {
|
||||
Shared { state: SyncMutex::new(DapState::default()), notify: Notify::new() }
|
||||
}
|
||||
|
||||
/// The break this catches: the cut that keeps the newest output fell inside a multibyte char,
|
||||
/// panicked under the state lock, poisoned it, and the session read as over while it ran.
|
||||
#[test]
|
||||
fn output_past_the_cap_is_cut_on_a_char_boundary() {
|
||||
let shared = shared();
|
||||
// an odd byte on either side puts the cut inside an `é`
|
||||
apply_event(&shared, &output_event("x", "stdout"));
|
||||
apply_event(&shared, &output_event(&format!("{}y", "é".repeat(35_000)), "stdout"));
|
||||
assert!(!shared.state.is_poisoned(), "the reader survived");
|
||||
let state = shared.state.lock().unwrap();
|
||||
assert!(state.output.len() <= MAX_OUTPUT_BYTES, "{}", state.output.len());
|
||||
assert!(state.output.trim_end_matches('y').chars().all(|c| c == 'é'), "whole chars only");
|
||||
}
|
||||
|
||||
/// A writer whose every write fails, as a closed pipe's does.
|
||||
struct Refusing;
|
||||
|
||||
impl tokio::io::AsyncWrite for Refusing {
|
||||
fn poll_write(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_: &mut std::task::Context<'_>,
|
||||
_: &[u8],
|
||||
) -> std::task::Poll<std::io::Result<usize>> {
|
||||
std::task::Poll::Ready(Err(std::io::ErrorKind::BrokenPipe.into()))
|
||||
}
|
||||
fn poll_flush(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
std::task::Poll::Ready(Ok(()))
|
||||
}
|
||||
fn poll_shutdown(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
std::task::Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A request whose write fails leaves no pending entry behind for nobody to answer.
|
||||
#[tokio::test]
|
||||
async fn a_failed_write_leaves_no_pending_entry() {
|
||||
let (_adapter, ours) = tokio::io::duplex(64);
|
||||
let client = DapClient::start(None, Box::new(Refusing), Box::new(ours), Arc::default());
|
||||
let written = client.write_request("threads", Value::Null).await;
|
||||
assert!(matches!(written, Err(DapError::Io(_))), "{:?}", written.err());
|
||||
assert!(client.pending.lock().await.is_empty());
|
||||
}
|
||||
|
||||
/// A poisoned state lock is reported as poisoned, not as an adapter that exited, and the
|
||||
/// request leaves nothing pending.
|
||||
#[tokio::test]
|
||||
async fn a_poisoned_state_is_poisoned_not_an_exit() {
|
||||
let (_adapter, ours) = tokio::io::duplex(64);
|
||||
let (writer, _) = tokio::io::duplex(64);
|
||||
let client = DapClient::start(None, Box::new(writer), Box::new(ours), Arc::default());
|
||||
let shared = Arc::clone(&client.shared);
|
||||
let poisoner = std::thread::spawn(move || {
|
||||
let _held = shared.state.lock().unwrap();
|
||||
panic!("poison the state lock");
|
||||
});
|
||||
assert!(poisoner.join().is_err());
|
||||
let written = client.write_request("threads", Value::Null).await;
|
||||
assert!(matches!(written, Err(DapError::Poisoned)), "{:?}", written.err());
|
||||
assert!(client.pending.lock().await.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_lines_from_one_stream_stay_intact() {
|
||||
// `print(..., end="")` and progress bars stream partial lines; splitting them would be
|
||||
// wrong, so same-category chunks are concatenated verbatim.
|
||||
let shared = shared();
|
||||
apply_event(&shared, &output_event("load", "stdout"));
|
||||
apply_event(&shared, &output_event("ing...", "stdout"));
|
||||
apply_event(&shared, &output_event(" done\n", "stdout"));
|
||||
let state = shared.state.lock().unwrap();
|
||||
assert_eq!(state.output, "loading... done\n");
|
||||
assert!(state.output_breaks.is_empty(), "no boundary inside one stream");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_switch_mid_line_is_broken_for_display_only() {
|
||||
// Two adapter messages must not glue into one nonsense token (`ptvsd` + `debugpy`).
|
||||
let shared = shared();
|
||||
apply_event(&shared, &output_event("ptvsd", "console"));
|
||||
apply_event(&shared, &output_event("debugpy", "stderr"));
|
||||
let state = shared.state.lock().unwrap();
|
||||
assert_eq!(state.output, "ptvsddebugpy", "captured bytes stay verbatim");
|
||||
assert_eq!(state.output_breaks, vec![5], "the boundary is recorded, not inserted");
|
||||
drop(state);
|
||||
|
||||
let state = shared.state.lock().unwrap();
|
||||
assert_eq!(state.output, "ptvsddebugpy", "the snapshot stays byte-faithful");
|
||||
assert_eq!(display_output(&state), "ptvsd\ndebugpy", "display separates the streams");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_switch_after_a_newline_needs_no_boundary() {
|
||||
let shared = shared();
|
||||
apply_event(&shared, &output_event("hello\n", "stdout"));
|
||||
apply_event(&shared, &output_event("warning\n", "stderr"));
|
||||
let state = shared.state.lock().unwrap();
|
||||
assert!(state.output_breaks.is_empty(), "the newline already separates them");
|
||||
assert_eq!(state.output, "hello\nwarning\n");
|
||||
}
|
||||
}
|
||||
215
crates/luxe-dap/src/client/reader.rs
Normal file
215
crates/luxe-dap/src/client/reader.rs
Normal file
@@ -0,0 +1,215 @@
|
||||
//! DAP reader — the background task that reads the adapter, and the folding of what it says.
|
||||
//!
|
||||
//! Responses go to their pending request, events fold into [`Shared`] state, and reverse requests
|
||||
//! are refused at once so the adapter never waits on us.
|
||||
|
||||
use super::{BoxWriter, DapError, DapState, Pending, Shared, MAX_OUTPUT_BYTES};
|
||||
use crate::protocol::{ProtocolMessage, StoppedBody};
|
||||
use luxe_core::jsonrpc_frame::{read_frame, write_frame, MAX_FRAME_BYTES};
|
||||
use serde_json::{json, Value};
|
||||
use std::sync::{Arc, Mutex as SyncMutex};
|
||||
use tokio::io::{AsyncBufRead, AsyncReadExt};
|
||||
use tokio::process::Child;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::debug;
|
||||
|
||||
/// The start of what an adapter wrote to stderr, filled as it arrives.
|
||||
#[derive(Default)]
|
||||
pub(super) struct StderrHead {
|
||||
/// What has arrived, up to [`STDERR_HEAD_BYTES`]
|
||||
pub(super) text: SyncMutex<String>,
|
||||
/// Whether stderr has closed, so nothing more is coming
|
||||
pub(super) closed: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
/// Background reader: routes responses to pending requests, folds events, replies to reverse requests.
|
||||
pub(super) async fn read_loop<R: AsyncBufRead + Unpin>(
|
||||
reader: &mut R,
|
||||
shared: Arc<Shared>,
|
||||
writer: Arc<Mutex<BoxWriter>>,
|
||||
pending: Pending,
|
||||
) -> Result<(), DapError> {
|
||||
let outcome = route_messages(reader, &shared, &writer, &pending).await;
|
||||
// Only the reader can answer an in-flight request, so once it stops — the adapter exited, or
|
||||
// its stream broke — nothing is coming for any of them. Dropping the senders fails each waiter
|
||||
// as `Cancelled` now instead of at its own timeout, and the session reads as over either way.
|
||||
// Marked first, so a request written from here on sees it and does not wait either.
|
||||
shared.update(|s| {
|
||||
s.disconnected = true;
|
||||
s.terminated = true;
|
||||
});
|
||||
pending.lock().await.clear();
|
||||
outcome
|
||||
}
|
||||
|
||||
/// The reader's loop proper, split out so [`read_loop`] can clean up on every exit path.
|
||||
async fn route_messages<R: AsyncBufRead + Unpin>(
|
||||
reader: &mut R,
|
||||
shared: &Shared,
|
||||
writer: &Arc<Mutex<BoxWriter>>,
|
||||
pending: &Pending,
|
||||
) -> Result<(), DapError> {
|
||||
while let Some(bytes) =
|
||||
read_frame(reader, MAX_FRAME_BYTES).await.map_err(|e| DapError::Io(e.to_string()))?
|
||||
{
|
||||
let msg: ProtocolMessage = match serde_json::from_slice(&bytes) {
|
||||
Ok(msg) => msg,
|
||||
Err(e) => {
|
||||
debug!(error = %e, "dap: dropping unparseable message");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match msg.kind.as_str() {
|
||||
"response" => {
|
||||
if let Some(request_seq) = msg.request_seq {
|
||||
if let Some(tx) = pending.lock().await.remove(&request_seq) {
|
||||
let _ = tx.send(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
"event" => apply_event(shared, &msg),
|
||||
"request" => reply_unsupported(writer, &msg).await,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Render captured output with its recorded stream boundaries broken onto their own lines.
|
||||
pub(super) fn display_output(state: &DapState) -> String {
|
||||
if state.output_breaks.is_empty() {
|
||||
return state.output.clone();
|
||||
}
|
||||
let mut out = String::with_capacity(state.output.len() + state.output_breaks.len());
|
||||
let mut cursor = 0usize;
|
||||
for offset in &state.output_breaks {
|
||||
let offset = (*offset).min(state.output.len());
|
||||
if offset < cursor || !state.output.is_char_boundary(offset) {
|
||||
continue;
|
||||
}
|
||||
out.push_str(&state.output[cursor..offset]);
|
||||
out.push('\n');
|
||||
cursor = offset;
|
||||
}
|
||||
out.push_str(&state.output[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Fold a DAP event into shared session state.
|
||||
pub(super) fn apply_event(shared: &Shared, msg: &ProtocolMessage) {
|
||||
let Some(event) = msg.event.as_deref() else { return };
|
||||
match event {
|
||||
"initialized" => shared.update(|s| s.initialized = true),
|
||||
"stopped" => {
|
||||
let body = msg
|
||||
.body
|
||||
.clone()
|
||||
.and_then(|b| serde_json::from_value::<StoppedBody>(b).ok())
|
||||
.unwrap_or_default();
|
||||
shared.update(|s| s.stopped = Some(body));
|
||||
}
|
||||
"continued" => shared.update(|s| s.stopped = None),
|
||||
"terminated" | "exited" => shared.update(|s| s.terminated = true),
|
||||
"output" => {
|
||||
let chunk = msg
|
||||
.body
|
||||
.as_ref()
|
||||
.and_then(|b| b.get("output"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
let category = msg
|
||||
.body
|
||||
.as_ref()
|
||||
.and_then(|b| b.get("category"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("console")
|
||||
.to_string();
|
||||
if !chunk.is_empty() {
|
||||
let chunk = chunk.to_string();
|
||||
shared.update(move |s| {
|
||||
// A different stream cutting in mid-line is a display boundary; the bytes
|
||||
// themselves stay exactly as the adapter sent them.
|
||||
let switched =
|
||||
s.last_output_category.as_deref().is_some_and(|last| last != category);
|
||||
if switched && !s.output.ends_with('\n') && !s.output.is_empty() {
|
||||
s.output_breaks.push(s.output.len());
|
||||
}
|
||||
s.last_output_category = Some(category);
|
||||
s.output.push_str(&chunk);
|
||||
if s.output.len() > MAX_OUTPUT_BYTES {
|
||||
let start = luxe_core::output_limit::ceil_boundary(
|
||||
&s.output,
|
||||
s.output.len() - MAX_OUTPUT_BYTES,
|
||||
);
|
||||
s.output = s.output.split_off(start);
|
||||
s.output_breaks.retain(|offset| *offset > start);
|
||||
for offset in &mut s.output_breaks {
|
||||
*offset -= start;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reply to an adapter→client (reverse) request with a failure, so the adapter never blocks on us.
|
||||
async fn reply_unsupported(writer: &Arc<Mutex<BoxWriter>>, msg: &ProtocolMessage) {
|
||||
let response = json!({
|
||||
"seq": 0,
|
||||
"type": "response",
|
||||
"request_seq": msg.seq,
|
||||
"success": false,
|
||||
"command": msg.command.clone().unwrap_or_default(),
|
||||
"message": "unsupported reverse request",
|
||||
});
|
||||
if let Ok(payload) = serde_json::to_vec(&response) {
|
||||
let mut guard = writer.lock().await;
|
||||
let _ = write_frame(&mut *guard, &payload).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The most of an adapter's stderr kept to explain a failed start.
|
||||
const STDERR_HEAD_BYTES: usize = 2_000;
|
||||
|
||||
/// Drains an adapter's stdout, when it is not the transport, and its stderr to `dap.adapter` logs
|
||||
/// so its pipes never block, keeping the start of stderr: when an adapter fails to start, that is
|
||||
/// usually where it said why. Both are read as bytes to the end, so a line that is not UTF-8 does
|
||||
/// not stop the drain and leave the adapter writing into a closed pipe.
|
||||
pub(super) fn drain_child_logs(child: &mut Child) -> Arc<StderrHead> {
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
tokio::spawn(drain(stdout, None));
|
||||
}
|
||||
let head = Arc::new(StderrHead::default());
|
||||
match child.stderr.take() {
|
||||
Some(stderr) => {
|
||||
tokio::spawn(drain(stderr, Some(Arc::clone(&head))));
|
||||
}
|
||||
None => head.closed.store(true, std::sync::atomic::Ordering::Release),
|
||||
}
|
||||
head
|
||||
}
|
||||
|
||||
/// Reads `pipe` to its end, logging each chunk and keeping the start in `head`, when given one.
|
||||
async fn drain(mut pipe: impl tokio::io::AsyncRead + Unpin, head: Option<Arc<StderrHead>>) {
|
||||
let mut chunk = [0u8; 4096];
|
||||
let mut kept = Vec::new();
|
||||
while let Ok(read) = pipe.read(&mut chunk).await {
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
for line in String::from_utf8_lossy(&chunk[..read]).lines() {
|
||||
debug!(target: "dap.adapter", "{line}");
|
||||
}
|
||||
if let Some(head) = head.as_ref().filter(|_| kept.len() < STDERR_HEAD_BYTES) {
|
||||
kept.extend_from_slice(&chunk[..read.min(STDERR_HEAD_BYTES - kept.len())]);
|
||||
if let Ok(mut text) = head.text.lock() {
|
||||
*text = String::from_utf8_lossy(&kept).replace("\r\n", "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(head) = head {
|
||||
head.closed.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
}
|
||||
30
crates/luxe-dap/src/default-debug-adapters.json
Normal file
30
crates/luxe-dap/src/default-debug-adapters.json
Normal file
@@ -0,0 +1,30 @@
|
||||
[
|
||||
{
|
||||
"id": "debugpy",
|
||||
"command": ["python3", "-m", "debugpy.adapter"],
|
||||
"extensions": ["py"],
|
||||
"dialect": "debugpy"
|
||||
},
|
||||
{
|
||||
"id": "codelldb",
|
||||
"command": ["codelldb"],
|
||||
"dialect": "lldb"
|
||||
},
|
||||
{
|
||||
"id": "lldb-dap",
|
||||
"command": ["lldb-dap"],
|
||||
"dialect": "lldb"
|
||||
},
|
||||
{
|
||||
"id": "gdb",
|
||||
"command": ["gdb", "--interpreter=dap"],
|
||||
"dialect": "gdb"
|
||||
},
|
||||
{
|
||||
"id": "dlv",
|
||||
"command": ["dlv", "dap", "--client-addr", "${DAP_ADDR}"],
|
||||
"extensions": ["go"],
|
||||
"dialect": "delve",
|
||||
"transport": "tcp_dial_in"
|
||||
}
|
||||
]
|
||||
22
crates/luxe-dap/src/lib.rs
Normal file
22
crates/luxe-dap/src/lib.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
//! luxe-dap — a native Debug Adapter Protocol client and the `debug` tool.
|
||||
//!
|
||||
//! Gives the agent a real debugger: launch/attach a program, set breakpoints, step, and inspect
|
||||
//! threads/stack/variables/expressions across adapters (CodeLLDB/lldb-dap/gdb for native, debugpy
|
||||
//! for Python) over stdio. Mirrors `luxe-lsp`'s warm-service shape — one long-lived
|
||||
//! [`service::DapService`] reuses sessions across tool calls. Allowed edge: `dap → core`.
|
||||
|
||||
pub mod adapter;
|
||||
mod client;
|
||||
pub mod protocol;
|
||||
pub mod service;
|
||||
mod tool;
|
||||
|
||||
pub use adapter::{
|
||||
any_adapter_available, builtin_adapters, AdapterSpec, ConfiguredAdapter, CustomAdapter,
|
||||
};
|
||||
pub use client::{DapClient, DapError};
|
||||
pub use service::{
|
||||
BreakpointRequest, DapService, DapSession, DapSessionInfo, FunctionBreakpoint, LaunchOutcome,
|
||||
SourceBreakpoint,
|
||||
};
|
||||
pub use tool::DebugTool;
|
||||
132
crates/luxe-dap/src/protocol.rs
Normal file
132
crates/luxe-dap/src/protocol.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
//! Debug Adapter Protocol message envelope and the payload types the tool formats.
|
||||
//!
|
||||
//! Only the shapes we read back are typed; request `arguments` are built as `serde_json::Value` in
|
||||
//! the client. See the DAP spec: <https://microsoft.github.io/debug-adapter-protocol/specification>.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// A DAP wire message (request, response, or event). Fields are optional so one type parses all
|
||||
/// three variants coming from the adapter.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ProtocolMessage {
|
||||
/// Adapter-assigned sequence number for this message.
|
||||
#[serde(default)]
|
||||
pub seq: i64,
|
||||
/// `"request"`, `"response"`, or `"event"`.
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
/// Response: the request seq this answers.
|
||||
#[serde(default)]
|
||||
pub request_seq: Option<i64>,
|
||||
/// Response: whether the request succeeded.
|
||||
#[serde(default)]
|
||||
pub success: Option<bool>,
|
||||
/// Response/request: the command name.
|
||||
#[serde(default)]
|
||||
pub command: Option<String>,
|
||||
/// Event: the event name.
|
||||
#[serde(default)]
|
||||
pub event: Option<String>,
|
||||
/// Response: a human-readable failure message.
|
||||
#[serde(default)]
|
||||
pub message: Option<String>,
|
||||
/// Response body / event body.
|
||||
#[serde(default)]
|
||||
pub body: Option<Value>,
|
||||
}
|
||||
|
||||
/// A DAP thread (`threads` response).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Thread {
|
||||
/// Adapter thread id.
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// A source location referenced by a stack frame or breakpoint.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Source {
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
/// A stack frame (`stackTrace` response).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StackFrame {
|
||||
/// Frame id used to scope `scopes`/`evaluate`.
|
||||
pub id: i64,
|
||||
/// Frame (function) name.
|
||||
pub name: String,
|
||||
/// Source location, if resolved.
|
||||
#[serde(default)]
|
||||
pub source: Option<Source>,
|
||||
/// 1-based line.
|
||||
#[serde(default)]
|
||||
pub line: i64,
|
||||
/// 1-based column.
|
||||
#[serde(default)]
|
||||
pub column: i64,
|
||||
}
|
||||
|
||||
/// A variable scope (`scopes` response).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Scope {
|
||||
/// Scope name (e.g. "Locals").
|
||||
pub name: String,
|
||||
/// Reference for a `variables` request.
|
||||
#[serde(rename = "variablesReference")]
|
||||
pub variables_reference: i64,
|
||||
/// Whether retrieving this scope is expensive.
|
||||
#[serde(default)]
|
||||
pub expensive: bool,
|
||||
/// What the scope holds (`arguments`, `locals`, `registers`), when the adapter says
|
||||
#[serde(rename = "presentationHint", default)]
|
||||
pub presentation_hint: Option<String>,
|
||||
}
|
||||
|
||||
/// A variable (`variables` / `evaluate` response).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Variable {
|
||||
pub name: String,
|
||||
/// Rendered value.
|
||||
pub value: String,
|
||||
/// Declared type, if the adapter provides it.
|
||||
#[serde(rename = "type", default)]
|
||||
pub type_name: Option<String>,
|
||||
/// Non-zero when the variable is structured (expandable).
|
||||
#[serde(rename = "variablesReference", default)]
|
||||
pub variables_reference: i64,
|
||||
}
|
||||
|
||||
/// A breakpoint verification result (`setBreakpoints` response).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Breakpoint {
|
||||
/// Whether the adapter bound the breakpoint.
|
||||
#[serde(default)]
|
||||
pub verified: bool,
|
||||
/// Resolved line, if the adapter moved it.
|
||||
#[serde(default)]
|
||||
pub line: Option<i64>,
|
||||
/// Explanation when unverified.
|
||||
#[serde(default)]
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
/// Body of a `stopped` event.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct StoppedBody {
|
||||
/// Why execution stopped (e.g. "breakpoint", "step", "exception").
|
||||
#[serde(default)]
|
||||
pub reason: String,
|
||||
/// Thread that stopped, if reported.
|
||||
#[serde(rename = "threadId", default)]
|
||||
pub thread_id: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
/// Extra detail (e.g. exception text).
|
||||
#[serde(default)]
|
||||
pub text: Option<String>,
|
||||
}
|
||||
428
crates/luxe-dap/src/service.rs
Normal file
428
crates/luxe-dap/src/service.rs
Normal file
@@ -0,0 +1,428 @@
|
||||
//! Debug session management — the warm, per-workspace `DapService`.
|
||||
//!
|
||||
//! Owns live [`DapSession`]s keyed by id, runs the DAP launch choreography (initialize → launch →
|
||||
//! `initialized` event → breakpoints → configurationDone → first stop), and routes control/read
|
||||
//! actions to a session's client. Mirrors the LSP service pattern: sessions are reused across tool
|
||||
//! calls rather than re-created per request.
|
||||
|
||||
use crate::adapter::{self};
|
||||
use crate::client::{DapClient, DapError};
|
||||
use crate::protocol::{Scope, StackFrame, StoppedBody, Thread, Variable};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex as SyncMutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
mod breakpoints;
|
||||
mod startup;
|
||||
|
||||
use breakpoints::parse_array;
|
||||
pub use breakpoints::{set_breakpoints, set_function_breakpoints};
|
||||
|
||||
const STOP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// Override for [`STOP_TIMEOUT`], for a program whose next stop is genuinely far away.
|
||||
const STOP_TIMEOUT_ENV: &str = "LUXE_DAP_STOP_TIMEOUT_SECS";
|
||||
|
||||
/// How long to wait for a resumed program to stop.
|
||||
fn stop_timeout() -> Duration {
|
||||
std::env::var(STOP_TIMEOUT_ENV)
|
||||
.ok()
|
||||
.and_then(|raw| raw.trim().parse::<u64>().ok())
|
||||
.filter(|secs| *secs > 0)
|
||||
.map_or(STOP_TIMEOUT, Duration::from_secs)
|
||||
}
|
||||
const CONTROL_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// A live debug session's status for `/debug` and the dock DEBUG section.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DapSessionInfo {
|
||||
/// Session id (from launch/attach).
|
||||
pub id: String,
|
||||
/// Backing adapter id.
|
||||
pub adapter: String,
|
||||
/// Debuggee program / label.
|
||||
pub program: String,
|
||||
/// Whether the debuggee has terminated.
|
||||
pub terminated: bool,
|
||||
/// Whether the debuggee is currently paused at a stop (breakpoint/step/exception).
|
||||
pub stopped: bool,
|
||||
/// Why it stopped, when paused (e.g. `breakpoint`).
|
||||
pub stop_reason: Option<String>,
|
||||
}
|
||||
|
||||
/// One source-line breakpoint, optionally conditional.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SourceBreakpoint {
|
||||
/// 1-based line number.
|
||||
pub line: i64,
|
||||
/// Break only when this expression is true (adapter-evaluated), if set.
|
||||
pub condition: Option<String>,
|
||||
}
|
||||
|
||||
/// A source file's breakpoints.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BreakpointRequest {
|
||||
/// Absolute or workspace-relative source path.
|
||||
pub path: String,
|
||||
/// Breakpoints to set in this file.
|
||||
pub breakpoints: Vec<SourceBreakpoint>,
|
||||
}
|
||||
|
||||
/// A breakpoint that triggers on entry to a named function, optionally conditional.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FunctionBreakpoint {
|
||||
/// Function name to break on.
|
||||
pub name: String,
|
||||
/// Break only when this expression is true, if set.
|
||||
pub condition: Option<String>,
|
||||
}
|
||||
|
||||
/// Outcome of a launch: the new session plus where it first stopped (or that it ran to completion).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LaunchOutcome {
|
||||
/// Stable session id for follow-up actions.
|
||||
pub session_id: String,
|
||||
/// Adapter that backs the session.
|
||||
pub adapter_id: String,
|
||||
/// First stop, if the program paused (breakpoint / entry / exception).
|
||||
pub stop: Option<StoppedBody>,
|
||||
/// Whether the program already terminated.
|
||||
pub terminated: bool,
|
||||
/// Captured program output so far.
|
||||
pub output: String,
|
||||
/// Breakpoints the adapter did not bind, each with its reason
|
||||
pub unverified: Vec<String>,
|
||||
}
|
||||
|
||||
/// `path` as the adapter needs it: absolute, relative ones taken from `base`.
|
||||
///
|
||||
/// Adapters resolve a relative path against their own idea of a directory, or not at all: `gdb`
|
||||
/// leaves `src/lib.rs` pending as "No source file named src/lib.rs".
|
||||
pub fn resolve(path: &str, base: &str) -> String {
|
||||
let candidate = Path::new(path);
|
||||
if candidate.is_absolute() {
|
||||
path.to_string()
|
||||
} else {
|
||||
Path::new(base).join(candidate).to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// One live debug session.
|
||||
pub struct DapSession {
|
||||
/// Stable session id.
|
||||
pub id: String,
|
||||
/// Backing adapter id.
|
||||
pub adapter_id: String,
|
||||
/// Debuggee program (path).
|
||||
pub program: String,
|
||||
/// Directory the program runs in, which relative breakpoint paths resolve against
|
||||
pub cwd: String,
|
||||
/// The adapter connection.
|
||||
pub client: Arc<DapClient>,
|
||||
/// Thread selected by the last stop (default for control actions); interior-mutable so control
|
||||
/// methods stay `&self`.
|
||||
current_thread: SyncMutex<Option<i64>>,
|
||||
}
|
||||
|
||||
/// Warm, per-workspace debug service.
|
||||
#[derive(Default)]
|
||||
pub struct DapService {
|
||||
sessions: Mutex<HashMap<String, Arc<DapSession>>>,
|
||||
next_id: AtomicU64,
|
||||
/// User-configured adapters (extension-routed + selectable by id), shadowing built-ins.
|
||||
custom: Vec<adapter::ConfiguredAdapter>,
|
||||
}
|
||||
|
||||
impl DapService {
|
||||
/// Create an empty service (built-in adapters only).
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Whether this service could debug anything at all — i.e. some adapter is installed.
|
||||
pub fn has_adapter(&self) -> bool {
|
||||
adapter::any_adapter_available(&self.custom)
|
||||
}
|
||||
|
||||
/// Create a service with user-configured custom adapters (from config).
|
||||
pub fn with_adapters(custom: Vec<adapter::CustomAdapter>) -> Self {
|
||||
Self {
|
||||
custom: custom.iter().map(adapter::ConfiguredAdapter::from_custom).collect(),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Launch a program under a debug adapter, applying breakpoints, and wait for the first stop.
|
||||
pub async fn launch(
|
||||
&self,
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
cwd: String,
|
||||
stop_on_entry: bool,
|
||||
breakpoints: Vec<BreakpointRequest>,
|
||||
adapter: Option<String>,
|
||||
) -> Result<LaunchOutcome, DapError> {
|
||||
let spec = adapter::resolve(&program, adapter.as_deref(), &self.custom)?;
|
||||
let request_args = spec.launch_arguments(&program, &args, &cwd, stop_on_entry);
|
||||
self.start(spec, "launch".to_string(), request_args, cwd, breakpoints, program).await
|
||||
}
|
||||
|
||||
/// Attach to a running process (`pid`) or a listening adapter (`port`).
|
||||
pub async fn attach(
|
||||
&self,
|
||||
pid: Option<i64>,
|
||||
port: Option<i64>,
|
||||
cwd: String,
|
||||
breakpoints: Vec<BreakpointRequest>,
|
||||
adapter: Option<String>,
|
||||
) -> Result<LaunchOutcome, DapError> {
|
||||
// No program path for attach; `resolve("", ...)` picks the native adapter unless overridden.
|
||||
let spec = adapter::resolve("", adapter.as_deref(), &self.custom)?;
|
||||
let request_args = spec.attach_arguments(pid, port);
|
||||
let label = pid
|
||||
.map(|p| format!("attach pid {p}"))
|
||||
.or_else(|| port.map(|p| format!("attach :{p}")))
|
||||
.unwrap_or_else(|| "attach".to_string());
|
||||
self.start(spec, "attach".to_string(), request_args, cwd, breakpoints, label).await
|
||||
}
|
||||
|
||||
/// Shared launch/attach choreography: initialize → request → `initialized` → breakpoints →
|
||||
/// configurationDone → first stop. `label` names the session's program column.
|
||||
async fn start(
|
||||
&self,
|
||||
spec: adapter::AdapterSpec,
|
||||
request: String,
|
||||
request_args: Value,
|
||||
cwd: String,
|
||||
breakpoints: Vec<BreakpointRequest>,
|
||||
label: String,
|
||||
) -> Result<LaunchOutcome, DapError> {
|
||||
// stdio adapters run over the child's pipes; socket adapters dial in over TCP.
|
||||
let connected = match &spec.transport {
|
||||
adapter::Transport::Stdio => DapClient::spawn(&spec.command, Path::new(&cwd)).await,
|
||||
adapter::Transport::TcpDialIn { placeholder } => {
|
||||
DapClient::connect_dial_in(&spec.command, Path::new(&cwd), placeholder).await
|
||||
}
|
||||
};
|
||||
let client = Arc::new(connected?);
|
||||
let launch = startup::Launch { client: &client, adapter: &spec.id, request: &request };
|
||||
let started = launch.handshake(request_args).await?;
|
||||
let unverified = launch.configure(&breakpoints, &cwd, started.configuration_done).await?;
|
||||
let stop = launch.first_stop(started.pending).await?;
|
||||
|
||||
let id = format!("dbg-{}", self.next_id.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
let current_thread = stop.as_ref().and_then(|s| s.thread_id);
|
||||
let outcome = LaunchOutcome {
|
||||
session_id: id.clone(),
|
||||
adapter_id: spec.id.to_string(),
|
||||
stop,
|
||||
terminated: client.is_terminated(),
|
||||
output: client.output_for_display(),
|
||||
unverified,
|
||||
};
|
||||
let session = DapSession {
|
||||
id: id.clone(),
|
||||
adapter_id: spec.id.to_string(),
|
||||
program: label,
|
||||
cwd,
|
||||
client,
|
||||
current_thread: SyncMutex::new(current_thread),
|
||||
};
|
||||
self.sessions.lock().await.insert(id, Arc::new(session));
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Fetch a session handle by id.
|
||||
pub async fn get(&self, id: &str) -> Option<Arc<DapSession>> {
|
||||
self.sessions.lock().await.get(id).cloned()
|
||||
}
|
||||
|
||||
/// Describes every live session, in id order.
|
||||
pub async fn list(&self) -> Vec<DapSessionInfo> {
|
||||
let mut out: Vec<_> = self
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.values()
|
||||
.map(|session| {
|
||||
let terminated = session.client.is_terminated();
|
||||
let last_stop = session.client.last_stop();
|
||||
DapSessionInfo {
|
||||
id: session.id.clone(),
|
||||
adapter: session.adapter_id.clone(),
|
||||
program: session.program.clone(),
|
||||
terminated,
|
||||
stopped: !terminated && last_stop.is_some(),
|
||||
stop_reason: last_stop.map(|stop| stop.reason).filter(|r| !r.is_empty()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Terminate a session and drop it from the map.
|
||||
pub async fn terminate(&self, id: &str) -> Result<(), DapError> {
|
||||
let session = self.sessions.lock().await.remove(id).ok_or(DapError::NoSession)?;
|
||||
session.client.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Terminate every live session (used when leaving a project). Best-effort; the process-group
|
||||
/// reaping on each client's drop is the backstop.
|
||||
pub async fn terminate_all(&self) {
|
||||
let ids: Vec<String> = self.sessions.lock().await.keys().cloned().collect();
|
||||
for id in ids {
|
||||
let _ = self.terminate(&id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DapSession {
|
||||
/// Resolve the thread to act on: an explicit id, else the last stopped thread.
|
||||
fn thread(&self, explicit: Option<i64>) -> Result<i64, DapError> {
|
||||
let current = *self.current_thread.lock().expect("session state poisoned");
|
||||
explicit.or(current).ok_or(DapError::NoThread)
|
||||
}
|
||||
|
||||
/// Record the thread selected by the most recent stop.
|
||||
fn remember_stop(&self, stop: &Option<StoppedBody>) {
|
||||
if let Some(thread_id) = stop.as_ref().and_then(|s| s.thread_id) {
|
||||
*self.current_thread.lock().expect("session state poisoned") = Some(thread_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume execution; waits for the next stop or termination.
|
||||
pub async fn continue_(&self, thread: Option<i64>) -> Result<Option<StoppedBody>, DapError> {
|
||||
let thread = self.thread(thread)?;
|
||||
self.client.clear_stop();
|
||||
self.client.request("continue", json!({ "threadId": thread }), CONTROL_TIMEOUT).await?;
|
||||
let stop = self.await_stop("continue").await?;
|
||||
self.remember_stop(&stop);
|
||||
Ok(stop)
|
||||
}
|
||||
|
||||
/// Wait for the stop that `command` was expected to produce, and say what it means if none
|
||||
/// comes.
|
||||
///
|
||||
/// An adapter can accept a resume, answer `success: true`, and then report nothing — gdb does
|
||||
/// exactly that for a `stepIn` with nowhere to step. The program is *running*, so the error
|
||||
/// says that, with the two actions that reach a running program, rather than naming a wait.
|
||||
async fn await_stop(&self, command: &str) -> Result<Option<StoppedBody>, DapError> {
|
||||
let budget = stop_timeout();
|
||||
match self.client.wait_for_stop_or_terminate(budget).await {
|
||||
Err(DapError::Timeout { .. }) => Err(DapError::StillRunning {
|
||||
command: command.to_string(),
|
||||
secs: budget.as_secs(),
|
||||
env: STOP_TIMEOUT_ENV,
|
||||
}),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Step (`next`, `stepIn`, `stepOut`); waits for the next stop.
|
||||
pub async fn step(
|
||||
&self,
|
||||
command: &str,
|
||||
thread: Option<i64>,
|
||||
) -> Result<Option<StoppedBody>, DapError> {
|
||||
let thread = self.thread(thread)?;
|
||||
self.client.clear_stop();
|
||||
self.client.request(command, json!({ "threadId": thread }), CONTROL_TIMEOUT).await?;
|
||||
let stop = self.await_stop(command).await?;
|
||||
self.remember_stop(&stop);
|
||||
Ok(stop)
|
||||
}
|
||||
|
||||
/// Pause a running thread.
|
||||
pub async fn pause(&self, thread: Option<i64>) -> Result<(), DapError> {
|
||||
let thread = self.thread(thread)?;
|
||||
self.client
|
||||
.request("pause", json!({ "threadId": thread }), CONTROL_TIMEOUT)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// List threads.
|
||||
pub async fn threads(&self) -> Result<Vec<Thread>, DapError> {
|
||||
let body = self.client.request("threads", Value::Null, CONTROL_TIMEOUT).await?;
|
||||
Ok(parse_array(&body, "threads"))
|
||||
}
|
||||
|
||||
/// Fetch a thread's stack frames.
|
||||
pub async fn stack_trace(&self, thread: Option<i64>) -> Result<Vec<StackFrame>, DapError> {
|
||||
let thread = self.thread(thread)?;
|
||||
let body = self
|
||||
.client
|
||||
.request("stackTrace", json!({ "threadId": thread, "levels": 20 }), CONTROL_TIMEOUT)
|
||||
.await?;
|
||||
Ok(parse_array(&body, "stackFrames"))
|
||||
}
|
||||
|
||||
/// Fetch a frame's variable scopes.
|
||||
pub async fn scopes(&self, frame_id: i64) -> Result<Vec<Scope>, DapError> {
|
||||
let body =
|
||||
self.client.request("scopes", json!({ "frameId": frame_id }), CONTROL_TIMEOUT).await?;
|
||||
Ok(parse_array(&body, "scopes"))
|
||||
}
|
||||
|
||||
/// Fetch variables for a `variablesReference`.
|
||||
pub async fn variables(&self, variables_reference: i64) -> Result<Vec<Variable>, DapError> {
|
||||
let body = self
|
||||
.client
|
||||
.request(
|
||||
"variables",
|
||||
json!({ "variablesReference": variables_reference }),
|
||||
CONTROL_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
Ok(parse_array(&body, "variables"))
|
||||
}
|
||||
|
||||
/// Evaluate an expression in a frame (or globally when `frame_id` is `None`).
|
||||
pub async fn evaluate(
|
||||
&self,
|
||||
expression: &str,
|
||||
frame_id: Option<i64>,
|
||||
) -> Result<String, DapError> {
|
||||
let mut args = json!({ "expression": expression, "context": "watch" });
|
||||
if let Some(frame_id) = frame_id {
|
||||
args["frameId"] = json!(frame_id);
|
||||
}
|
||||
let body = self.client.request("evaluate", args, CONTROL_TIMEOUT).await?;
|
||||
Ok(body.get("result").and_then(Value::as_str).unwrap_or("").to_string())
|
||||
}
|
||||
|
||||
/// Set a variable's value in a scope/structure; returns the adapter's rendered new value.
|
||||
pub async fn set_variable(
|
||||
&self,
|
||||
variables_reference: i64,
|
||||
name: &str,
|
||||
value: &str,
|
||||
) -> Result<String, DapError> {
|
||||
let body = self
|
||||
.client
|
||||
.request(
|
||||
"setVariable",
|
||||
json!({ "variablesReference": variables_reference, "name": name, "value": value }),
|
||||
CONTROL_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
Ok(body.get("value").and_then(Value::as_str).unwrap_or(value).to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminate_all_is_a_noop_when_no_sessions() {
|
||||
let service = DapService::new();
|
||||
service.terminate_all().await;
|
||||
assert!(service.list().await.is_empty());
|
||||
}
|
||||
}
|
||||
83
crates/luxe-dap/src/service/breakpoints.rs
Normal file
83
crates/luxe-dap/src/service/breakpoints.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
//! Breakpoints — setting them, and saying which ones did not take.
|
||||
|
||||
use super::{FunctionBreakpoint, SourceBreakpoint, CONTROL_TIMEOUT};
|
||||
use crate::client::{DapClient, DapError};
|
||||
use crate::protocol::Breakpoint;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Send a `setBreakpoints` request for one source file (with optional conditions) and parse the
|
||||
/// results.
|
||||
pub async fn set_breakpoints(
|
||||
client: &DapClient,
|
||||
path: &str,
|
||||
breakpoints: &[SourceBreakpoint],
|
||||
) -> Result<Vec<Breakpoint>, DapError> {
|
||||
let breakpoints: Vec<Value> = breakpoints
|
||||
.iter()
|
||||
.map(|bp| match &bp.condition {
|
||||
Some(condition) => json!({ "line": bp.line, "condition": condition }),
|
||||
None => json!({ "line": bp.line }),
|
||||
})
|
||||
.collect();
|
||||
let body = client
|
||||
.request(
|
||||
"setBreakpoints",
|
||||
json!({
|
||||
"source": { "path": path },
|
||||
"breakpoints": breakpoints,
|
||||
"sourceModified": false,
|
||||
}),
|
||||
CONTROL_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
Ok(parse_array(&body, "breakpoints"))
|
||||
}
|
||||
|
||||
/// Send a `setFunctionBreakpoints` request (break on entry to named functions).
|
||||
pub async fn set_function_breakpoints(
|
||||
client: &DapClient,
|
||||
breakpoints: &[FunctionBreakpoint],
|
||||
) -> Result<Vec<Breakpoint>, DapError> {
|
||||
let breakpoints: Vec<Value> = breakpoints
|
||||
.iter()
|
||||
.map(|bp| match &bp.condition {
|
||||
Some(condition) => json!({ "name": bp.name, "condition": condition }),
|
||||
None => json!({ "name": bp.name }),
|
||||
})
|
||||
.collect();
|
||||
let body = client
|
||||
.request("setFunctionBreakpoints", json!({ "breakpoints": breakpoints }), CONTROL_TIMEOUT)
|
||||
.await?;
|
||||
Ok(parse_array(&body, "breakpoints"))
|
||||
}
|
||||
|
||||
/// Parse a typed array out of a response body field, dropping malformed entries.
|
||||
pub(super) fn parse_array<T: serde::de::DeserializeOwned>(body: &Value, field: &str) -> Vec<T> {
|
||||
body.get(field)
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| items.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Each requested breakpoint in `path` the adapter did not bind, with its reason.
|
||||
///
|
||||
/// Answers line up with requests by position, as the protocol says; a request with no answer at
|
||||
/// all was not bound either.
|
||||
pub(super) fn unverified(
|
||||
path: &str,
|
||||
requested: &[SourceBreakpoint],
|
||||
bound: &[Breakpoint],
|
||||
) -> Vec<String> {
|
||||
requested
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, request)| match bound.get(index) {
|
||||
Some(answer) if answer.verified => None,
|
||||
Some(answer) => {
|
||||
let why = answer.message.as_deref().unwrap_or("not verified by the adapter");
|
||||
Some(format!("{path}:{}: {why}", request.line))
|
||||
}
|
||||
None => Some(format!("{path}:{}: the adapter did not answer for it", request.line)),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
194
crates/luxe-dap/src/service/startup.rs
Normal file
194
crates/luxe-dap/src/service/startup.rs
Normal file
@@ -0,0 +1,194 @@
|
||||
//! Startup — the launch and attach choreography, step by step.
|
||||
//!
|
||||
//! initialize → launch/attach → `initialized` → breakpoints → configurationDone → first stop. Each
|
||||
//! step that can fail says what happened in the user's terms, with whatever the adapter wrote to
|
||||
//! stderr, because an adapter that cannot start usually explains itself there and nowhere else.
|
||||
|
||||
use super::{breakpoints, resolve, stop_timeout, BreakpointRequest, CONTROL_TIMEOUT};
|
||||
use crate::client::{DapClient, DapError, PendingRequest};
|
||||
use crate::protocol::StoppedBody;
|
||||
use serde_json::{json, Value};
|
||||
use std::time::Duration;
|
||||
|
||||
const INIT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Said when attaching fails quietly, which is how a refused ptrace looks from here.
|
||||
///
|
||||
/// An adapter that never answers has not failed in any way it will tell us about: `gdb
|
||||
/// --interpreter=dap` asked to attach to a process it may not ptrace simply goes quiet. An internal
|
||||
/// `request 'event' timed out` would name a wait instead of the situation, for the failure a user
|
||||
/// can most readily fix.
|
||||
const PTRACE_HINT: &str = " — attaching to a process you did not start needs ptrace permission: \
|
||||
check `sysctl kernel.yama.ptrace_scope` (1 forbids it), or launch the \
|
||||
program from here instead of attaching";
|
||||
|
||||
/// What a handshake leaves to finish: the launch or attach reply, and whether the adapter said it
|
||||
/// takes `configurationDone`.
|
||||
pub(super) struct Started {
|
||||
pub(super) pending: PendingRequest,
|
||||
pub(super) configuration_done: bool,
|
||||
}
|
||||
|
||||
/// One launch or attach in progress.
|
||||
pub(super) struct Launch<'a> {
|
||||
pub(super) client: &'a DapClient,
|
||||
/// The adapter's id, for messages
|
||||
pub(super) adapter: &'a str,
|
||||
/// `launch` or `attach`
|
||||
pub(super) request: &'a str,
|
||||
}
|
||||
|
||||
impl Launch<'_> {
|
||||
/// Initializes the adapter, sends the launch or attach, and waits for `initialized`.
|
||||
///
|
||||
/// The request goes out before `configurationDone` but is answered after it, as the protocol's
|
||||
/// choreography has it, so its reply is returned to await later. It is written inline rather
|
||||
/// than from a spawned task, which is what keeps the two writes in order.
|
||||
pub(super) async fn handshake(&self, request_args: Value) -> Result<Started, DapError> {
|
||||
let init_args = json!({
|
||||
"clientID": "luxe",
|
||||
"adapterID": self.adapter,
|
||||
"linesStartAt1": true,
|
||||
"columnsStartAt1": true,
|
||||
"pathFormat": "path",
|
||||
"supportsRunInTerminalRequest": false,
|
||||
});
|
||||
let capabilities = match self.client.request("initialize", init_args, INIT_TIMEOUT).await {
|
||||
Ok(capabilities) => capabilities,
|
||||
Err(error) => {
|
||||
let message = format!("the {} adapter did not initialize: {error}", self.adapter);
|
||||
return Err(self.with_stderr(message).await);
|
||||
}
|
||||
};
|
||||
let configuration_done = capabilities
|
||||
.get("supportsConfigurationDoneRequest")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
// The program does not exist yet, so anything said so far was the adapter's own.
|
||||
self.client.discard_output_so_far();
|
||||
// an adapter that answered and died at once loses the race to this write, not to the wait
|
||||
let pending = match self.client.write_request(self.request, request_args).await {
|
||||
Ok(pending) => pending,
|
||||
Err(DapError::Cancelled | DapError::Io(_)) => return Err(self.exited_starting().await),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
// Quiet is the failure here; see [`PTRACE_HINT`] for why it is named, not a timeout.
|
||||
match self.client.wait_for_initialized(INIT_TIMEOUT).await {
|
||||
Ok(()) => {}
|
||||
Err(DapError::Cancelled) => return Err(self.exited_starting().await),
|
||||
Err(_) => {
|
||||
let mut message = format!(
|
||||
"the {} adapter never finished starting ({}s)",
|
||||
self.adapter,
|
||||
INIT_TIMEOUT.as_secs()
|
||||
);
|
||||
self.hint(&mut message);
|
||||
return Err(self.with_stderr(message).await);
|
||||
}
|
||||
}
|
||||
Ok(Started { pending, configuration_done })
|
||||
}
|
||||
|
||||
/// Sets the breakpoints and finishes configuration, returning the breakpoints that did not
|
||||
/// bind.
|
||||
///
|
||||
/// A refused `configurationDone` from an adapter that advertised it is a failed start, since
|
||||
/// the program never runs. One that never advertised it is still sent it, and its refusal is
|
||||
/// only logged: the protocol says not to ask, and some adapters need asking anyway.
|
||||
pub(super) async fn configure(
|
||||
&self,
|
||||
requests: &[BreakpointRequest],
|
||||
cwd: &str,
|
||||
advertised: bool,
|
||||
) -> Result<Vec<String>, DapError> {
|
||||
let mut unverified = Vec::new();
|
||||
for request in requests {
|
||||
let path = resolve(&request.path, cwd);
|
||||
match breakpoints::set_breakpoints(self.client, &path, &request.breakpoints).await {
|
||||
Ok(bound) => {
|
||||
unverified.extend(breakpoints::unverified(&path, &request.breakpoints, &bound));
|
||||
}
|
||||
Err(error) => unverified.push(format!("{path}: {error}")),
|
||||
}
|
||||
}
|
||||
match self.client.request("configurationDone", Value::Null, CONTROL_TIMEOUT).await {
|
||||
Ok(_) => {}
|
||||
Err(error) if !advertised => {
|
||||
let adapter = self.adapter;
|
||||
tracing::debug!(%error, adapter, "unadvertised configurationDone failed");
|
||||
}
|
||||
Err(error) => {
|
||||
let message =
|
||||
format!("the {} adapter refused `configurationDone`: {error}", self.adapter);
|
||||
return Err(self.with_stderr(message).await);
|
||||
}
|
||||
}
|
||||
Ok(unverified)
|
||||
}
|
||||
|
||||
/// Awaits the launch or attach reply, then the first stop or the end of the program.
|
||||
pub(super) async fn first_stop(
|
||||
&self,
|
||||
pending: PendingRequest,
|
||||
) -> Result<Option<StoppedBody>, DapError> {
|
||||
let request = self.request;
|
||||
// An adapter that never answers goes quiet for the whole launch timeout; see
|
||||
// [`PTRACE_HINT`].
|
||||
if let Err(error) = self.client.await_response(pending, request, LAUNCH_TIMEOUT).await {
|
||||
let adapter = self.adapter;
|
||||
let mut message = match error {
|
||||
DapError::Cancelled => {
|
||||
format!("the {adapter} adapter exited before answering `{request}`")
|
||||
}
|
||||
DapError::RequestFailed { message, .. } => {
|
||||
format!("the {adapter} adapter refused `{request}`: {message}")
|
||||
}
|
||||
_ => format!(
|
||||
"the {adapter} adapter did not answer `{request}` within {}s",
|
||||
LAUNCH_TIMEOUT.as_secs()
|
||||
),
|
||||
};
|
||||
self.hint(&mut message);
|
||||
return Err(self.with_stderr(message).await);
|
||||
}
|
||||
// The adapter accepted the launch or attach and then reported nothing. `gdb
|
||||
// --interpreter=dap` does exactly that when asked to attach to a process it may not
|
||||
// ptrace: it answers the request, and no stop ever comes.
|
||||
match self.client.wait_for_stop_or_terminate(stop_timeout()).await {
|
||||
Ok(stop) => Ok(stop),
|
||||
Err(DapError::Timeout { .. }) => {
|
||||
let mut message = format!(
|
||||
"the {} adapter accepted `{request}` but the program never stopped or \
|
||||
exited ({}s)",
|
||||
self.adapter,
|
||||
stop_timeout().as_secs()
|
||||
);
|
||||
self.hint(&mut message);
|
||||
Err(DapError::StartFailed(message))
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// The adapter went away after `initialize`, said with whatever it printed on the way out.
|
||||
async fn exited_starting(&self) -> DapError {
|
||||
let mut message = format!("the {} adapter exited while starting", self.adapter);
|
||||
self.hint(&mut message);
|
||||
self.with_stderr(message).await
|
||||
}
|
||||
|
||||
fn hint(&self, message: &mut String) {
|
||||
if self.request == "attach" {
|
||||
message.push_str(PTRACE_HINT);
|
||||
}
|
||||
}
|
||||
|
||||
/// `message`, with what the adapter wrote to stderr when it wrote anything.
|
||||
async fn with_stderr(&self, message: String) -> DapError {
|
||||
DapError::StartFailed(match self.client.adapter_stderr().await {
|
||||
stderr if stderr.is_empty() => message,
|
||||
stderr => format!("{message}; the adapter said:\n{stderr}"),
|
||||
})
|
||||
}
|
||||
}
|
||||
600
crates/luxe-dap/src/tool.rs
Normal file
600
crates/luxe-dap/src/tool.rs
Normal file
@@ -0,0 +1,600 @@
|
||||
//! The `debug` tool — one action-enum surface over the DAP service.
|
||||
//!
|
||||
//! Read actions (threads/stack_trace/scopes/variables/output/sessions) never mutate program state;
|
||||
//! exec actions (launch/attach/breakpoints/continue/step/pause/evaluate/terminate) run the
|
||||
//! debuggee and are gated whenever the permission hook is enabled (the `debug` tool is classified
|
||||
//! mutating). On every stop the result auto-injects the top frame + locals so the model sees where
|
||||
//! it is without extra round-trips.
|
||||
|
||||
use crate::protocol::StoppedBody;
|
||||
use crate::service::{
|
||||
BreakpointRequest, DapService, DapSession, FunctionBreakpoint, SourceBreakpoint,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::{Tool, ToolContext, ToolResultData};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
mod failure;
|
||||
mod schema;
|
||||
|
||||
use failure::Failure;
|
||||
|
||||
/// Max locals rendered in an auto stop-summary.
|
||||
const MAX_LOCALS: usize = 24;
|
||||
|
||||
/// The `debug` tool.
|
||||
pub struct DebugTool {
|
||||
service: Arc<DapService>,
|
||||
}
|
||||
|
||||
impl DebugTool {
|
||||
/// Create the tool over a shared warm debug service.
|
||||
pub fn new(service: Arc<DapService>) -> Self {
|
||||
Self { service }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for DebugTool {
|
||||
fn name(&self) -> &str {
|
||||
"debug"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
schema::schema()
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let Some(action) = args.get("action").and_then(|v| v.as_str()) else {
|
||||
return ToolResultData::error("Error: 'action' is required");
|
||||
};
|
||||
match self.dispatch(action, &args, cx).await {
|
||||
Ok(text) => ToolResultData::text(text),
|
||||
Err(failure) => ToolResultData::error(failure.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DebugTool {
|
||||
async fn dispatch(
|
||||
&self,
|
||||
action: &str,
|
||||
args: &serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
) -> Result<String, Failure> {
|
||||
match action {
|
||||
"launch" => self.launch(args, cx).await,
|
||||
"attach" => self.attach(args, cx).await,
|
||||
"sessions" => Ok(self.sessions().await),
|
||||
_ => {
|
||||
// All other actions operate on an existing session.
|
||||
let id = str_arg(args, "session").ok_or("Error: 'session' is required")?;
|
||||
let session = self.service.get(&id).await.ok_or_else(|| {
|
||||
format!(
|
||||
"Error: no active debug session '{id}'. It may have ended — use \
|
||||
action=sessions to list, or launch/attach to start one."
|
||||
)
|
||||
})?;
|
||||
// A program that ran to completion keeps its session (is_terminated) but its
|
||||
// runtime is gone; give a clear message instead of a low-level adapter error.
|
||||
if session.client.is_terminated() && Self::requires_live_program(action) {
|
||||
return Err(Failure::Usage(format!(
|
||||
"Error: debug session '{id}' has ended (program terminated); its runtime \
|
||||
state is gone. Use action=output for remaining output, or launch/attach \
|
||||
again to inspect."
|
||||
)));
|
||||
}
|
||||
self.session_action(action, &session, args).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn launch(&self, args: &serde_json::Value, cx: &ToolContext) -> Result<String, Failure> {
|
||||
let program = str_arg(args, "program").ok_or("Error: 'program' is required for launch")?;
|
||||
let cwd = str_arg(args, "cwd").unwrap_or_else(|| cx.cwd.display().to_string());
|
||||
let program_abs = crate::service::resolve(&program, &cwd);
|
||||
let outcome = self
|
||||
.service
|
||||
.launch(
|
||||
program_abs,
|
||||
string_array(args, "args"),
|
||||
cwd,
|
||||
args.get("stopOnEntry").and_then(|v| v.as_bool()).unwrap_or(false),
|
||||
breakpoint_requests(args),
|
||||
str_arg(args, "adapter"),
|
||||
)
|
||||
.await?;
|
||||
Ok(self.report(&outcome).await)
|
||||
}
|
||||
|
||||
/// What a launch or attach says: the session, its stop, what did not take, its output.
|
||||
async fn report(&self, outcome: &crate::service::LaunchOutcome) -> String {
|
||||
let mut out = format!("session {} ({})\n", outcome.session_id, outcome.adapter_id);
|
||||
if let Some(session) = self.service.get(&outcome.session_id).await {
|
||||
out.push_str(&stop_summary(&session, &outcome.stop).await);
|
||||
} else if outcome.terminated {
|
||||
out.push_str("Program terminated.\n");
|
||||
}
|
||||
if !outcome.unverified.is_empty() {
|
||||
let unverified = outcome.unverified.join("\n ");
|
||||
out.push_str(&format!("\nBreakpoints not set:\n {unverified}\n"));
|
||||
}
|
||||
if !outcome.output.is_empty() {
|
||||
out.push_str(&format!("\n--- output ---\n{}", tail(&outcome.output)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
async fn attach(&self, args: &serde_json::Value, cx: &ToolContext) -> Result<String, Failure> {
|
||||
let pid = args.get("pid").and_then(serde_json::Value::as_i64);
|
||||
let port = args.get("port").and_then(serde_json::Value::as_i64);
|
||||
if pid.is_none() && port.is_none() {
|
||||
return Err("Error: attach needs a 'pid' or 'port'".into());
|
||||
}
|
||||
let cwd = str_arg(args, "cwd").unwrap_or_else(|| cx.cwd.display().to_string());
|
||||
let outcome = self
|
||||
.service
|
||||
.attach(pid, port, cwd, breakpoint_requests(args), str_arg(args, "adapter"))
|
||||
.await?;
|
||||
Ok(self.report(&outcome).await)
|
||||
}
|
||||
|
||||
async fn session_action(
|
||||
&self,
|
||||
action: &str,
|
||||
session: &DapSession,
|
||||
args: &serde_json::Value,
|
||||
) -> Result<String, Failure> {
|
||||
let thread = args.get("threadId").and_then(serde_json::Value::as_i64);
|
||||
match action {
|
||||
"set_breakpoints" => set_breakpoints(session, args).await,
|
||||
"set_function_breakpoints" => set_function_breakpoints(session, args).await,
|
||||
"set_variable" => set_variable(session, args).await,
|
||||
"continue" => Ok(stop_summary(session, &session.continue_(thread).await?).await),
|
||||
"next" => Ok(stop_summary(session, &session.step("next", thread).await?).await),
|
||||
"step_in" => Ok(stop_summary(session, &session.step("stepIn", thread).await?).await),
|
||||
"step_out" => Ok(stop_summary(session, &session.step("stepOut", thread).await?).await),
|
||||
"pause" => {
|
||||
session.pause(thread).await?;
|
||||
Ok("pause requested".to_string())
|
||||
}
|
||||
"threads" => {
|
||||
let threads = session.threads().await?;
|
||||
Ok(threads
|
||||
.iter()
|
||||
.map(|t| format!("{}: {}", t.id, t.name))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"))
|
||||
}
|
||||
"stack_trace" => {
|
||||
let frames = session.stack_trace(thread).await?;
|
||||
Ok(render_frames(&frames, &session.cwd))
|
||||
}
|
||||
"scopes" => {
|
||||
let frame_id = args
|
||||
.get("frameId")
|
||||
.and_then(serde_json::Value::as_i64)
|
||||
.ok_or("Error: 'frameId' is required")?;
|
||||
let scopes = session.scopes(frame_id).await?;
|
||||
Ok(scopes
|
||||
.iter()
|
||||
.map(|s| format!("{} (ref {})", s.name, s.variables_reference))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"))
|
||||
}
|
||||
"variables" => {
|
||||
let vref = args
|
||||
.get("variablesReference")
|
||||
.and_then(serde_json::Value::as_i64)
|
||||
.ok_or("Error: 'variablesReference' is required")?;
|
||||
let vars = session.variables(vref).await?;
|
||||
Ok(render_variables(&vars))
|
||||
}
|
||||
"evaluate" => evaluate(session, args).await,
|
||||
"output" => Ok(tail(&session.client.output_for_display())),
|
||||
"terminate" => {
|
||||
self.service.terminate(&session.id).await?;
|
||||
Ok(format!("terminated session {}", session.id))
|
||||
}
|
||||
other => Err(Failure::Usage(format!("Error: unknown action '{other}'"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an action needs the debuggee still running (false for output/terminate, which are
|
||||
/// meaningful on an already-ended session).
|
||||
fn requires_live_program(action: &str) -> bool {
|
||||
!matches!(action, "output" | "terminate")
|
||||
}
|
||||
|
||||
async fn sessions(&self) -> String {
|
||||
let sessions = self.service.list().await;
|
||||
if sessions.is_empty() {
|
||||
return "No debug sessions.".to_string();
|
||||
}
|
||||
sessions
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let state = if s.terminated {
|
||||
"terminated".to_string()
|
||||
} else if s.stopped {
|
||||
match &s.stop_reason {
|
||||
Some(reason) => format!("stopped: {reason}"),
|
||||
None => "stopped".to_string(),
|
||||
}
|
||||
} else {
|
||||
"running".to_string()
|
||||
};
|
||||
format!("{} [{state}] {} · {}", s.id, s.adapter, s.program)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders a stop: reason + top frame location + top-scope locals (auto-injected context).
|
||||
async fn stop_summary(session: &DapSession, stop: &Option<StoppedBody>) -> String {
|
||||
let Some(stop) = stop else {
|
||||
return "Program terminated.".to_string();
|
||||
};
|
||||
let mut out = format!("stopped: {}", stop.reason);
|
||||
if let Some(text) = stop.text.as_deref().filter(|t| !t.is_empty()) {
|
||||
out.push_str(&format!(" — {text}"));
|
||||
}
|
||||
out.push('\n');
|
||||
|
||||
let Ok(frames) = session.stack_trace(None).await else {
|
||||
return out;
|
||||
};
|
||||
let Some(top) = frames.first() else {
|
||||
return out;
|
||||
};
|
||||
out.push_str(&format!("at {} ({})\n", top.name, frame_location(top)));
|
||||
|
||||
let scopes = session.scopes(top.id).await.unwrap_or_default();
|
||||
for scope in scopes.iter().filter(|scope| shown_on_stop(scope)) {
|
||||
if let Ok(vars) = session.variables(scope.variables_reference).await {
|
||||
if !vars.is_empty() {
|
||||
out.push_str(&format!("{}:\n{}\n", scope.name, render_variables(&vars)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a stop shows this scope's variables unasked.
|
||||
///
|
||||
/// Every cheap scope but the registers: `gdb` splits a frame into Arguments and Locals, and taking
|
||||
/// only the first showed the arguments and never the locals, while a frame with no debug info
|
||||
/// offered its 85 registers in their place.
|
||||
fn shown_on_stop(scope: &crate::protocol::Scope) -> bool {
|
||||
let registers = scope.presentation_hint.as_deref() == Some("registers")
|
||||
|| scope.name.eq_ignore_ascii_case("registers");
|
||||
!scope.expensive && !registers
|
||||
}
|
||||
|
||||
/// Frames this deep or deeper are listed only when they are the program's own.
|
||||
const FRAMES_ALWAYS_SHOWN: usize = 3;
|
||||
|
||||
/// A stack as a list, with runs of frames outside `project` folded into a count.
|
||||
///
|
||||
/// A Rust test stopped two frames into its own code sits on 17 more of `core`, `std` and the test
|
||||
/// runner, 600 tokens that say nothing about the bug. The top frames always show, since a stop
|
||||
/// inside a library is still where the program is.
|
||||
fn render_frames(frames: &[crate::protocol::StackFrame], project: &str) -> String {
|
||||
let ours = |frame: &crate::protocol::StackFrame| {
|
||||
frame
|
||||
.source
|
||||
.as_ref()
|
||||
.and_then(|source| source.path.as_deref())
|
||||
.is_some_and(|path| Path::new(path).starts_with(project))
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
let mut folded: Vec<i64> = Vec::new();
|
||||
let fold = |lines: &mut Vec<String>, folded: &mut Vec<i64>| {
|
||||
match folded.as_slice() {
|
||||
[] => {}
|
||||
[only] => lines.push(format!("#{only} (outside the project)")),
|
||||
[first, .., last] => lines.push(format!(
|
||||
"… {} frames outside the project, #{first} to #{last}",
|
||||
folded.len()
|
||||
)),
|
||||
}
|
||||
folded.clear();
|
||||
};
|
||||
for (depth, frame) in frames.iter().enumerate() {
|
||||
if depth < FRAMES_ALWAYS_SHOWN || ours(frame) {
|
||||
fold(&mut lines, &mut folded);
|
||||
lines.push(format!("#{} {} ({})", frame.id, frame.name, frame_location(frame)));
|
||||
} else {
|
||||
folded.push(frame.id);
|
||||
}
|
||||
}
|
||||
fold(&mut lines, &mut folded);
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn frame_location(frame: &crate::protocol::StackFrame) -> String {
|
||||
let file = frame
|
||||
.source
|
||||
.as_ref()
|
||||
.and_then(|s| s.name.clone().or_else(|| s.path.clone()))
|
||||
.unwrap_or_else(|| "?".to_string());
|
||||
format!("{file}:{}", frame.line)
|
||||
}
|
||||
|
||||
fn render_variables(vars: &[crate::protocol::Variable]) -> String {
|
||||
let mut out: Vec<String> = vars
|
||||
.iter()
|
||||
.take(MAX_LOCALS)
|
||||
.map(|v| {
|
||||
// A structured value can render as nothing at all (`gdb` on a slice), which read as
|
||||
// a variable without one; the reference is how to look inside
|
||||
let value = match (v.value.is_empty(), v.variables_reference) {
|
||||
(true, 0) => "\"\"".to_string(),
|
||||
(true, reference) => format!("{{…}} (variablesReference {reference})"),
|
||||
(false, 0) => v.value.clone(),
|
||||
(false, reference) => format!("{} (variablesReference {reference})", v.value),
|
||||
};
|
||||
match &v.type_name {
|
||||
Some(ty) if !ty.is_empty() => format!(" {} : {ty} = {value}", v.name),
|
||||
_ => format!(" {} = {value}", v.name),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if vars.len() > MAX_LOCALS {
|
||||
out.push(format!(" … {} more", vars.len() - MAX_LOCALS));
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// Keep only the tail of possibly-long program output.
|
||||
fn tail(output: &str) -> String {
|
||||
const MAX: usize = 4000;
|
||||
if output.len() <= MAX {
|
||||
return output.to_string();
|
||||
}
|
||||
format!("…{}", &output[luxe_core::output_limit::ceil_boundary(output, output.len() - MAX)..])
|
||||
}
|
||||
|
||||
/// Parse launch/attach breakpoints: `[{path, lines:[..], conditions?:[..]}]` or
|
||||
/// `[{path, breakpoints:[{line, condition?}]}]`. Per-line conditions align with `lines` by index;
|
||||
/// a `conditions` list shorter than `lines` leaves the rest unconditional.
|
||||
fn breakpoint_requests(args: &serde_json::Value) -> Vec<BreakpointRequest> {
|
||||
args.get("breakpoints")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|entries| entries.iter().filter_map(parse_breakpoint_entry).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn parse_breakpoint_entry(entry: &serde_json::Value) -> Option<BreakpointRequest> {
|
||||
let path = entry.get("path")?.as_str()?.to_string();
|
||||
// Explicit `breakpoints: [{line, condition?}]` form.
|
||||
if let Some(list) = entry.get("breakpoints").and_then(|v| v.as_array()) {
|
||||
let breakpoints = list
|
||||
.iter()
|
||||
.filter_map(|bp| {
|
||||
Some(SourceBreakpoint {
|
||||
line: bp.get("line")?.as_i64()?,
|
||||
condition: bp.get("condition").and_then(|c| c.as_str()).map(str::to_string),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
return Some(BreakpointRequest { path, breakpoints });
|
||||
}
|
||||
// Simple `lines: [..]` (+ optional aligned `conditions: [..]`) form.
|
||||
let conditions = entry.get("conditions").and_then(|v| v.as_array());
|
||||
let breakpoints = entry
|
||||
.get("lines")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|lines| {
|
||||
lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, line)| {
|
||||
Some(SourceBreakpoint {
|
||||
line: line.as_i64()?,
|
||||
condition: conditions
|
||||
.and_then(|c| c.get(index))
|
||||
.and_then(|c| c.as_str())
|
||||
.map(str::to_string),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Some(BreakpointRequest { path, breakpoints })
|
||||
}
|
||||
|
||||
fn str_arg(args: &serde_json::Value, key: &str) -> Option<String> {
|
||||
args.get(key).and_then(|v| v.as_str()).map(str::to_string)
|
||||
}
|
||||
|
||||
fn string_array(args: &serde_json::Value, key: &str) -> Vec<String> {
|
||||
args.get(key)
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn int_array(args: &serde_json::Value, key: &str) -> Vec<i64> {
|
||||
args.get(key)
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| a.iter().filter_map(serde_json::Value::as_i64).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Sets the breakpoints for one file's lines.
|
||||
async fn set_breakpoints(
|
||||
session: &DapSession,
|
||||
args: &serde_json::Value,
|
||||
) -> Result<String, Failure> {
|
||||
let path = str_arg(args, "path").ok_or("Error: 'path' is required")?;
|
||||
let condition = str_arg(args, "condition");
|
||||
let breakpoints: Vec<SourceBreakpoint> = int_array(args, "lines")
|
||||
.into_iter()
|
||||
.map(|line| SourceBreakpoint { line, condition: condition.clone() })
|
||||
.collect();
|
||||
let path_abs = crate::service::resolve(&path, &session.cwd);
|
||||
let bps = crate::service::set_breakpoints(&session.client, &path_abs, &breakpoints).await?;
|
||||
let verified = bps.iter().filter(|b| b.verified).count();
|
||||
Ok(format!("set {} breakpoint(s) in {path}, {verified} verified", bps.len()))
|
||||
}
|
||||
|
||||
/// Sets breakpoints on functions by name.
|
||||
async fn set_function_breakpoints(
|
||||
session: &DapSession,
|
||||
args: &serde_json::Value,
|
||||
) -> Result<String, Failure> {
|
||||
let condition = str_arg(args, "condition");
|
||||
let breakpoints: Vec<FunctionBreakpoint> = string_array(args, "functions")
|
||||
.into_iter()
|
||||
.map(|name| FunctionBreakpoint { name, condition: condition.clone() })
|
||||
.collect();
|
||||
if breakpoints.is_empty() {
|
||||
return Err("Error: 'functions' is required".into());
|
||||
}
|
||||
let bps = crate::service::set_function_breakpoints(&session.client, &breakpoints).await?;
|
||||
let verified = bps.iter().filter(|b| b.verified).count();
|
||||
Ok(format!("set {} function breakpoint(s), {verified} verified", bps.len()))
|
||||
}
|
||||
|
||||
/// Changes a variable's value in the stopped frame.
|
||||
async fn set_variable(session: &DapSession, args: &serde_json::Value) -> Result<String, Failure> {
|
||||
let vref = args
|
||||
.get("variablesReference")
|
||||
.and_then(serde_json::Value::as_i64)
|
||||
.ok_or("Error: 'variablesReference' is required")?;
|
||||
let name = str_arg(args, "name").ok_or("Error: 'name' is required")?;
|
||||
let value = str_arg(args, "value").ok_or("Error: 'value' is required")?;
|
||||
let updated = session.set_variable(vref, &name, &value).await?;
|
||||
Ok(format!("{name} = {updated}"))
|
||||
}
|
||||
|
||||
/// Evaluates an expression in a frame, the stopped top one unless told otherwise.
|
||||
async fn evaluate(session: &DapSession, args: &serde_json::Value) -> Result<String, Failure> {
|
||||
let expr = str_arg(args, "expression").ok_or("Error: 'expression' is required")?;
|
||||
// Default to the stopped top frame so an expression over locals resolves without a
|
||||
// manual stack_trace first (evaluating globally can't see locals — a common trap).
|
||||
let frame_id = match args.get("frameId").and_then(serde_json::Value::as_i64) {
|
||||
Some(id) => Some(id),
|
||||
None => session
|
||||
.stack_trace(None)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|frames| frames.first().map(|frame| frame.id)),
|
||||
};
|
||||
Ok(session.evaluate(&expr, frame_id).await?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::DebugTool;
|
||||
use crate::protocol::{Scope, Source, StackFrame, Variable};
|
||||
|
||||
fn frame(id: i64, path: &str) -> StackFrame {
|
||||
StackFrame {
|
||||
id,
|
||||
name: format!("f{id}"),
|
||||
source: Some(Source { name: Some("x.rs".into()), path: Some(path.into()) }),
|
||||
line: 1,
|
||||
column: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The break this catches: the tail of long output was a byte slice, which panics the tool
|
||||
/// call when it lands inside a multibyte char.
|
||||
#[test]
|
||||
fn a_long_tail_is_cut_on_a_char_boundary() {
|
||||
let output = format!("x{}y", "é".repeat(2_500));
|
||||
let tail = super::tail(&output);
|
||||
assert!(tail.starts_with('…') && tail.len() <= 4_000 + '…'.len_utf8(), "{}", tail.len());
|
||||
assert!(tail[..tail.len() - 1].chars().skip(1).all(|c| c == 'é'), "{tail}");
|
||||
}
|
||||
|
||||
/// Past the top few, frames outside the project fold into a count, and the project's own
|
||||
/// frames still show wherever they sit.
|
||||
#[test]
|
||||
fn library_frames_fold_into_a_count() {
|
||||
let mut frames: Vec<StackFrame> =
|
||||
(0..3).map(|id| frame(id, "/rustc/abc/library/core/x.rs")).collect();
|
||||
frames.push(frame(3, "/proj/src/lib.rs"));
|
||||
frames.extend((4..9).map(|id| frame(id, "/rustc/abc/library/std/x.rs")));
|
||||
frames.push(frame(9, "/proj/src/main.rs"));
|
||||
frames.push(frame(10, "/home/me/.cargo/registry/tokio/x.rs"));
|
||||
let shown = super::render_frames(&frames, "/proj");
|
||||
assert_eq!(
|
||||
shown,
|
||||
"#0 f0 (x.rs:1)\n#1 f1 (x.rs:1)\n#2 f2 (x.rs:1)\n#3 f3 (x.rs:1)\n\
|
||||
… 5 frames outside the project, #4 to #8\n#9 f9 (x.rs:1)\n#10 (outside the project)"
|
||||
);
|
||||
// a sibling directory sharing the prefix is not the project
|
||||
assert!(super::render_frames(
|
||||
&[frame(0, "/a"), frame(1, "/a"), frame(2, "/a"), frame(3, "/projector/x.rs")],
|
||||
"/proj"
|
||||
)
|
||||
.ends_with("#3 (outside the project)"));
|
||||
}
|
||||
|
||||
/// Every cheap scope shows on a stop, so the locals come with the arguments; registers and
|
||||
/// expensive scopes do not.
|
||||
#[test]
|
||||
fn a_stop_shows_every_cheap_scope_but_registers() {
|
||||
let scope = |name: &str, hint: Option<&str>, expensive: bool| Scope {
|
||||
name: name.into(),
|
||||
variables_reference: 1,
|
||||
expensive,
|
||||
presentation_hint: hint.map(str::to_string),
|
||||
};
|
||||
assert!(super::shown_on_stop(&scope("Arguments", Some("arguments"), false)));
|
||||
assert!(super::shown_on_stop(&scope("Locals", None, false)));
|
||||
assert!(!super::shown_on_stop(&scope("Registers", None, false)));
|
||||
assert!(!super::shown_on_stop(&scope("CPU", Some("registers"), false)));
|
||||
assert!(!super::shown_on_stop(&scope("Globals", None, true)));
|
||||
}
|
||||
|
||||
/// A structured value says how to look inside it, and one that renders as nothing still reads
|
||||
/// as a value.
|
||||
#[test]
|
||||
fn a_structured_value_names_its_reference() {
|
||||
let var = |name: &str, value: &str, reference: i64| Variable {
|
||||
name: name.into(),
|
||||
value: value.into(),
|
||||
type_name: None,
|
||||
variables_reference: reference,
|
||||
};
|
||||
let shown = super::render_variables(&[
|
||||
var("items", "", 4),
|
||||
var("item", "0x5555", 5),
|
||||
var("sum", "0", 0),
|
||||
var("name", "", 0),
|
||||
]);
|
||||
assert_eq!(
|
||||
shown,
|
||||
" items = {…} (variablesReference 4)\n item = 0x5555 (variablesReference 5)\n \
|
||||
sum = 0\n name = \"\""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relative_path_resolves_against_the_directory_not_the_program() {
|
||||
let base = std::env::temp_dir();
|
||||
let base = base.to_string_lossy();
|
||||
let joined = std::path::Path::new(&*base).join("src/lib.rs");
|
||||
assert_eq!(crate::service::resolve("src/lib.rs", &base), joined.to_string_lossy());
|
||||
let absolute = joined.to_string_lossy();
|
||||
assert_eq!(crate::service::resolve(&absolute, "/elsewhere"), absolute);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_program_guard_allows_output_and_terminate() {
|
||||
// Actions that still make sense on an ended session.
|
||||
assert!(!DebugTool::requires_live_program("output"));
|
||||
assert!(!DebugTool::requires_live_program("terminate"));
|
||||
// Anything that touches the running program does not.
|
||||
for action in ["continue", "next", "variables", "evaluate", "set_variable", "stack_trace"] {
|
||||
assert!(DebugTool::requires_live_program(action), "{action} needs a live program");
|
||||
}
|
||||
}
|
||||
}
|
||||
38
crates/luxe-dap/src/tool/failure.rs
Normal file
38
crates/luxe-dap/src/tool/failure.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
//! Failure — why a `debug` call produced no answer.
|
||||
|
||||
use crate::client::DapError;
|
||||
|
||||
/// Why a `debug` call produced no answer.
|
||||
pub(super) enum Failure {
|
||||
/// The call was wrong: a missing argument, an unknown action, a session that is gone
|
||||
Usage(String),
|
||||
/// The debugger said no
|
||||
Dap(DapError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Failure {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Usage(message) => formatter.write_str(message),
|
||||
Self::Dap(error) => error.fmt(formatter),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Failure {
|
||||
fn from(message: String) -> Self {
|
||||
Self::Usage(message)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Failure {
|
||||
fn from(message: &str) -> Self {
|
||||
Self::Usage(message.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DapError> for Failure {
|
||||
fn from(error: DapError) -> Self {
|
||||
Self::Dap(error)
|
||||
}
|
||||
}
|
||||
63
crates/luxe-dap/src/tool/schema.rs
Normal file
63
crates/luxe-dap/src/tool/schema.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
//! The `debug` tool's schema — the action enum and what each action takes.
|
||||
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) fn schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "debug".to_string(),
|
||||
description: "Drive a real debugger (DAP): launch/attach a program, set breakpoints, step, \
|
||||
and inspect/modify state. Prefer this over print-debugging. Rust/C/C++ use \
|
||||
CodeLLDB (or lldb-dap/gdb); Python uses debugpy. Start with launch (or attach); \
|
||||
every follow-up takes the returned `session`. On each stop the result already \
|
||||
includes the top frame + locals. Params by action: \
|
||||
launch{program, args?, cwd?, breakpoints?, stopOnEntry?}; attach{pid | port}; \
|
||||
set_breakpoints{session, path, lines, condition?}; \
|
||||
set_function_breakpoints{session, functions}; \
|
||||
continue|next|step_in|step_out|pause{session, threadId?}; \
|
||||
threads|stack_trace{session}; scopes{session, frameId}; \
|
||||
variables{session, variablesReference}; \
|
||||
set_variable{session, variablesReference, name, value}; \
|
||||
evaluate{session, expression, frameId?}; output|sessions|terminate{session}."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"launch", "attach", "set_breakpoints", "set_function_breakpoints",
|
||||
"continue", "next", "step_in", "step_out", "pause", "threads",
|
||||
"stack_trace", "scopes", "variables", "set_variable", "evaluate",
|
||||
"output", "sessions", "terminate"
|
||||
],
|
||||
"description": "The debug operation to perform."
|
||||
},
|
||||
"session": { "type": "string", "description": "Session id (from launch/attach) for follow-up actions." },
|
||||
"program": { "type": "string", "description": "launch: path to the program/binary (or .py script)." },
|
||||
"args": { "type": "array", "items": { "type": "string" }, "description": "launch: program arguments." },
|
||||
"cwd": { "type": "string", "description": "launch/attach: working directory (default: tool cwd)." },
|
||||
"adapter": { "type": "string", "description": "force an adapter (debugpy|codelldb|lldb-dap|gdb)." },
|
||||
"stopOnEntry": { "type": "boolean", "description": "launch: pause at program entry (default false)." },
|
||||
"pid": { "type": "integer", "description": "attach: process id to attach to (native)." },
|
||||
"port": { "type": "integer", "description": "attach: port of a listening adapter (debugpy)." },
|
||||
"breakpoints": {
|
||||
"type": "array",
|
||||
"description": "launch/set_breakpoints: [{path, lines:[..], conditions?:[..]}] or [{path, breakpoints:[{line, condition?}]}].",
|
||||
"items": { "type": "object" }
|
||||
},
|
||||
"path": { "type": "string", "description": "set_breakpoints: source file path." },
|
||||
"lines": { "type": "array", "items": { "type": "integer" }, "description": "set_breakpoints: 1-based lines." },
|
||||
"condition": { "type": "string", "description": "set_breakpoints/set_function_breakpoints: break only when this expression is true." },
|
||||
"functions": { "type": "array", "items": { "type": "string" }, "description": "set_function_breakpoints: function names to break on." },
|
||||
"threadId": { "type": "integer", "description": "continue/step/pause/stack_trace: thread (default: last stopped)." },
|
||||
"frameId": { "type": "integer", "description": "scopes/evaluate: stack frame id." },
|
||||
"variablesReference": { "type": "integer", "description": "variables/set_variable: reference from a scope/variable." },
|
||||
"name": { "type": "string", "description": "set_variable: variable name." },
|
||||
"value": { "type": "string", "description": "set_variable: new value." },
|
||||
"expression": { "type": "string", "description": "evaluate: expression to evaluate." }
|
||||
},
|
||||
"required": ["action"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
534
crates/luxe-dap/tests/integration_debug.rs
Normal file
534
crates/luxe-dap/tests/integration_debug.rs
Normal file
@@ -0,0 +1,534 @@
|
||||
//! End-to-end `DapService` test against a Python DAP adapter stub.
|
||||
//!
|
||||
//! The stub (named `codelldb` on a temp PATH so the native-adapter resolver picks it) implements
|
||||
//! the launch choreography and a small breakpoint/step/inspect session, exercising the client's
|
||||
//! seq correlation, event folding, and settle waits without a real debugger installed.
|
||||
// These tests stand up a stub server as an executable shell script, so they are unix-only by
|
||||
// construction — the thing under test is portable, the fixture is not. Gated at the file level rather
|
||||
// than per function so a Windows `cargo test` compiles the crate instead of failing on the fixture.
|
||||
#![cfg(unix)]
|
||||
|
||||
use luxe_dap::{BreakpointRequest, DapService, FunctionBreakpoint, SourceBreakpoint};
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::sync::{Mutex, MutexGuard};
|
||||
|
||||
static ENV_LOCK: Mutex<()> = Mutex::const_new(());
|
||||
|
||||
/// One test's changes to the process environment: made under the lock every test in this binary
|
||||
/// takes, and undone when dropped, even past a failed assertion.
|
||||
struct TestEnv {
|
||||
saved: Vec<(&'static str, Option<OsString>)>,
|
||||
_lock: MutexGuard<'static, ()>,
|
||||
}
|
||||
|
||||
impl TestEnv {
|
||||
/// `dir` put in front of `PATH`, so the stub there is the adapter found.
|
||||
async fn prepend_path(dir: &Path) -> Self {
|
||||
let mut env = Self { saved: Vec::new(), _lock: ENV_LOCK.lock().await };
|
||||
let old = std::env::var_os("PATH");
|
||||
let dirs = std::iter::once(dir.to_path_buf())
|
||||
.chain(old.iter().flat_map(std::env::split_paths))
|
||||
.collect::<Vec<_>>();
|
||||
env.set("PATH", std::env::join_paths(dirs).expect("a temp dir joins PATH"));
|
||||
env
|
||||
}
|
||||
|
||||
fn set(&mut self, name: &'static str, value: impl AsRef<OsStr>) {
|
||||
self.saved.push((name, std::env::var_os(name)));
|
||||
std::env::set_var(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestEnv {
|
||||
fn drop(&mut self) {
|
||||
for (name, value) in self.saved.drain(..).rev() {
|
||||
match value {
|
||||
Some(value) => std::env::set_var(name, value),
|
||||
None => std::env::remove_var(name),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const STUB: &str = r#"#!/usr/bin/env python3
|
||||
import json, os, sys
|
||||
|
||||
# A file of this name in the working directory switches on a misbehavior
|
||||
def mode(name):
|
||||
return os.path.exists(name)
|
||||
|
||||
seq = 0
|
||||
def send(obj):
|
||||
global seq
|
||||
seq += 1
|
||||
obj["seq"] = seq
|
||||
data = json.dumps(obj).encode()
|
||||
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
|
||||
sys.stdout.buffer.write(data)
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
def read():
|
||||
header = b""
|
||||
while b"\r\n\r\n" not in header:
|
||||
ch = sys.stdin.buffer.read(1)
|
||||
if not ch:
|
||||
return None
|
||||
header += ch
|
||||
n = 0
|
||||
for line in header.split(b"\r\n"):
|
||||
if line.lower().startswith(b"content-length:"):
|
||||
n = int(line.split(b":")[1].strip())
|
||||
return json.loads(sys.stdin.buffer.read(n))
|
||||
|
||||
def respond(req, body=None):
|
||||
send({"type": "response", "request_seq": req["seq"], "success": True,
|
||||
"command": req["command"], "body": body or {}})
|
||||
|
||||
pending_start = None
|
||||
while True:
|
||||
msg = read()
|
||||
if msg is None:
|
||||
break
|
||||
cmd = msg.get("command")
|
||||
if cmd == "initialize" and mode("die_on_initialize"):
|
||||
sys.stderr.write("codelldb: this build needs a newer libpython\n")
|
||||
sys.stderr.flush()
|
||||
sys.exit(3)
|
||||
if cmd == "initialize" and mode("deaf_after_initialize"):
|
||||
# stops listening first, so the launch that follows always meets a closed pipe
|
||||
os.close(0)
|
||||
respond(msg, {"supportsConfigurationDoneRequest": True})
|
||||
sys.stderr.write("codelldb: stopped reading\n")
|
||||
sys.stderr.flush()
|
||||
import time
|
||||
time.sleep(1)
|
||||
sys.exit(6)
|
||||
if cmd == "initialize" and mode("quiet_after_initialize"):
|
||||
respond(msg, {"supportsConfigurationDoneRequest": True})
|
||||
sys.stderr.write("codelldb: no debuggee support\r\non this host\r\n")
|
||||
sys.stderr.flush()
|
||||
sys.exit(5)
|
||||
if cmd == "initialize" and mode("binary_stderr"):
|
||||
sys.stderr.buffer.write(b"\xff\xfe not text\n")
|
||||
sys.stderr.flush()
|
||||
if cmd == "initialize":
|
||||
respond(msg, {"supportsConfigurationDoneRequest": True})
|
||||
send({"type": "event", "event": "initialized"})
|
||||
elif cmd == "launch" or cmd == "attach":
|
||||
pending_start = msg # respond after configurationDone
|
||||
elif cmd == "setBreakpoints" and mode("refuse_breakpoints"):
|
||||
send({"type": "response", "request_seq": msg["seq"], "success": False,
|
||||
"command": cmd, "message": "no such source"})
|
||||
elif cmd == "setBreakpoints":
|
||||
bps = msg["arguments"]["breakpoints"]
|
||||
unbound = mode("unverified_breakpoints")
|
||||
respond(msg, {"breakpoints": [
|
||||
{"verified": False, "message": "no code at this line"} if unbound and i == 0
|
||||
else {"verified": True, "line": b["line"]} for i, b in enumerate(bps)]})
|
||||
elif cmd == "setFunctionBreakpoints":
|
||||
bps = msg["arguments"]["breakpoints"]
|
||||
respond(msg, {"breakpoints": [{"verified": True} for _ in bps]})
|
||||
elif cmd == "setVariable":
|
||||
respond(msg, {"value": msg["arguments"]["value"]})
|
||||
elif cmd == "configurationDone" and mode("refuse_configuration_done"):
|
||||
send({"type": "response", "request_seq": msg["seq"], "success": False,
|
||||
"command": cmd, "message": "not ready"})
|
||||
elif cmd == "configurationDone" and mode("die_after_configuration"):
|
||||
respond(msg)
|
||||
sys.stderr.write("codelldb: lost the debuggee\n")
|
||||
sys.stderr.flush()
|
||||
sys.exit(4)
|
||||
elif cmd == "configurationDone" and mode("refuse_launch"):
|
||||
respond(msg)
|
||||
send({"type": "response", "request_seq": pending_start["seq"], "success": False,
|
||||
"command": pending_start["command"], "message": "program not found"})
|
||||
elif cmd == "configurationDone":
|
||||
if mode("binary_stderr"):
|
||||
# a drain that stopped at the bad line has closed the pipe, and this raises
|
||||
sys.stderr.write("still talking\n")
|
||||
sys.stderr.flush()
|
||||
respond(msg)
|
||||
if pending_start:
|
||||
respond(pending_start)
|
||||
send({"type": "event", "event": "output", "body": {"category": "stdout", "output": "hello from stub\n"}})
|
||||
send({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}})
|
||||
elif cmd == "threads":
|
||||
respond(msg, {"threads": [{"id": 1, "name": "main"}]})
|
||||
elif cmd == "stackTrace":
|
||||
respond(msg, {"stackFrames": [
|
||||
{"id": 1000, "name": "compute", "line": 5, "column": 1,
|
||||
"source": {"name": "app.py", "path": "/tmp/app.py"}}
|
||||
]})
|
||||
elif cmd == "scopes":
|
||||
respond(msg, {"scopes": [{"name": "Locals", "variablesReference": 2000, "expensive": False}]})
|
||||
elif cmd == "variables":
|
||||
respond(msg, {"variables": [
|
||||
{"name": "x", "value": "42", "type": "int", "variablesReference": 0},
|
||||
{"name": "label", "value": "'answer'", "type": "str", "variablesReference": 0}
|
||||
]})
|
||||
elif cmd == "continue":
|
||||
respond(msg, {"allThreadsContinued": True})
|
||||
send({"type": "event", "event": "terminated"})
|
||||
elif cmd == "disconnect":
|
||||
respond(msg)
|
||||
break
|
||||
else:
|
||||
respond(msg)
|
||||
"#;
|
||||
|
||||
fn write_stub(dir: &std::path::Path) -> PathBuf {
|
||||
let stub = dir.join("codelldb");
|
||||
std::fs::write(&stub, STUB).unwrap();
|
||||
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
stub
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn launch_stop_inspect_continue_and_terminate() {
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
write_stub(&dir);
|
||||
|
||||
let _env = TestEnv::prepend_path(&dir).await;
|
||||
|
||||
let service = DapService::new();
|
||||
// A non-.py program resolves to the first native adapter on PATH — our `codelldb` stub.
|
||||
let outcome = service
|
||||
.launch(
|
||||
"/tmp/app".to_string(),
|
||||
vec![],
|
||||
dir.display().to_string(),
|
||||
false,
|
||||
vec![BreakpointRequest {
|
||||
path: "/tmp/app.py".to_string(),
|
||||
breakpoints: vec![SourceBreakpoint { line: 5, condition: Some("x > 0".into()) }],
|
||||
}],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("launch should succeed");
|
||||
|
||||
assert_eq!(outcome.adapter_id, "codelldb");
|
||||
let stop = outcome.stop.expect("program should stop at the breakpoint");
|
||||
assert_eq!(stop.reason, "breakpoint");
|
||||
assert!(outcome.output.contains("hello from stub"));
|
||||
|
||||
let session = service.get(&outcome.session_id).await.expect("session exists");
|
||||
|
||||
// Threads + stack.
|
||||
assert_eq!(session.threads().await.unwrap()[0].name, "main");
|
||||
let frames = session.stack_trace(None).await.unwrap();
|
||||
assert_eq!(frames[0].name, "compute");
|
||||
assert_eq!(frames[0].line, 5);
|
||||
|
||||
// Scopes + variables (auto-context path).
|
||||
let scopes = session.scopes(frames[0].id).await.unwrap();
|
||||
assert_eq!(scopes[0].name, "Locals");
|
||||
let vars = session.variables(scopes[0].variables_reference).await.unwrap();
|
||||
assert_eq!(vars.len(), 2);
|
||||
assert_eq!(vars[0].name, "x");
|
||||
assert_eq!(vars[0].value, "42");
|
||||
|
||||
// set_variable echoes the adapter's new value.
|
||||
let updated = session.set_variable(scopes[0].variables_reference, "x", "99").await.unwrap();
|
||||
assert_eq!(updated, "99");
|
||||
|
||||
// Function breakpoints verify.
|
||||
let fn_bps = luxe_dap::service::set_function_breakpoints(
|
||||
&session.client,
|
||||
&[FunctionBreakpoint { name: "compute".into(), condition: None }],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fn_bps.len(), 1);
|
||||
assert!(fn_bps[0].verified);
|
||||
|
||||
// Continue runs to completion.
|
||||
let after = session.continue_(None).await.unwrap();
|
||||
assert!(after.is_none(), "continue should run to termination");
|
||||
assert!(session.client.is_terminated());
|
||||
|
||||
service.terminate(&outcome.session_id).await.unwrap();
|
||||
assert!(service.get(&outcome.session_id).await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attach_by_pid_reaches_a_stop() {
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
write_stub(&dir);
|
||||
|
||||
let _env = TestEnv::prepend_path(&dir).await;
|
||||
|
||||
let service = DapService::new();
|
||||
let outcome = service
|
||||
.attach(Some(4321), None, dir.display().to_string(), Vec::new(), Some("codelldb".into()))
|
||||
.await
|
||||
.expect("attach should succeed");
|
||||
assert_eq!(outcome.adapter_id, "codelldb");
|
||||
assert_eq!(outcome.stop.expect("attach should stop").reason, "breakpoint");
|
||||
|
||||
let session = service.get(&outcome.session_id).await.expect("session exists");
|
||||
assert!(session.program.contains("attach pid 4321"));
|
||||
service.terminate(&outcome.session_id).await.unwrap();
|
||||
}
|
||||
|
||||
/// A resume the adapter accepts and never reports on says the program is running.
|
||||
///
|
||||
/// Adapters do this. `gdb --interpreter=dap` answers `stepIn` with `success: true` and then sends
|
||||
/// no event at all when there is nowhere to step (confirmed against the raw protocol), and no
|
||||
/// client can invent a stop that was never reported. What Luxe owes is a reply that says which
|
||||
/// situation this is: the old one was `request 'event' timed out` after the full thirty-second
|
||||
/// budget, which names an internal wait instead of the program's state and offers nothing to do
|
||||
/// about it.
|
||||
///
|
||||
/// The stub answers any command it does not recognize with a bare success, which is precisely the
|
||||
/// shape; the budget is turned down so the test costs a second rather than half a minute.
|
||||
#[tokio::test]
|
||||
async fn a_resume_that_never_stops_says_the_program_is_running() {
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
write_stub(&dir);
|
||||
|
||||
let mut env = TestEnv::prepend_path(&dir).await;
|
||||
env.set("LUXE_DAP_STOP_TIMEOUT_SECS", "1");
|
||||
|
||||
let service = DapService::new();
|
||||
let outcome = service
|
||||
.launch("/tmp/app".to_string(), vec![], "/tmp".to_string(), false, vec![], None)
|
||||
.await
|
||||
.expect("the stub launches");
|
||||
let session = service.get(&outcome.session_id).await.expect("a live session");
|
||||
|
||||
let error = session.step("next", Some(1)).await.expect_err("the stub reports no stop");
|
||||
|
||||
drop(env);
|
||||
service.terminate_all().await;
|
||||
|
||||
assert!(matches!(error, luxe_dap::DapError::StillRunning { .. }), "{error:?}");
|
||||
let refused = error.to_string();
|
||||
assert!(refused.contains("still"), "it has to name the state: {refused}");
|
||||
assert!(refused.contains("pause"), "and the action that reaches it: {refused}");
|
||||
assert!(
|
||||
!refused.contains("'event'"),
|
||||
"naming an internal wait tells the caller nothing: {refused}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A directory of this test's own, deleted when it is dropped; it reads as the path it holds.
|
||||
struct Scratch(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for Scratch {
|
||||
type Target = std::path::Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
/// A temp directory holding the stub, on `PATH` until the [`TestEnv`] drops, with `modes` on.
|
||||
async fn stub_dir(name: &str, modes: &[&str]) -> (Scratch, TestEnv) {
|
||||
let dir = Scratch(
|
||||
tempfile::Builder::new().prefix(&format!("luxe-dap-{name}-")).tempdir().expect("temp dir"),
|
||||
);
|
||||
write_stub(&dir);
|
||||
for mode in modes {
|
||||
std::fs::write(dir.join(mode), "").unwrap();
|
||||
}
|
||||
let env = TestEnv::prepend_path(&dir).await;
|
||||
(dir, env)
|
||||
}
|
||||
|
||||
async fn launch_in(
|
||||
dir: &std::path::Path,
|
||||
lines: &[i64],
|
||||
) -> Result<luxe_dap::LaunchOutcome, String> {
|
||||
let breakpoints = vec![BreakpointRequest {
|
||||
path: "/tmp/app.py".to_string(),
|
||||
breakpoints: lines.iter().map(|&line| SourceBreakpoint { line, condition: None }).collect(),
|
||||
}];
|
||||
let service = DapService::new();
|
||||
let outcome = service
|
||||
.launch("/tmp/app".to_string(), vec![], dir.display().to_string(), false, breakpoints, None)
|
||||
.await;
|
||||
service.terminate_all().await;
|
||||
outcome.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// A breakpoint the adapter would not bind is reported, by line, with the adapter's reason.
|
||||
///
|
||||
/// The break this catches: launch sent `setBreakpoints` with `let _ =`, so a refused breakpoint
|
||||
/// vanished and the model went on believing it was set.
|
||||
#[tokio::test]
|
||||
async fn breakpoints_that_did_not_take_are_reported() {
|
||||
let (dir, _env) = stub_dir("unverified", &["unverified_breakpoints"]).await;
|
||||
let outcome = launch_in(&dir, &[5, 9]).await;
|
||||
std::fs::remove_file(dir.join("unverified_breakpoints")).unwrap();
|
||||
std::fs::write(dir.join("refuse_breakpoints"), "").unwrap();
|
||||
let refused = launch_in(&dir, &[5]).await;
|
||||
|
||||
let outcome = outcome.expect("an unbound breakpoint does not fail the launch");
|
||||
assert_eq!(outcome.unverified, ["/tmp/app.py:5: no code at this line"]);
|
||||
let refused = refused.expect("a refused request does not fail it either");
|
||||
assert_eq!(refused.unverified.len(), 1);
|
||||
assert!(
|
||||
refused.unverified[0].contains("/tmp/app.py")
|
||||
&& refused.unverified[0].contains("no such source")
|
||||
);
|
||||
}
|
||||
|
||||
/// A refused `configurationDone` from an adapter that advertised it fails the launch, naming the
|
||||
/// adapter, instead of waiting out "never stopped or exited".
|
||||
#[tokio::test]
|
||||
async fn a_refused_configuration_done_fails_the_launch() {
|
||||
let (dir, _env) = stub_dir("configuration", &["refuse_configuration_done"]).await;
|
||||
let started = std::time::Instant::now();
|
||||
let outcome = launch_in(&dir, &[]).await;
|
||||
|
||||
let error = outcome.expect_err("the program never runs");
|
||||
assert!(error.contains("codelldb") && error.contains("configurationDone"), "{error}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10));
|
||||
}
|
||||
|
||||
/// An adapter that dies while starting says why, from its own stderr, and says it at once.
|
||||
///
|
||||
/// The break this catches: a stdio adapter's stderr went to the null device and a dead adapter
|
||||
/// left its request waiting out the whole timeout, so the answer was a bare timeout.
|
||||
#[tokio::test]
|
||||
async fn an_adapter_that_dies_starting_says_why() {
|
||||
let (dir, _env) = stub_dir("dies", &["die_on_initialize"]).await;
|
||||
let started = std::time::Instant::now();
|
||||
let outcome = launch_in(&dir, &[]).await;
|
||||
|
||||
let error = outcome.expect_err("nothing to launch with");
|
||||
assert!(error.contains("newer libpython"), "{error}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// A client over a script that answers nothing, and does `behavior` once its first request lands.
|
||||
async fn client_over(behavior: &str) -> luxe_dap::DapClient {
|
||||
let script = format!("import sys, time\nsys.stdin.buffer.read(1)\n{behavior}\n");
|
||||
let command = vec!["python3".to_string(), "-c".to_string(), script];
|
||||
luxe_dap::DapClient::spawn(&command, &std::env::temp_dir()).await.expect("spawned")
|
||||
}
|
||||
|
||||
/// A request in flight when the adapter exits fails at once, not at its own timeout.
|
||||
#[tokio::test]
|
||||
async fn a_request_fails_at_once_when_the_adapter_exits() {
|
||||
let client = client_over("sys.exit(0)").await;
|
||||
let started = std::time::Instant::now();
|
||||
let error = client
|
||||
.request("threads", serde_json::Value::Null, std::time::Duration::from_secs(30))
|
||||
.await
|
||||
.expect_err("nobody will answer");
|
||||
assert!(matches!(error, luxe_dap::DapError::Cancelled), "{error}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert!(client.is_terminated());
|
||||
}
|
||||
|
||||
/// A stream that breaks its framing ends the session: requests fail and it reads as over.
|
||||
///
|
||||
/// The break this catches: a read error returned before `terminated` was set, so the session
|
||||
/// never read as ended and every request waited out its timeout.
|
||||
#[tokio::test]
|
||||
async fn a_broken_stream_ends_the_session() {
|
||||
let client = client_over(
|
||||
"sys.stdout.buffer.write(b'Content-Length: nope\\r\\n\\r\\n'); sys.stdout.flush(); time.sleep(30)",
|
||||
)
|
||||
.await;
|
||||
let started = std::time::Instant::now();
|
||||
let error = client
|
||||
.request("threads", serde_json::Value::Null, std::time::Duration::from_secs(30))
|
||||
.await
|
||||
.expect_err("nobody will answer");
|
||||
assert!(matches!(error, luxe_dap::DapError::Cancelled), "{error}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert!(client.is_terminated());
|
||||
|
||||
// and one asked after the stream broke does not wait either
|
||||
let started = std::time::Instant::now();
|
||||
let again = client
|
||||
.request("threads", serde_json::Value::Null, std::time::Duration::from_secs(30))
|
||||
.await;
|
||||
assert!(again.is_err(), "{again:?}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// A launch that fails after configuration says how: an adapter that dies says it exited, with
|
||||
/// what it printed, and one that refuses passes on its own reason, neither as a 30 s silence.
|
||||
#[tokio::test]
|
||||
async fn a_failed_launch_says_how_it_failed() {
|
||||
let (dir, _env) = stub_dir("launch-fails", &["die_after_configuration"]).await;
|
||||
let died = launch_in(&dir, &[]).await;
|
||||
std::fs::remove_file(dir.join("die_after_configuration")).unwrap();
|
||||
std::fs::write(dir.join("refuse_launch"), "").unwrap();
|
||||
let refused = launch_in(&dir, &[]).await;
|
||||
|
||||
let died = died.expect_err("the adapter is gone");
|
||||
assert!(died.contains("exited") && died.contains("lost the debuggee"), "{died}");
|
||||
let refused = refused.expect_err("the adapter said no");
|
||||
assert!(refused.contains("refused") && refused.contains("program not found"), "{refused}");
|
||||
}
|
||||
|
||||
/// A stderr line that is not text does not stop the drain, which would leave the adapter writing
|
||||
/// into a closed pipe and dying of it.
|
||||
#[tokio::test]
|
||||
async fn stderr_that_is_not_text_keeps_draining() {
|
||||
let (dir, _env) = stub_dir("binary-stderr", &["binary_stderr"]).await;
|
||||
let outcome = launch_in(&dir, &[]).await;
|
||||
outcome.expect("the adapter outlives its own odd bytes");
|
||||
}
|
||||
|
||||
/// An adapter that answers `initialize` and then exits says so at once, with what it printed,
|
||||
/// instead of waiting out the start timeout and calling it slow.
|
||||
#[tokio::test]
|
||||
async fn an_adapter_that_exits_after_initialize_says_so_at_once() {
|
||||
let (dir, _env) = stub_dir("quiet", &["quiet_after_initialize"]).await;
|
||||
let started = std::time::Instant::now();
|
||||
let outcome = launch_in(&dir, &[]).await;
|
||||
|
||||
let error = outcome.expect_err("it is gone");
|
||||
assert!(error.contains("exited while starting"), "{error}");
|
||||
assert!(error.contains("no debuggee support\non this host"), "{error:?}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// An adapter that stops reading after `initialize` is reported as an exit at the launch write,
|
||||
/// the side of the race the test above only sometimes reaches.
|
||||
#[tokio::test]
|
||||
async fn a_launch_write_into_a_closed_adapter_is_an_exit() {
|
||||
let (dir, _env) = stub_dir("deaf", &["deaf_after_initialize"]).await;
|
||||
let outcome = launch_in(&dir, &[]).await;
|
||||
|
||||
let error = outcome.expect_err("it stopped listening");
|
||||
assert!(error.contains("exited while starting"), "{error}");
|
||||
assert!(error.contains("stopped reading"), "{error}");
|
||||
}
|
||||
|
||||
/// What went wrong is the variant, not a sentence to search: a caller can tell a debugger that is
|
||||
/// not installed from a start that failed from a session that is gone.
|
||||
#[tokio::test]
|
||||
async fn failures_come_back_as_the_kind_of_failure_they_are() {
|
||||
use luxe_dap::DapError;
|
||||
|
||||
let service = DapService::new();
|
||||
let unknown = service
|
||||
.launch("/tmp/app".into(), vec![], "/tmp".into(), false, vec![], Some("nope".into()))
|
||||
.await
|
||||
.expect_err("no adapter by that id");
|
||||
assert!(matches!(unknown, DapError::AdapterUnavailable(_)), "{unknown:?}");
|
||||
let gone = service.terminate("dbg-404").await.expect_err("no such session");
|
||||
assert!(matches!(gone, DapError::NoSession), "{gone:?}");
|
||||
|
||||
let (dir, _env) = stub_dir("kinds", &["refuse_configuration_done"]).await;
|
||||
let refused = service
|
||||
.launch("/tmp/app".into(), vec![], dir.display().to_string(), false, vec![], None)
|
||||
.await
|
||||
.expect_err("configurationDone is refused");
|
||||
assert!(matches!(refused, DapError::StartFailed(_)), "{refused:?}");
|
||||
}
|
||||
119
crates/luxe-dap/tests/integration_dlv.rs
Normal file
119
crates/luxe-dap/tests/integration_dlv.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! Live Delve (Go) debugging test — exercises the TCP dial-in transport end-to-end.
|
||||
//!
|
||||
//! Skips unless both `dlv` and `go` are on PATH (CI won't have them). Builds a tiny Go module in a
|
||||
//! temp dir and drives `DapService` through the real dlv DAP dial-in choreography.
|
||||
|
||||
use luxe_dap::DapService;
|
||||
use std::time::Duration;
|
||||
|
||||
fn on_path(program: &str) -> bool {
|
||||
std::env::var_os("PATH")
|
||||
.map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(program).is_file()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
// Opt-in: this drives a real dlv + Go build, which is slow and environment-sensitive, so it is
|
||||
// skipped unless `LUXE_TEST_DLV=1` (keeps the default suite fast and unpoisonable).
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn dlv_launches_go_and_hits_a_breakpoint() {
|
||||
if std::env::var("LUXE_TEST_DLV").as_deref() != Ok("1") {
|
||||
eprintln!("skipping dlv test (set LUXE_TEST_DLV=1 to run)");
|
||||
return;
|
||||
}
|
||||
if !on_path("dlv") || !on_path("go") {
|
||||
eprintln!("skipping: dlv/go not installed");
|
||||
return;
|
||||
}
|
||||
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("go.mod"), "module dbggo\ngo 1.21\n").unwrap();
|
||||
std::fs::write(
|
||||
dir.join("main.go"),
|
||||
"package main\n\nimport \"fmt\"\n\nfunc compute(n int) int {\n\ttotal := 0\n\tfor i := 0; i < n; i++ {\n\t\ttotal += i\n\t}\n\treturn total\n}\n\nfunc main() {\n\tfmt.Printf(\"result=%d\\n\", compute(5))\n}\n",
|
||||
)
|
||||
.unwrap();
|
||||
let cwd = dir.to_string_lossy().to_string();
|
||||
|
||||
// Results go to a file so they survive even when the harness drops the test's stdout for
|
||||
// debugger-process-tree commands (read /tmp/dlv-result.txt afterward).
|
||||
let result_path = "/tmp/dlv-result.txt";
|
||||
std::fs::write(result_path, "=== dlv (Go) e2e ===\n").ok();
|
||||
let mark = |line: String| {
|
||||
use std::io::Write;
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(result_path) {
|
||||
let _ = writeln!(f, "{line}");
|
||||
let _ = f.flush();
|
||||
}
|
||||
};
|
||||
|
||||
let service = DapService::new();
|
||||
mark("launching (adapter=dlv, stopOnEntry)…".to_string());
|
||||
let outcome = tokio::time::timeout(
|
||||
Duration::from_secs(40),
|
||||
service.launch(
|
||||
cwd.clone(),
|
||||
Vec::new(),
|
||||
cwd.clone(),
|
||||
true, // stopOnEntry
|
||||
Vec::new(),
|
||||
Some("dlv".to_string()),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("[dlv-test] launch hung >40s")
|
||||
.expect("launch should succeed");
|
||||
mark(format!(
|
||||
"launch OK: adapter={} terminated={} stop_reason={:?}",
|
||||
outcome.adapter_id,
|
||||
outcome.terminated,
|
||||
outcome.stop.as_ref().map(|s| s.reason.clone())
|
||||
));
|
||||
assert_eq!(outcome.adapter_id, "dlv");
|
||||
assert!(outcome.stop.is_some(), "stopOnEntry should have stopped the program");
|
||||
|
||||
// Set a breakpoint on the `total += i` line and continue to it.
|
||||
let session = service.get(&outcome.session_id).await.expect("session exists");
|
||||
let main_go = dir.join("main.go");
|
||||
let bps = tokio::time::timeout(
|
||||
Duration::from_secs(15),
|
||||
luxe_dap::service::set_breakpoints(
|
||||
&session.client,
|
||||
&main_go.to_string_lossy(),
|
||||
&[luxe_dap::SourceBreakpoint { line: 8, condition: None }],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("set_breakpoints hung")
|
||||
.expect("set_breakpoints");
|
||||
mark(format!("breakpoint line 8: {} verified", bps.iter().filter(|b| b.verified).count()));
|
||||
assert!(bps.iter().any(|b| b.verified), "breakpoint should verify");
|
||||
|
||||
let stop = tokio::time::timeout(Duration::from_secs(20), session.continue_(None))
|
||||
.await
|
||||
.expect("continue hung")
|
||||
.expect("continue");
|
||||
mark(format!("continue → stop_reason={:?}", stop.as_ref().map(|s| s.reason.clone())));
|
||||
assert!(stop.is_some(), "should stop at the breakpoint");
|
||||
|
||||
// Capture the locals at the stop (the money shot: top frame → scopes → variables).
|
||||
if let Ok(frames) = session.stack_trace(None).await {
|
||||
if let Some(top) = frames.first() {
|
||||
mark(format!("top frame: {} @ line {}", top.name, top.line));
|
||||
if let Ok(scopes) = session.scopes(top.id).await {
|
||||
if let Some(scope) = scopes.iter().find(|s| !s.expensive) {
|
||||
if let Ok(vars) = session.variables(scope.variables_reference).await {
|
||||
for v in vars.iter().take(6) {
|
||||
mark(format!(" local {} = {}", v.name, v.value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
service.terminate(&outcome.session_id).await.ok();
|
||||
mark("terminated OK — dlv e2e PASSED".to_string());
|
||||
}
|
||||
468
crates/luxe-dap/tests/integration_real_gdb.rs
Normal file
468
crates/luxe-dap/tests/integration_real_gdb.rs
Normal file
@@ -0,0 +1,468 @@
|
||||
//! Live `gdb --interpreter=dap` debugging — the first test of this crate against a real debugger.
|
||||
//!
|
||||
//! Everything else here drives a **stub** adapter: a shell script that speaks just enough DAP to
|
||||
//! answer the choreography. That proves Luxe's side of the protocol and nothing about a real one,
|
||||
//! which is how twelve lines of GPL notice came to ride into the model's context on every gdb
|
||||
//! launch — a stub has no banner to emit, so no test could see it.
|
||||
//!
|
||||
//! Skips unless `gdb` (14+, for DAP) and a C compiler are both present.
|
||||
//!
|
||||
//! ```bash
|
||||
//! cargo nextest run -p luxe-dap --run-ignored all -E 'test(real_gdb)' --no-capture
|
||||
//! ```
|
||||
|
||||
use luxe_core::tool::{Tool, ToolContext};
|
||||
use luxe_dap::DapService;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn context(cwd: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: cwd.to_path_buf(),
|
||||
session_id: "real-gdb".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn on_path(program: &str) -> bool {
|
||||
luxe_core::program::resolve(program).is_some()
|
||||
}
|
||||
|
||||
/// Whether this `gdb` speaks DAP at all (it arrived in GDB 14).
|
||||
fn gdb_speaks_dap() -> bool {
|
||||
let Ok(output) = std::process::Command::new("gdb").arg("--version").output() else {
|
||||
return false;
|
||||
};
|
||||
let banner = String::from_utf8_lossy(&output.stdout);
|
||||
banner
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().last())
|
||||
.and_then(|version| version.split('.').next()?.parse::<u32>().ok())
|
||||
.is_some_and(|major| major >= 14)
|
||||
}
|
||||
|
||||
/// A two-function C program, compiled with debug info.
|
||||
fn build(dir: &std::path::Path) -> Option<String> {
|
||||
std::fs::write(
|
||||
dir.join("main.c"),
|
||||
"#include <stdio.h>\n\
|
||||
int add(int a, int b) { int sum = a + b; return sum; }\n\
|
||||
int main(void) { int total = add(2, 3); printf(\"%d\\n\", total); return 0; }\n",
|
||||
)
|
||||
.ok()?;
|
||||
let binary = dir.join("app");
|
||||
let built = std::process::Command::new("cc")
|
||||
.args(["-g", "-O0", "-o"])
|
||||
.arg(&binary)
|
||||
.arg(dir.join("main.c"))
|
||||
.status()
|
||||
.ok()?;
|
||||
built.success().then(|| binary.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "drives a real gdb; run with --run-ignored"]
|
||||
async fn real_gdb_stops_at_a_breakpoint_and_reports_the_frame() {
|
||||
if !on_path("gdb") || !gdb_speaks_dap() || !on_path("cc") {
|
||||
eprintln!("skipping: needs gdb 14+ (DAP) and a C compiler");
|
||||
return;
|
||||
}
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let Some(program) = build(&dir) else {
|
||||
eprintln!("skipping: the fixture would not compile");
|
||||
return;
|
||||
};
|
||||
|
||||
let service = DapService::new();
|
||||
let outcome = tokio::time::timeout(
|
||||
Duration::from_secs(60),
|
||||
service.launch(
|
||||
program,
|
||||
vec![],
|
||||
dir.to_string_lossy().into_owned(),
|
||||
false,
|
||||
vec![luxe_dap::BreakpointRequest {
|
||||
path: dir.join("main.c").to_string_lossy().into_owned(),
|
||||
breakpoints: vec![luxe_dap::SourceBreakpoint { line: 2, condition: None }],
|
||||
}],
|
||||
Some("gdb".to_string()),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("gdb answers inside a minute")
|
||||
.expect("gdb launches the program");
|
||||
|
||||
eprintln!("STOP: {:?}", outcome.stop);
|
||||
eprintln!("OUTPUT: {:?}", outcome.output);
|
||||
|
||||
let stop = outcome.stop.as_ref().expect("a breakpoint on line 2 must stop the program");
|
||||
assert_eq!(stop.reason, "breakpoint", "{stop:?}");
|
||||
|
||||
// The adapter's own startup chatter is not the program's output. gdb opens with its version
|
||||
// and GPL notice tagged as `stdout`, which is indistinguishable from program output by
|
||||
// category alone — so it is dropped by *when* it arrived, before the program existed.
|
||||
assert!(
|
||||
!outcome.output.contains("GNU gdb"),
|
||||
"the adapter's banner is not program output: {:?}",
|
||||
outcome.output
|
||||
);
|
||||
assert!(!outcome.output.contains("GPL"), "nor is its license: {:?}", outcome.output);
|
||||
|
||||
service.terminate_all().await;
|
||||
}
|
||||
|
||||
/// Every remaining `debug` action, driven through the tool against real gdb.
|
||||
///
|
||||
/// `debug` carries the largest schema in the set and, until now, the least evidence: its whole
|
||||
/// suite drove a shell-script stub that answers the choreography and nothing else. A stub cannot
|
||||
/// disagree with a real debugger about a frame id, a variables reference, or what `evaluate`
|
||||
/// accepts — so these actions were, in practice, untested.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "drives a real gdb; run with --run-ignored"]
|
||||
async fn real_gdb_walks_the_whole_debug_surface() {
|
||||
if !on_path("gdb") || !gdb_speaks_dap() || !on_path("cc") {
|
||||
eprintln!("skipping: needs gdb 14+ (DAP) and a C compiler");
|
||||
return;
|
||||
}
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let Some(program) = build(&dir) else {
|
||||
eprintln!("skipping: the fixture would not compile");
|
||||
return;
|
||||
};
|
||||
let source = dir.join("main.c").to_string_lossy().into_owned();
|
||||
let cwd = dir.to_string_lossy().into_owned();
|
||||
|
||||
let service = Arc::new(DapService::new());
|
||||
let tool = luxe_dap::DebugTool::new(service.clone());
|
||||
let cx = context(&dir);
|
||||
let call = |args: serde_json::Value| {
|
||||
let tool = &tool;
|
||||
let cx = &cx;
|
||||
async move {
|
||||
let result = tool.run(args, cx).await;
|
||||
let text = result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
luxe_core::ContentBlock::Text(text) => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
(text, result.is_error)
|
||||
}
|
||||
};
|
||||
|
||||
// launch{program, cwd, stopOnEntry} — stop before any user code runs.
|
||||
let (launched, failed) = call(json!({
|
||||
"action": "launch", "program": program, "cwd": cwd, "adapter": "gdb", "stopOnEntry": true
|
||||
}))
|
||||
.await;
|
||||
assert!(!failed, "launch: {launched}");
|
||||
eprintln!("LAUNCH:\n{launched}");
|
||||
let session = launched
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.strip_prefix("session "))
|
||||
.and_then(|rest| rest.split_whitespace().next())
|
||||
.expect("launch names its session")
|
||||
.to_string();
|
||||
|
||||
// set_function_breakpoints{functions} — a breakpoint by name, not by line.
|
||||
let (set, failed) = call(
|
||||
json!({"action": "set_function_breakpoints", "session": session, "functions": ["add"]}),
|
||||
)
|
||||
.await;
|
||||
assert!(!failed, "set_function_breakpoints: {set}");
|
||||
assert!(set.contains("1 function breakpoint"), "{set}");
|
||||
|
||||
// set_breakpoints{path, lines, condition} — the conditional form, which the stub never tested.
|
||||
let (set, failed) = call(json!({
|
||||
"action": "set_breakpoints", "session": session, "path": source,
|
||||
"lines": [3], "condition": "total == 5"
|
||||
}))
|
||||
.await;
|
||||
assert!(!failed, "set_breakpoints: {set}");
|
||||
eprintln!("BREAKPOINTS: {set}");
|
||||
|
||||
// continue → the function breakpoint in add().
|
||||
let (stopped, failed) = call(json!({"action": "continue", "session": session})).await;
|
||||
assert!(!failed, "continue: {stopped}");
|
||||
eprintln!("CONTINUE:\n{stopped}");
|
||||
assert!(stopped.contains("add"), "the function breakpoint should stop in add: {stopped}");
|
||||
|
||||
// threads → at least the main thread, with an id the other actions take.
|
||||
let (threads, failed) = call(json!({"action": "threads", "session": session})).await;
|
||||
assert!(!failed, "threads: {threads}");
|
||||
let thread_id: i64 = threads
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split(':').next())
|
||||
.and_then(|id| id.trim().parse().ok())
|
||||
.unwrap_or_else(|| panic!("threads lists an id: {threads}"));
|
||||
|
||||
// stack_trace{threadId} → frames, whose ids `scopes` takes.
|
||||
let (frames, failed) =
|
||||
call(json!({"action": "stack_trace", "session": session, "threadId": thread_id})).await;
|
||||
assert!(!failed, "stack_trace: {frames}");
|
||||
eprintln!("STACK:\n{frames}");
|
||||
assert!(frames.contains("add"), "the top frame is add: {frames}");
|
||||
let frame_id: i64 = frames
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.strip_prefix('#'))
|
||||
.and_then(|rest| rest.split_whitespace().next())
|
||||
.and_then(|id| id.parse().ok())
|
||||
.unwrap_or_else(|| panic!("a frame carries an id: {frames}"));
|
||||
|
||||
// scopes{frameId} → a variables reference, which is the only way to reach `variables`.
|
||||
let (scopes, failed) =
|
||||
call(json!({"action": "scopes", "session": session, "frameId": frame_id})).await;
|
||||
assert!(!failed, "scopes: {scopes}");
|
||||
eprintln!("SCOPES:\n{scopes}");
|
||||
let vref: i64 = scopes
|
||||
.lines()
|
||||
.find_map(|line| line.rsplit_once("ref ").map(|(_, r)| r.trim_end_matches(')').to_string()))
|
||||
.and_then(|r| r.parse().ok())
|
||||
.unwrap_or_else(|| panic!("a scope carries a variables reference: {scopes}"));
|
||||
|
||||
// variables{variablesReference} → the arguments this frame was called with.
|
||||
let (vars, failed) =
|
||||
call(json!({"action": "variables", "session": session, "variablesReference": vref})).await;
|
||||
assert!(!failed, "variables: {vars}");
|
||||
eprintln!("VARIABLES:\n{vars}");
|
||||
assert!(vars.contains('a') && vars.contains('2'), "a = 2 is in scope: {vars}");
|
||||
|
||||
// set_variable{variablesReference, name, value} → and evaluate proves it took.
|
||||
let (updated, failed) = call(json!({
|
||||
"action": "set_variable", "session": session, "variablesReference": vref,
|
||||
"name": "b", "value": "40"
|
||||
}))
|
||||
.await;
|
||||
assert!(!failed, "set_variable: {updated}");
|
||||
eprintln!("SET VARIABLE: {updated}");
|
||||
|
||||
// evaluate{expression} → reads the frame we are stopped in, without being handed a frameId.
|
||||
let (evaluated, failed) =
|
||||
call(json!({"action": "evaluate", "session": session, "expression": "a + b"})).await;
|
||||
assert!(!failed, "evaluate: {evaluated}");
|
||||
eprintln!("EVALUATE a + b = {evaluated}");
|
||||
assert!(
|
||||
evaluated.contains("42"),
|
||||
"set_variable must have changed what evaluate sees: {evaluated}"
|
||||
);
|
||||
|
||||
// next — a step that gdb reports, from a frame where there is somewhere to go.
|
||||
//
|
||||
// Only `next` is asserted here. gdb answers `stepIn` with `success: true` and then sends no
|
||||
// event at all when there is nothing to step into (confirmed against the raw protocol), and no
|
||||
// client can invent a stop the adapter never reported — what Luxe owes there is a *reply that
|
||||
// says so*, which `a_resume_that_never_stops_says_the_program_is_running` covers.
|
||||
let (stepped, failed) =
|
||||
call(json!({"action": "next", "session": session, "threadId": thread_id})).await;
|
||||
assert!(!failed, "next: {stepped}");
|
||||
eprintln!("NEXT: {}", stepped.lines().next().unwrap_or(""));
|
||||
|
||||
// sessions → this one, listed.
|
||||
let (sessions, failed) = call(json!({"action": "sessions"})).await;
|
||||
assert!(!failed, "sessions: {sessions}");
|
||||
assert!(sessions.contains(&session), "the live session is listed: {sessions}");
|
||||
|
||||
// output → whatever the program has printed, without the adapter's banner.
|
||||
let (output, failed) = call(json!({"action": "output", "session": session})).await;
|
||||
assert!(!failed, "output: {output}");
|
||||
assert!(!output.contains("GNU gdb"), "the adapter's banner is not output: {output}");
|
||||
|
||||
// terminate → and the session stops being listed.
|
||||
let (ended, failed) = call(json!({"action": "terminate", "session": session})).await;
|
||||
assert!(!failed, "terminate: {ended}");
|
||||
let (sessions, _) = call(json!({"action": "sessions"})).await;
|
||||
assert!(
|
||||
!sessions.contains(&session),
|
||||
"a terminated session must not still be listed: {sessions}"
|
||||
);
|
||||
}
|
||||
|
||||
/// `launch{args, breakpoints}` and `attach{pid}` — the last of the schema, against real gdb.
|
||||
///
|
||||
/// `args` and the launch-time `breakpoints` array had never reached a debugger: the walk test sets
|
||||
/// breakpoints as a follow-up action, and a stub cannot tell whether an adapter received argv at
|
||||
/// all. `attach` was stub-only, which proves the choreography and nothing about a real process.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "drives a real gdb; run with --run-ignored"]
|
||||
async fn real_gdb_takes_program_arguments() {
|
||||
if !on_path("gdb") || !gdb_speaks_dap() || !on_path("cc") {
|
||||
eprintln!("skipping: needs gdb 14+ (DAP) and a C compiler");
|
||||
return;
|
||||
}
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
|
||||
// Reads argv into a local, so `args` arriving is observable in a variable rather than inferred.
|
||||
std::fs::write(
|
||||
dir.join("main.c"),
|
||||
"#include <stdio.h>\n\
|
||||
int main(int argc, char **argv) {\n\
|
||||
\x20 int seen = argc;\n\
|
||||
\x20 printf(\"%s\\n\", argv[argc - 1]);\n\
|
||||
\x20 return seen;\n\
|
||||
}\n",
|
||||
)
|
||||
.expect("write");
|
||||
let binary = dir.join("app");
|
||||
assert!(
|
||||
std::process::Command::new("cc")
|
||||
.args(["-g", "-O0", "-o"])
|
||||
.arg(&binary)
|
||||
.arg(dir.join("main.c"))
|
||||
.status()
|
||||
.expect("cc runs")
|
||||
.success(),
|
||||
"the fixture must compile"
|
||||
);
|
||||
let program = binary.to_string_lossy().into_owned();
|
||||
let source = dir.join("main.c").to_string_lossy().into_owned();
|
||||
let cwd = dir.to_string_lossy().into_owned();
|
||||
|
||||
let service = Arc::new(DapService::new());
|
||||
let tool = luxe_dap::DebugTool::new(service.clone());
|
||||
let cx = context(&dir);
|
||||
let call = |args: serde_json::Value| {
|
||||
let (tool, cx) = (&tool, &cx);
|
||||
async move {
|
||||
let result = tool.run(args, cx).await;
|
||||
let text = result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
luxe_core::ContentBlock::Text(text) => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
(text, result.is_error)
|
||||
}
|
||||
};
|
||||
|
||||
// launch{args, breakpoints} — three arguments, and a breakpoint set by the launch itself.
|
||||
let (launched, failed) = call(json!({
|
||||
"action": "launch", "program": program, "cwd": cwd, "adapter": "gdb",
|
||||
"args": ["alpha", "beta", "gamma"],
|
||||
"breakpoints": [{ "path": source, "lines": [4] }]
|
||||
}))
|
||||
.await;
|
||||
assert!(!failed, "launch with args: {launched}");
|
||||
eprintln!("LAUNCH+ARGS:\n{launched}");
|
||||
assert!(
|
||||
launched.contains("stopped"),
|
||||
"the launch-time breakpoint must stop the program: {launched}"
|
||||
);
|
||||
let session = launched
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.strip_prefix("session "))
|
||||
.and_then(|rest| rest.split_whitespace().next())
|
||||
.expect("launch names its session")
|
||||
.to_string();
|
||||
|
||||
// argc is 4: the program plus the three arguments. Anything else and `args` did not arrive.
|
||||
let (argc, failed) =
|
||||
call(json!({"action": "evaluate", "session": session, "expression": "argc"})).await;
|
||||
assert!(!failed, "evaluate argc: {argc}");
|
||||
eprintln!("ARGC: {argc}");
|
||||
assert!(argc.contains('4'), "three `args` plus the program name is argc 4, got: {argc}");
|
||||
|
||||
let (argv, _) =
|
||||
call(json!({"action": "evaluate", "session": session, "expression": "argv[2]"})).await;
|
||||
eprintln!("ARGV[2]: {argv}");
|
||||
assert!(argv.contains("beta"), "the arguments arrive in order: {argv}");
|
||||
|
||||
call(json!({"action": "terminate", "session": session})).await;
|
||||
service.terminate_all().await;
|
||||
}
|
||||
|
||||
/// Attaching to a process this host forbids ptracing is reported, not waited out silently.
|
||||
///
|
||||
/// `kernel.yama.ptrace_scope = 1` — the default on most desktop Linux — forbids attaching to a
|
||||
/// process you did not fork. gdb accepts the `attach` request anyway and then simply never reports
|
||||
/// a stop, so the only thing Luxe can do is say which situation this is. It used to answer
|
||||
/// `request 'event' timed out`, which names an internal wait and offers nothing; the check here is
|
||||
/// that the reply names the permission and the sysctl that governs it.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "drives a real gdb; run with --run-ignored"]
|
||||
async fn real_gdb_explains_an_attach_the_host_forbids() {
|
||||
if !on_path("gdb") || !gdb_speaks_dap() || !on_path("cc") {
|
||||
eprintln!("skipping: needs gdb 14+ (DAP) and a C compiler");
|
||||
return;
|
||||
}
|
||||
let scope = std::fs::read_to_string("/proc/sys/kernel/yama/ptrace_scope").unwrap_or_default();
|
||||
if scope.trim() == "0" {
|
||||
eprintln!("skipping: this host permits ptrace, so there is no refusal to report");
|
||||
return;
|
||||
}
|
||||
let dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let dir = dir_guard.path().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(
|
||||
dir.join("main.c"),
|
||||
"#include <unistd.h>\nint main(void) { for (int i = 0; i < 600; i++) sleep(1); return 0; }\n",
|
||||
)
|
||||
.expect("write");
|
||||
let binary = dir.join("app");
|
||||
assert!(
|
||||
std::process::Command::new("cc")
|
||||
.args(["-g", "-O0", "-o"])
|
||||
.arg(&binary)
|
||||
.arg(dir.join("main.c"))
|
||||
.status()
|
||||
.expect("cc runs")
|
||||
.success(),
|
||||
"the fixture must compile"
|
||||
);
|
||||
|
||||
let mut running = std::process::Command::new(&binary)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.expect("the fixture runs");
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
|
||||
let service = DapService::new();
|
||||
let outcome = service
|
||||
.attach(
|
||||
Some(i64::from(running.id())),
|
||||
None,
|
||||
dir.to_string_lossy().into_owned(),
|
||||
vec![],
|
||||
Some("gdb".to_string()),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Killed before asserting: a panic must not leave the fixture running.
|
||||
let _ = running.kill();
|
||||
let _ = running.wait();
|
||||
service.terminate_all().await;
|
||||
|
||||
let refusal = outcome.expect_err("this host forbids the attach").to_string();
|
||||
eprintln!("ATTACH REFUSAL: {refusal}");
|
||||
assert!(
|
||||
refusal.contains("ptrace_scope"),
|
||||
"the reply must name the permission that governs this: {refusal}"
|
||||
);
|
||||
assert!(
|
||||
!refusal.contains("'event'"),
|
||||
"naming an internal wait tells the caller nothing: {refusal}"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user