//! Debug Adapter Protocol client. //! //! [`DebugManager`] owns every debug session plus the per-file breakpoint //! store (independent of sessions; sent to each session during configuration //! and updated live). Sessions emit `IdeEvent::Debug`; the UI then pulls //! threads, frames, scopes and variables on demand. //! //! All lines and columns in this API are 0-based; the client tells adapters //! `linesStartAt1`/`columnsStartAt1` and converts at this edge. pub mod adapter; pub mod attach; mod cargo; pub mod connection; mod debugpy; mod disassembly; mod exception_classes; pub mod jdwp; mod js_cdp; mod js_debug; mod jvm_memory; pub mod kotlin; pub mod kotlin_lsp; #[cfg(target_os = "macos")] mod lldb_server; mod memory; pub mod native; mod session; mod stream_trace; mod swiftpm; pub mod unity; use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher}; use connection::{Connection, DapError}; pub use disassembly::{Instruction, MAX_INSTRUCTIONS}; pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport}; use futures::future::join_all; use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink}; use ide_language::LanguageRegistry; pub use js_cdp::JsResponseRule; pub use js_debug::JsResponseBody; pub use jvm_memory::*; pub use memory::{MAX_READ, MemoryBlock}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use session::Session; use specta::Type; use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; use std::sync::{Arc, Weak}; use std::time::Duration; pub use stream_trace::{TracePhase, TraceProgress, TraceRun, TraceUnavailable}; /// The adapter name of a notebook kernel's own debugger (see [`DebugManager::start_over`]). pub const NOTEBOOK_ADAPTER: &str = "jupyter-kernel"; /// How a notebook cell's breakpoints are keyed: `vscode-notebook-cell:#`. pub const NOTEBOOK_CELL_SCHEME: &str = "vscode-notebook-cell:"; #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct LaunchConfig { pub name: String, /// DAP adapter name from `languages/*.toml` (or a built-in: codelldb, debugpy, js-debug, delve, netcoredbg). pub adapter: String, /// `launch` or `attach`. pub request: String, pub program: Option, pub args: Vec, pub cwd: Option, pub env: BTreeMap, /// Adapter specific extra arguments as JSON text, merged into the launch request. /// A `"cargo": {"args": [...], "filter": {"name", "kind"}}` entry builds with cargo /// and launches the produced executable; `"debugServer": ` connects to an /// adapter already listening on that local port (e.g. java-debug inside jdtls) /// instead of starting one, `"debugServer": "host:port"` to one on another machine /// (`dlv --headless`, `debugpy --listen`). pub extra_json: Option, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct Breakpoint { pub line: u32, pub condition: Option, pub hit_condition: Option, /// Logpoint message; when set the breakpoint logs instead of suspending. pub log_message: Option, pub enabled: bool, } /// A method breakpoint (DAP function breakpoint). `name` uses the adapter's syntax: /// `pkg.Class#method` for java-debug, `pkg.Func` / `pkg.(*T).Method` for Delve, a plain /// function name for debugpy and LLDB. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct FunctionBreakpoint { pub name: String, pub condition: Option, pub hit_condition: Option, pub enabled: bool, } /// A field watchpoint (DAP data breakpoint) on a `dataId` from [`DebugManager::data_breakpoint_info`] /// (java-debug ids, `Class#field`, stay valid across sessions). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct DataBreakpoint { pub data_id: String, /// `read`, `write` or `readWrite` (adapter default when unset). pub access_type: Option, pub condition: Option, pub hit_condition: Option, pub enabled: bool, } /// Answer of `dataBreakpointInfo`: `data_id` is `None` when the value cannot be watched. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct DataBreakpointInfo { pub data_id: Option, pub description: String, pub access_types: Vec, } /// A call on the current line that Smart Step Into can enter (`stepInTargets`). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct StepInTarget { pub id: i64, pub label: String, /// 0-based, when the adapter reports where the call is. pub line: Option, pub column: Option, pub end_column: Option, } /// What a session's adapter supports, for enabling actions. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct DebugCapabilities { pub restart_frame: bool, pub step_in_targets: bool, pub function_breakpoints: bool, pub data_breakpoints: bool, /// `setVariable` or `setExpression`. pub set_value: bool, pub conditional_breakpoints: bool, pub hit_conditional_breakpoints: bool, pub log_points: bool, /// HotSwap ("Reload Changed Classes"): java-debug's `redefineClasses` request. pub hot_code_replace: bool, /// The session debugs a JVM, so it has a Memory view; [`DebugManager::jvm_memory_classes`] /// says why when it has no data (platform, remote JVM, ...). pub jvm_memory: bool, /// The session has a JVM inspector: instances, fields and referrers while suspended. Can /// change during the session ([`ide_core::event::DebugEvent::Capabilities`]). pub jvm_instances: bool, /// The session can be asked for a heap dump ([`DebugManager::jvm_heap_dump`]). pub jvm_heap: bool, /// The session debugs a page in a browser: js-debug's requests for pages apply /// ([`DebugManager::js_set_custom_breakpoints`]). pub js_page: bool, /// The adapter evaluates expressions while the program runs, without a stack frame. pub live_evaluate: bool, /// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]). /// Can change during the session, like `jvm_instances`. pub stream_trace: bool, /// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View. pub read_memory: bool, /// The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view. pub disassemble: bool, /// Steps can move by one instruction ([`DebugManager::step_instruction`]). pub instruction_stepping: bool, } /// Result of [`DebugManager::redefine_classes`]. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct HotSwapResult { /// Fully qualified names of the classes reloaded (empty: nothing had changed). pub changed_classes: Vec, pub error_message: Option, } /// Adapters that implement java-debug's hot code replace protocol. pub const HOT_CODE_REPLACE_ADAPTERS: &[&str] = &["java-debug"]; /// java-debug's `HotCodeReplaceEvent.changeType` (an enum name, or its numeric code). pub(crate) fn hot_code_replace_type(v: Option<&Value>) -> String { match v { Some(Value::String(s)) => s.clone(), Some(Value::Number(n)) => match n.as_i64() { Some(-1) => "ERROR", Some(-2) => "WARNING", Some(1) => "STARTING", Some(2) => "END", Some(3) => "BUILD_COMPLETE", _ => "UNKNOWN", } .to_owned(), _ => "UNKNOWN".to_owned(), } } pub(crate) fn hot_swap_result(body: &Value) -> HotSwapResult { HotSwapResult { changed_classes: body .get("changedClasses") .and_then(Value::as_array) .map(|a| a.iter().filter_map(|c| c.as_str().map(str::to_owned)).collect()) .unwrap_or_default(), error_message: body.get("errorMessage").and_then(Value::as_str).filter(|m| !m.is_empty()).map(str::to_owned), } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct BreakpointState { pub line: u32, pub verified: bool, pub message: Option, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] pub struct ThreadInfo { pub id: i64, pub name: String, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct StackFrame { pub id: i64, pub name: String, pub path: Option, pub line: u32, pub column: u32, /// `subtle` frames (library/generated) are collapsed in the UI. pub presentation_hint: Option, /// The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub instruction_pointer_reference: Option, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct Scope { pub name: String, pub variables_reference: i64, pub expensive: bool, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct Variable { pub name: String, pub value: String, pub type_name: Option, /// > 0 when expandable. pub variables_reference: i64, pub evaluate_name: Option, /// `value` is not computed yet (DAP `presentationHint.lazy`): the single variable that /// `variables` returns for `variables_reference` holds the value and its children. #[serde(default, skip_serializing_if = "std::ops::Not::not")] #[specta(optional)] pub lazy: bool, /// Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`). #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub memory_reference: Option, } /// A completion the adapter offers for an expression (DAP `completions`). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct DebugCompletion { pub label: String, /// What to insert, when it differs from `label`. pub text: Option, /// DAP item type: `method`, `field`, `variable`, `class`, `keyword`, … pub kind: Option, pub detail: Option, pub sort_text: Option, } #[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum StepKind { Over, Into, Out, } /// An exception breakpoint filter offered by an adapter (`exceptionBreakpointFilters`). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct ExceptionFilter { pub filter: String, pub label: String, pub description: Option, /// Enabled unless the user chose otherwise. pub default: bool, pub supports_condition: bool, } /// Exception filters of one session (see [`DebugManager::exception_filters`]). #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct SessionExceptionFilters { pub session: DebugSessionId, pub adapter: String, pub filters: Vec, /// Set when the session takes exception breakpoints on a chosen class. pub classes: Option, } /// What triggered a hot reload; `flutter debug_adapter` takes it as `reason`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum HotReloadReason { Manual, Save, } /// A live session, as listed by [`DebugManager::sessions`]. #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct SessionInfo { pub id: DebugSessionId, pub name: String, pub adapter: String, /// Set for child sessions started by the adapter (`startDebugging`). pub parent: Option, } /// One owner's breakpoints, kept without a session and sent when one of its sessions starts. #[derive(Default)] struct OwnerBreakpoints { lines: BTreeMap>, functions: Vec, data: Vec, } /// Who started a session. Every event of the session, and of the child sessions /// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes /// listings such as [`DebugManager::sessions`]. #[derive(Clone)] pub struct SessionOwner { pub key: String, pub sink: SharedSink, } impl SessionOwner { pub fn new(key: impl Into, sink: SharedSink) -> Self { Self { key: key.into(), sink } } } const INIT_TIMEOUT: Duration = Duration::from_secs(20); const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3); /// Redefining many classes in a large JVM can take a while. const HOT_SWAP_TIMEOUT: Duration = Duration::from_secs(120); pub struct DebugManager { languages: Arc, launcher: Arc, me: Weak, sessions: Mutex>>, /// Session start order, for "the first session" semantics. order: Mutex>, /// Breakpoints by owner (window): each window's sessions get only its own. breakpoints: Mutex>, states: Mutex>>, /// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default. exception_choices: Mutex>, exception_classes: Mutex>, /// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills. stopping: Mutex>>, jvm_finder: Mutex, } /// rdbg (Ruby's debug gem) starts the debuggee itself and ignores `launch`'s program, /// arguments and environment: they go on its command line after `--` and into its process. /// In a Bundler project it runs from the bundle, which must have `debug`: the debuggee then /// loads that version, and the gems rdbg needs (irb is not a default gem from Ruby 3.5). fn rdbg_command_line(spec: &mut AdapterSpec, config: &LaunchConfig, cwd: &Path) -> IdeResult<()> { if config.request != "launch" { return Ok(()); } if spec.command == "rdbg" && let Some(gemfile) = bundler_gemfile(cwd, &config.env) { if !bundles_debug(&gemfile) { return Err(IdeError::unavailable(format!( "the bundle of {} has no `debug` gem. Add `gem \"debug\"` to the Gemfile and run `bundle install`", gemfile.display() ))); } spec.args.splice(0..0, ["exec".to_owned(), "rdbg".to_owned()]); spec.command = "bundle".into(); } spec.env.extend(config.env.iter().map(|(k, v)| (k.clone(), v.clone()))); spec.args.push("--".into()); // With only a command, Ruby's exec treats it as shell text. Ruby entry points // without arguments go through -S so spaces and metacharacters stay literal. if config.program.is_some() && config.args.is_empty() { spec.args.extend(["ruby", "-S", "--"].map(str::to_owned)); } spec.args.extend(config.program.iter().cloned()); spec.args.extend(config.args.iter().cloned()); Ok(()) } /// The Gemfile Bundler uses in `dir`: `BUNDLE_GEMFILE`, else the closest `Gemfile` / `gems.rb` from `dir` up. fn bundler_gemfile(dir: &Path, env: &BTreeMap) -> Option { let gemfile = env .get("BUNDLE_GEMFILE") .cloned() .or_else(|| ide_core::process::host_var_os("BUNDLE_GEMFILE").map(|v| v.to_string_lossy().into_owned())); match gemfile.filter(|g| !g.is_empty()) { Some(gemfile) => Some(dir.join(gemfile)), None => dir.ancestors().flat_map(|d| [d.join("gems.rb"), d.join("Gemfile")]).find(|g| g.is_file()), } } /// Whether the lockfile of `gemfile` lists the `debug` gem. fn bundles_debug(gemfile: &Path) -> bool { let lockfile = if gemfile.file_name().is_some_and(|n| n == "gems.rb") { gemfile.with_file_name("gems.locked") } else { let mut name = gemfile.as_os_str().to_owned(); name.push(".lock"); PathBuf::from(name) }; // The bundle's gems are the lines indented by four spaces: ` debug (1.9.2)`. std::fs::read_to_string(lockfile).is_ok_and(|text| text.lines().any(|l| l.starts_with(" debug ("))) } /// Whether the debugged project depends on the Flutter SDK, so it must go /// through `flutter debug_adapter` instead of the plain Dart one. /// /// `dart debug_adapter` cannot start a program that imports `dart:ui`, and only /// the Flutter adapter answers `hotReload` / `hotRestart`. `dir` is the launch /// `cwd`; the program's own directory is tried first because a module inside a /// larger repository has its `pubspec.yaml` above the program, not above `cwd`. fn is_flutter_project(dir: &Path, program: Option<&Path>) -> bool { let mut start: Vec<&Path> = program.and_then(Path::parent).into_iter().collect(); start.push(dir); start .iter() .filter_map(|d| d.ancestors().take(6).find(|a| a.join("pubspec.yaml").is_file())) .filter_map(|root| std::fs::read_to_string(root.join("pubspec.yaml")).ok()) .any(|s| s.contains("sdk: flutter")) } /// `flutter debug_adapter` passes `toolArgs` on to `flutter run` / `flutter attach`. fn add_flutter_device(arguments: &mut Value, device: Value) { let args = arguments.as_object_mut().map(|o| o.entry("toolArgs").or_insert_with(|| json!([]))); if let Some(args) = args.and_then(Value::as_array_mut) { args.extend([json!("-d"), device]); } } /// The source a `navigate` tool event points at (1-based there). A `package:` location comes /// with the file the adapter resolved it to. fn flutter_navigation(body: &Value) -> Option { if body.get("kind")?.as_str()? != "navigate" { return None; } let data = body.get("data")?; let uri = data.get("resolvedFileUri").or_else(|| data.get("fileUri"))?.as_str()?; let position = |key| data.get(key)?.as_u64().map(|n| n.saturating_sub(1) as u32); Some(ide_core::event::DebugEvent::FlutterNavigate { path: kotlin_lsp::source_path(uri)?.into(), line: position("line")?, column: position("column").unwrap_or(0), }) } fn no_session(s: DebugSessionId) -> IdeError { IdeError::not_found(format!("no debug session {}", s.0)) } /// debugpy hands a subprocess (`subProcess: true`, forked or spawned) over as an `attach` whose /// `connect` is its own client listener: the child session is another connection to the running /// adapter, as VS Code makes it, not a new adapter that would take that port for a debug server. fn subprocess_connection(configuration: &Value, spec: &AdapterSpec) -> Option<(AdapterSpec, u16)> { configuration.get("subProcessId")?; let connect = configuration.get("connect")?; let port = u16::try_from(connect.get("port")?.as_u64()?).ok()?; let mut spec = spec.clone(); if let Some(host) = connect.get("host").and_then(Value::as_str) { let loopback = host == "localhost" || host.parse::().is_ok_and(|ip| ip.is_loopback()); spec.server_host = (!loopback).then(|| host.to_owned()); } Some((spec, port)) } /// The name of a child session: the adapter's, or the parent's when it gives none. js-debug /// names a browser page's session after the page the browser starts on, before the URL /// loads (`about:blank`, or nothing in a new profile), which says nothing about what is debugged. fn child_name(configuration: &Value, parent: &str) -> String { match configuration.get("name").and_then(Value::as_str) { Some(name) if !name.trim().is_empty() && name != "about:blank" => name.to_owned(), _ => parent.to_owned(), } } /// LLDB-based adapters, which debug native programs (and Swift on Apple platforms). fn is_native(adapter: &str) -> bool { matches!(adapter, "lldb-dap" | "codelldb") } /// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the /// adapter. pub const RUN_LINK: &str = "__openideaRun"; const XCODE_ATTACH: &str = "__openideaXcodeAttach"; fn take_run_link(arguments: &mut Value) -> Option { let run = arguments.as_object_mut()?.remove(RUN_LINK)?; serde_json::from_value(run).ok() } /// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top. pub fn launch_arguments(config: &LaunchConfig) -> IdeResult { // VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch // or attach from `request` there, not from the DAP command. let mut args = json!({ "name": config.name, "request": config.request }); if let Some(t) = adapter::default_type(&config.adapter) { args["type"] = t.into(); } if let Some(p) = &config.program { args["program"] = p.as_str().into(); } if !config.args.is_empty() { args["args"] = json!(config.args); } if let Some(cwd) = &config.cwd { args["cwd"] = json!(cwd); } if !config.env.is_empty() { args["env"] = json!(config.env); } if let Some(extra) = config.extra_json.as_deref().filter(|e| !e.trim().is_empty()) { let extra: Value = serde_json::from_str(extra).map_err(|e| IdeError::invalid(format!("invalid launch JSON: {e}")))?; let Value::Object(extra) = extra else { return Err(IdeError::invalid("launch JSON must be an object")); }; if let Some(obj) = args.as_object_mut() { obj.extend(extra); } } Ok(args) } /// Placeholder in launch arguments for a free local port, the same one everywhere in a /// launch: Deno's `--inspect-wait=127.0.0.1:${freePort}` and js-debug's /// `"attachSimplePort": "${freePort}"` (a `port` / `…Port` attribute that is only the /// placeholder becomes a number; everything else stays a string, e.g. `env` values). pub const FREE_PORT_PLACEHOLDER: &str = "${freePort}"; /// Replaces [`FREE_PORT_PLACEHOLDER`] in every string of `value` with `port()` (called once, if used). pub(crate) fn substitute_free_port(value: &mut Value, port: &mut impl FnMut() -> IdeResult) -> IdeResult<()> { fn walk(v: &mut Value, key: &str, port: &mut dyn FnMut() -> IdeResult) -> IdeResult<()> { match v { Value::String(s) if s.contains(FREE_PORT_PLACEHOLDER) => { let p = port()?; *v = if s == FREE_PORT_PLACEHOLDER && (key == "port" || key.ends_with("Port")) { p.into() } else { s.replace(FREE_PORT_PLACEHOLDER, &p.to_string()).into() }; } Value::Array(a) => a.iter_mut().try_for_each(|x| walk(x, key, port))?, Value::Object(o) => o.iter_mut().try_for_each(|(k, x)| walk(x, k, port))?, _ => {} } Ok(()) } let mut chosen = None; walk(value, "", &mut || match chosen { Some(p) => Ok(p), None => { let p = port()?; chosen = Some(p); Ok(p) } }) } /// Where a running adapter listens: `debugServer` of the launch arguments. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct DebugServer { /// `None` for the loopback interface (an adapter inside a local process such as jdtls). pub host: Option, pub port: u16, } /// Removes `debugServer` (VS Code's "connect to a running adapter" attribute) from the /// launch arguments: a port (`4711`, `"4711"`) on this machine, or `"host:port"` / /// `"[v6]:port"` of a remote one (`dlv --headless`, `debugpy --listen`). pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult> { let Some(v) = arguments.as_object_mut().and_then(|o| o.remove("debugServer")) else { return Ok(None) }; let invalid = || IdeError::invalid(format!("invalid debugServer address: {v}")); let port_of = |p: u64| u16::try_from(p).ok().filter(|p| *p != 0); if let Some(p) = v.as_u64() { return port_of(p).map(|port| Some(DebugServer { host: None, port })).ok_or_else(invalid); } let s = v.as_str().map(str::trim).ok_or_else(invalid)?; let (host, port) = match s.rsplit_once(':') { Some((host, port)) => { let host = host.trim().trim_start_matches('[').trim_end_matches(']'); (Some(host).filter(|h| !h.is_empty()).map(str::to_owned), port) } None => (None, s), }; let port = port.trim().parse::().ok().and_then(port_of).ok_or_else(invalid)?; Ok(Some(DebugServer { host, port })) } /// A source served only through the `source` request whose `path` is no file, such as /// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without /// debug info. Opening it would show an error tab; without a path the stop selects the /// first frame with source instead. Non-file paths (`jdt://`, ``) stay. /// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive. fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool { let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0); reference > 0 && Path::new(path).has_root() && !Path::new(path).exists() } /// DAP stack frame → [`StackFrame`] (1-based → 0-based). pub(crate) fn frame_from(f: &Value) -> StackFrame { let source = f.get("source"); let source_hint = source.and_then(|s| s.get("presentationHint")).and_then(Value::as_str); let hint = f .get("presentationHint") .and_then(Value::as_str) .map(str::to_owned) .or_else(|| (source_hint == Some("deemphasize")).then(|| "subtle".to_owned())); StackFrame { id: f.get("id").and_then(Value::as_i64).unwrap_or_default(), name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(), path: source .and_then(|s| s.get("path")) .and_then(Value::as_str) .filter(|p| !is_pseudo_path(source, p)) .map(Into::into), line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), presentation_hint: hint, instruction_pointer_reference: f .get("instructionPointerReference") .and_then(Value::as_str) .filter(|r| !r.is_empty()) .map(str::to_owned), } } pub(crate) fn exception_filters_from(caps: &Value) -> Vec { caps.get("exceptionBreakpointFilters") .and_then(Value::as_array) .map(|a| { a.iter() .filter_map(|f| { let filter = f.get("filter").and_then(Value::as_str)?.to_owned(); Some(ExceptionFilter { label: f .get("label") .and_then(Value::as_str) .map(str::to_owned) .unwrap_or_else(|| filter.clone()), description: f.get("description").and_then(Value::as_str).map(str::to_owned), default: f.get("default").and_then(Value::as_bool).unwrap_or(false), supports_condition: f.get("supportsCondition").and_then(Value::as_bool).unwrap_or(false), filter, }) }) .collect() }) .unwrap_or_default() } /// Filter ids to enable: explicit choices win (`adapter:filter`, then the bare filter id, /// since adapters reuse ids such as `uncaught`), otherwise the adapter's default. pub(crate) fn enabled_filters( filters: &[ExceptionFilter], choices: &BTreeMap, adapter: &str, ) -> Vec { filters .iter() .filter(|f| { choices .get(&format!("{adapter}:{}", f.filter)) .or_else(|| choices.get(&f.filter)) .copied() .unwrap_or(f.default) }) .map(|f| f.filter.clone()) .collect() } pub(crate) fn step_in_target_from(t: &Value) -> StepInTarget { let num = |k: &str| t.get(k).and_then(Value::as_u64).map(|n| (n as u32).saturating_sub(1)); StepInTarget { id: t.get("id").and_then(Value::as_i64).unwrap_or_default(), label: t.get("label").and_then(Value::as_str).unwrap_or_default().to_owned(), line: num("line"), column: num("column"), end_column: num("endColumn"), } } pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities { let has = |k: &str| caps.get(k).and_then(Value::as_bool).unwrap_or(false); DebugCapabilities { restart_frame: has("supportsRestartFrame"), step_in_targets: has("supportsStepInTargetsRequest"), function_breakpoints: has("supportsFunctionBreakpoints"), data_breakpoints: has("supportsDataBreakpoints"), set_value: has("supportsSetVariable") || has("supportsSetExpression"), conditional_breakpoints: has("supportsConditionalBreakpoints"), hit_conditional_breakpoints: has("supportsHitConditionalBreakpoints"), log_points: has("supportsLogPoints"), hot_code_replace: false, jvm_memory: false, jvm_instances: false, jvm_heap: false, js_page: false, live_evaluate: false, stream_trace: false, read_memory: has("supportsReadMemoryRequest"), disassemble: has("supportsDisassembleRequest"), instruction_stepping: has("supportsSteppingGranularity"), } } pub(crate) fn session_capabilities(session: &Session) -> DebugCapabilities { let mut caps = capabilities_from(&session.caps.lock()); caps.hot_code_replace = HOT_CODE_REPLACE_ADAPTERS.contains(&session.adapter.as_str()); caps.jvm_memory = JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str()); caps.jvm_instances = session.jvm_inspector.lock().is_some(); caps.jvm_heap = JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str()); caps.js_page = js_debug::is_page(session); caps.live_evaluate = session.adapter == js_debug::ADAPTER; caps.stream_trace = stream_trace::available(session); caps } /// States of a file's line breakpoints that no session has been sent. fn unsent(breakpoints: &[Breakpoint]) -> Vec { breakpoints .iter() .map(|b| BreakpointState { line: b.line, verified: false, message: (!b.enabled).then(|| "Disabled".to_owned()), }) .collect() } /// States for breakpoints no session has verified yet. fn unverified(enabled: impl Iterator) -> Vec { enabled .map(|e| BreakpointState { line: 0, verified: false, message: (!e).then(|| "Disabled".to_owned()) }) .collect() } /// A step request's outcome; a failed one leaves no step pending, so the next stop keeps its reason. fn step_settled(session: &Session, sent: Result) -> Result { if sent.is_err() && let Some(quirks) = session.kotlin_lsp_quirks() { quirks.resume_sent(); } sent } /// Delve compiles the debuggee to `__debug_bin` in the session's cwd (in DAP mode a /// temp-file name, `__debug_bin`; on Windows with `.exe` before the digits) and /// removes it on a graceful exit — a shutdown it doesn't always reach, so the files pile up. Sweep /// the leftovers once the session is down. Runs after `session_closed`, so Delve /// has already exited or been killed and holds no file locks; a leftover of a /// still-building run is removed on that run's own shutdown. fn remove_delve_binaries(cwd: &Path) { let Ok(entries) = std::fs::read_dir(cwd) else { return }; for entry in entries.flatten() { let name = entry.file_name(); let Some(name) = name.to_str() else { continue }; // `__debug_bin`, then `.exe` on Windows, then DAP mode's temp-file digits. // Suffixes like `.go` are user files. let suffix = name.strip_prefix("__debug_bin").map(|s| s.strip_prefix(".exe").unwrap_or(s)); let leftover = suffix.is_some_and(|s| s.chars().all(|c| c.is_ascii_digit())); if !leftover || entry.file_type().is_ok_and(|t| !t.is_file()) { continue; } // Windows: a just-killed dlv / debuggee can still hold this session's // binary while the previous one's lock is already gone, so one try // leaves exactly the current leftover behind. Retry on a short back-off // to outlast the handle release; a truly busy file is retried into the // next run's sweep anyway. for attempt in 0..5 { match std::fs::remove_file(entry.path()) { Ok(()) => break, Err(e) if attempt == 4 => { tracing::debug!("could not remove Delve leftover {}: {e}", entry.path().display()); } Err(_) => std::thread::sleep(std::time::Duration::from_millis(50 * (attempt as u64 + 1))), } } } } pub(crate) fn variable_from(v: &Value) -> Variable { let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned); Variable { name: s("name").unwrap_or_default(), value: s("value").unwrap_or_default(), type_name: s("type").filter(|t| !t.is_empty()), variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0), evaluate_name: s("evaluateName"), lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false), memory_reference: memory_reference(v), } } /// A variable's or evaluation result's `memoryReference`. fn memory_reference(v: &Value) -> Option { v.get("memoryReference").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_owned) } async fn session_variables(session: &Session, reference: i64) -> IdeResult> { let body = session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?; Ok(body .get("variables") .and_then(Value::as_array) .map(|v| v.iter().map(variable_from).collect()) .unwrap_or_default()) } async fn resolve_in(session: &Session, variable: Variable) -> IdeResult { if !variable.lazy || variable.variables_reference <= 0 { return Ok(variable); } let mut inner = session_variables(session, variable.variables_reference).await?; Ok(match (inner.pop(), inner.is_empty()) { (Some(value), true) => Variable { type_name: value.type_name.or(variable.type_name), evaluate_name: variable.evaluate_name.or(value.evaluate_name), name: variable.name, value: value.value, variables_reference: value.variables_reference, lazy: value.lazy, memory_reference: value.memory_reference.or(variable.memory_reference), }, _ => variable, }) } /// A value that cannot be computed stays lazy, so the row can still be opened by hand. async fn resolve_lazy(session: &Session, variable: Variable) -> Variable { if !variable.lazy { return variable; } resolve_in(session, variable.clone()).await.unwrap_or(variable) } impl DebugManager { pub fn new(languages: Arc) -> Arc { Self::with_launcher(languages, Arc::new(ProcessLauncher)) } /// Like [`new`](Self::new) with a custom way to start adapters (tests use in-memory adapters). pub fn with_launcher(languages: Arc, launcher: Arc) -> Arc { Arc::new_cyclic(|me| Self { languages, launcher, me: me.clone(), sessions: Mutex::default(), order: Mutex::default(), breakpoints: Mutex::default(), states: Mutex::default(), exception_choices: Mutex::default(), exception_classes: Mutex::default(), stopping: Mutex::default(), jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)), }) } #[cfg(test)] pub(crate) fn set_jvm_finder(&self, finder: jvm_memory::JvmFinder) { *self.jvm_finder.lock() = finder; } fn session(&self, s: DebugSessionId) -> IdeResult> { self.sessions.lock().get(&s).cloned().ok_or_else(|| no_session(s)) } fn live_sessions(&self) -> Vec> { let sessions = self.sessions.lock(); self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect() } pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec { self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default() } fn function_breakpoints(&self, owner: &str) -> Vec { self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default() } fn data_breakpoints(&self, owner: &str) -> Vec { self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default() } /// `owner`'s sessions that take breakpoint requests. fn configured_sessions(&self, owner: &str) -> Vec> { self.live_sessions() .into_iter() .filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed()) .collect() } /// Live sessions of `owner` (all owners when `None`). pub fn sessions(&self, owner: Option<&str>) -> Vec { self.live_sessions() .iter() .filter(|s| owner.is_none_or(|o| s.owner.key == o)) .map(|s| SessionInfo { id: s.id, name: s.name.clone(), adapter: s.adapter.clone(), parent: s.parent }) .collect() } /// Whether `s` is live and currently suspended (a breakpoint, step or manual pause). /// `None` when the session has ended. pub fn session_suspended(&self, s: DebugSessionId) -> Option { self.sessions.lock().get(&s).map(|session| session.suspended.get()) } /// The thread of `s`'s most recent stop, when the adapter named one. pub fn stopped_thread(&self, s: DebugSessionId) -> Option { self.sessions.lock().get(&s).and_then(|session| session.suspended.stopped_thread()) } /// All stored breakpoints of `owner`, for tools that list or edit them. Line breakpoints /// are keyed by file; function and data breakpoints have no file. pub fn breakpoints( &self, owner: &str, ) -> (BTreeMap>, Vec, Vec) { let store = self.breakpoints.lock(); match store.get(owner) { Some(owner) => (owner.lines.clone(), owner.functions.clone(), owner.data.clone()), None => Default::default(), } } /// Starts a session: spawns the adapter, `initialize`, `launch`/`attach`, /// waits for `initialized`, sends breakpoints, then `configurationDone`. /// Events of the session (including cargo build output) go to `owner` only. pub async fn start(&self, config: LaunchConfig, owner: SessionOwner) -> IdeResult { self.start_with(config, owner, |_| None).await } /// [`start`](Self::start) with the adapter executable chosen by `custom_command` /// (the configured command → a user-chosen executable, from settings). pub async fn start_with( &self, config: LaunchConfig, owner: SessionOwner, custom_command: impl FnOnce(&str) -> Option, ) -> IdeResult { self.start_with_exception_classes(config, owner, custom_command, None).await } /// [`start_with`](Self::start_with), the session arming [`Self::set_exception_class_breakpoints`] /// through `exception_classes`. pub async fn start_with_exception_classes( &self, config: LaunchConfig, owner: SessionOwner, custom_command: impl FnOnce(&str) -> Option, exception_classes: Option>, ) -> IdeResult { self.start_with_cancel(config, owner, custom_command, exception_classes, ide_core::CancellationToken::new()) .await } /// [`start_with_exception_classes`](Self::start_with_exception_classes), cancelling a pending /// pre-launch build, adapter launch or configuration when `cancel` is triggered. pub async fn start_with_cancel( &self, config: LaunchConfig, owner: SessionOwner, custom_command: impl FnOnce(&str) -> Option, exception_classes: Option>, cancel: ide_core::CancellationToken, ) -> IdeResult { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } let mut arguments = launch_arguments(&config)?; if debugpy::listens(&config.adapter, &config.request, &arguments) { debugpy::require_free_port(&arguments).await?; } // An IDE-side marker (never sent to the adapter): the session is a Flutter // one regardless of what the working directory holds. let force_flutter = arguments.as_object_mut().and_then(|o| o.remove("__flutter")).and_then(|v| v.as_bool()).unwrap_or(false); // Also IDE-side: the device to run on, should this turn out to be a Flutter session. let flutter_device = arguments.as_object_mut().and_then(|o| o.remove("__flutterDevice")); let cwd = config .cwd .clone() .map(Into::into) .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| "/".into())); let dbg = adapter::find_config(&self.languages, &config.adapter) .ok_or_else(|| IdeError::unavailable(format!("unknown debug adapter `{}`", config.adapter)))?; if config.adapter == "js-debug" { adapter::set_browser_profile(&mut arguments, &cwd); } let mut spec = adapter::resolve(&dbg, cwd.clone()); if config.adapter == kotlin::ADAPTER && let Some(home) = arguments .as_object_mut() .and_then(|o| o.remove("__adapterJavaHome")) .and_then(|v| v.as_str().map(str::to_owned)) { spec.env.push(("JAVA_HOME".into(), home)); } // Delve looks up Go before applying the debuggee's launch environment. if config.adapter == "delve" { spec.env.extend(config.env.iter().map(|(key, value)| (key.clone(), value.clone()))); } if config.adapter == "rdbg" { rdbg_command_line(&mut spec, &config, &cwd)?; } // Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter` // (the Dart adapter cannot start a program importing `dart:ui`, and hot reload // is Flutter-only). Plain Dart projects keep the configured `dart`. Before // `custom_command`, which picks the Flutter SDK setting's `flutter`. if config.adapter == "dart" { let program = arguments.get("program").and_then(Value::as_str).map(Path::new); if force_flutter || is_flutter_project(&cwd, program) { if spec.command == "dart" { spec.command = "flutter".into(); } if let Some(device) = flutter_device { add_flutter_device(&mut arguments, device); } } } if let Some(command) = custom_command(&spec.command) { spec.command = command; } // The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice. if let Some(command) = arguments .as_object_mut() .and_then(|o| o.remove(native::ADAPTER_COMMAND)) .and_then(|v| v.as_str().map(str::to_owned)) { spec.command = command; spec.pinned = None; } // debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy), // or with the launcher's when the debuggee runs through a manager (`uv run python`). if config.adapter == "debugpy" { let python = match (arguments.get("debugLauncherPython"), arguments.get("python")) { (Some(Value::String(p)), _) | (_, Some(Value::String(p))) => Some(p.clone()), (_, Some(Value::Array(a))) => a.first().and_then(Value::as_str).map(str::to_owned), _ => None, }; if let Some(python) = python { spec.command = python; } } let id = DebugSessionId::next(); let debug_server = take_debug_server(&mut arguments)?; if let Some(server) = &debug_server { spec.server_host = server.host.clone(); } if config.adapter == "gdb" && config.request == "launch" && debug_server.is_none() { // GDB's DAP env replaces the entire inferior environment. Ordinary run overrides // instead belong on the adapter process, which the inferior inherits. Explicit // launch JSON keeps GDB's replacement semantics. let explicit_env = config.extra_json.as_deref().is_some_and(|extra| { serde_json::from_str::(extra).is_ok_and(|extra| extra.get("env").is_some()) }); if !explicit_env { spec.env.extend(config.env.iter().map(|(k, v)| (k.clone(), v.clone()))); arguments.as_object_mut().unwrap().remove("env"); } } if let Some(cargo) = arguments.as_object_mut().and_then(|o| o.remove("cargo")) { let cargo_args: Vec = cargo .get("args") .and_then(Value::as_array) .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect()) .unwrap_or_else(|| vec!["build".into()]); let filter = cargo::CargoFilter::from_json(cargo.get("filter")); let sink = owner.sink.clone(); let program = cargo::build(&cwd, &cargo_args, &filter, &cancel, move |line| { sink.emit(ide_core::IdeEvent::Debug { session: id, event: ide_core::event::DebugEvent::Output { category: "console".into(), output: line }, }); }) .await?; arguments["program"] = json!(program); } if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) { arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?); } // Attach to a Node process started without `--inspect`: open its inspector first. if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() { let pid = arguments.get("processId").and_then(|p| match p { Value::String(s) => s.split(':').next().and_then(|p| p.trim().parse::().ok()), other => other.as_u64().and_then(|p| u32::try_from(p).ok()), }); if let Some(pid) = pid { let port = tokio::select! { biased; _ = cancel.cancelled() => return Err(IdeError::cancelled()), port = attach::enable_node_inspector(pid) => port?, }; if let Some(obj) = arguments.as_object_mut() { obj.remove("processId"); obj.insert("port".into(), port.into()); obj.entry("address").or_insert_with(|| "127.0.0.1".into()); } } } substitute_free_port(&mut arguments, &mut || adapter::free_port().map_err(IdeError::from))?; // VS Code passes the workspace folder: js-debug's default `outFiles` (where it looks // for compiled code of a TypeScript breakpoint before it loads) is relative to it. if config.adapter == "js-debug" && arguments.get("__workspaceFolder").is_none() { arguments["__workspaceFolder"] = json!(cwd); } // Godot compares `project` with its own (resolved) project path: `/tmp/game` is // rejected by an editor that opened `/private/tmp/game`. if config.adapter == "godot" && let Some(project) = arguments.get("project").and_then(Value::as_str) && let Ok(real) = std::fs::canonicalize(project) { arguments["project"] = json!(real); } if config.adapter == "codelldb" { if arguments.get("sourceLanguages").is_none() { arguments["sourceLanguages"] = json!(["rust"]); } // The Debug Console and Evaluate Expression take expressions, as with every other // debugger; LLDB commands still run with a leading backtick. match arguments.get_mut("_adapterSettings") { None => arguments["_adapterSettings"] = json!({"consoleMode": "evaluate"}), Some(Value::Object(settings)) => { settings.entry("consoleMode").or_insert_with(|| json!("evaluate")); } Some(_) => {} } } let port = debug_server.map(|s| s.port); self.start_session( id, owner, config.name, config.adapter, None, config.request, arguments, spec, port, exception_classes, cancel, None, ) .await } /// Starts an `attach` session named `name` over `io`: a debugger reached without an /// adapter process, such as a notebook kernel's over its control channel /// ([`NOTEBOOK_ADAPTER`]). `arguments` is the `attach` request's. `notebook_cells`, the /// prefix of a notebook's cell URIs, gives the session that notebook's cell breakpoints. pub async fn start_over( &self, io: AdapterIo, name: String, adapter: String, arguments: Value, owner: SessionOwner, notebook_cells: Option, ) -> IdeResult { let spec = AdapterSpec { adapter: adapter.clone(), command: String::new(), args: Vec::new(), transport: adapter::Transport::Stdio, install_hint: None, cwd: PathBuf::new(), env: Vec::new(), server_host: None, connect: None, pinned: None, resolve_lazy_variables: false, shared: false, }; let cancel = ide_core::CancellationToken::new(); self.start_session( DebugSessionId::next(), owner, name, adapter, None, "attach".into(), arguments, spec, None, None, cancel, Some((io, notebook_cells)), ) .await } /// `startDebugging` reverse request: a child session on the same adapter. pub(crate) async fn start_child( &self, parent: &Arc, request: String, configuration: Value, ) -> IdeResult<()> { let name = child_name(&configuration, &parent.name); let mut configuration = configuration; if let Some(obj) = configuration.as_object_mut() { obj.entry("request").or_insert_with(|| request.clone().into()); } let (spec, port) = match parent.port { Some(port) => (parent.spec.clone(), Some(port)), None => match subprocess_connection(&configuration, &parent.spec) { Some((spec, port)) => (spec, Some(port)), None => (parent.spec.clone(), None), }, }; self.start_session( DebugSessionId::next(), parent.owner.clone(), name, parent.adapter.clone(), Some(parent.id), request, configuration, spec, port, None, ide_core::CancellationToken::new(), None, ) .await .map(|_| ()) } #[allow(clippy::too_many_arguments)] async fn start_session( &self, id: DebugSessionId, owner: SessionOwner, name: String, adapter_name: String, parent: Option, request: String, mut arguments: Value, mut spec: AdapterSpec, reuse_port: Option, exception_classes: Option>, cancel: ide_core::CancellationToken, connected: Option<(AdapterIo, Option)>, ) -> IdeResult { if request != "launch" && request != "attach" { return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`"))); } // Xcode Debug attaches to the app its run launched: a shared lldb-dap server keeps the // system libraries it parsed, so the next attach skips that (#6665 E7). let xcode_attach = arguments.as_object_mut().and_then(|args| args.remove(XCODE_ATTACH)); spec.shared = xcode_attach == Some(Value::Bool(true)) && adapter_name == "lldb-dap" && request == "attach" && arguments.get(RUN_LINK).is_some(); if cancel.is_cancelled() { return Err(IdeError::cancelled()); } let (io, notebook_cells) = match connected { Some((io, cells)) => (io, cells), None => ( tokio::select! { biased; _ = cancel.cancelled() => return Err(IdeError::cancelled()), io = self.launcher.launch(spec.clone(), reuse_port) => io?, }, None, ), }; let launch_after_configuration = io.launch_after_configuration && request == "launch"; let stderr = io.stderr.clone(); let (conn, incoming) = { let stderr = stderr.clone(); Connection::start_with_output(io.reader, io.writer, Box::new(move |line| adapter::push_line(&stderr, line))) }; let rdbg_pid = (adapter_name == "rdbg" && request == "launch") .then(|| io.child.as_ref().and_then(tokio::process::Child::id)) .flatten(); let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child); session.exception_classes = exception_classes; session.notebook_cells = notebook_cells; session.run = take_run_link(&mut arguments); let session = Arc::new(session); if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) { let _ = session.launch_type.set(launch_type.to_owned()); } // rdbg execs the debuggee in its own process and sends no DAP process event. if let Some(pid) = rdbg_pid { session.debuggee_pid.store(i64::from(pid), Ordering::Release); } let cancelled = { let mut sessions = self.sessions.lock(); if cancel.is_cancelled() { true } else { sessions.insert(id, session.clone()); self.order.lock().push(id); false } }; if cancelled { session.conn.close(); session.kill_processes(); return Err(IdeError::cancelled()); } if let Some(mut output) = io.program_output { session.output_drained.send_replace(false); let session = session.clone(); tokio::spawn(async move { while let Some((category, output)) = output.recv().await { session.emit(ide_core::event::DebugEvent::Output { category: category.into(), output }); } session.output_drained.send_replace(true); }); } // Announced before the event loop runs, so it precedes every adapter event. session.emit(ide_core::event::DebugEvent::Started { name: session.name.clone(), adapter: session.adapter.clone(), parent, }); tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming)); if debugpy::listens(&session.adapter, &session.request, &arguments) { session.debugpy_version_unchecked.store(true, Ordering::Release); } enum ConfigOutcome { Done(IdeResult<()>), Stopped, Cancelled, } let configured = tokio::select! { biased; _ = session.startup_cancel.cancelled() => ConfigOutcome::Stopped, _ = cancel.cancelled() => ConfigOutcome::Cancelled, result = self.configure(&session, arguments, launch_after_configuration) => ConfigOutcome::Done(result), }; match configured { ConfigOutcome::Done(Ok(())) => Ok(id), ConfigOutcome::Stopped => Err(IdeError::cancelled()), ConfigOutcome::Cancelled => { let _ = self.stop(id).await; Err(IdeError::cancelled()) } ConfigOutcome::Done(Err(e)) => { let e = if session.conn.is_closed() { let mut msg = format!("debug adapter `{}` exited during startup", session.adapter); let tail = stderr.lock().join("\n"); if !tail.is_empty() { msg.push_str(":\n"); msg.push_str(&tail); } if let Some(hint) = &session.spec.install_hint { msg.push('\n'); msg.push_str(hint); } IdeError::unavailable(msg) } else { e }; session.terminated.store(true, Ordering::Release); self.shutdown(&session, true).await; Err(e) } } } async fn configure(&self, s: &Arc, mut arguments: Value, launch_in_config: bool) -> IdeResult<()> { if s.adapter == kotlin::ADAPTER { let project = arguments .get("projectRoot") .and_then(Value::as_str) .map(PathBuf::from) .unwrap_or_else(|| s.spec.cwd.clone()); let mirror = tokio::task::spawn_blocking(move || kotlin::SourceMirror::create(&project)) .await .map_err(|e| IdeError::internal(e.to_string()))??; arguments["projectRoot"] = json!(mirror.root()); *s.kotlin_mirror.lock() = Some(mirror); } let is_kotlin_lsp = s.adapter == kotlin_lsp::ADAPTER; let caps = s .conn .request_timeout( "initialize", json!({ "clientID": "openidea", "clientName": "OpenIDEA", "adapterID": if is_kotlin_lsp { kotlin_lsp::DAP_ADAPTER_ID } else { s.adapter.as_str() }, "locale": "en", "linesStartAt1": true, "columnsStartAt1": true, "pathFormat": "path", "supportsVariableType": true, "supportsVariablePaging": false, "supportsRunInTerminalRequest": true, "supportsStartDebuggingRequest": true, "supportsProgressReporting": true, // kotlin-lsp sends `invalidated` either way. "supportsInvalidatedEvent": is_kotlin_lsp, "supportsMemoryReferences": true, "supportsArgsCanBeInterpretedByShell": false, }), INIT_TIMEOUT, ) .await?; *s.caps.lock() = if caps.is_object() { caps } else { json!({}) }; if s.adapter == adapter::JAVA_ANALYZER && s.request == "launch" { session::shorten_java_analyzer_classpath(s, &mut arguments)?; } // The Kotlin adapters ignore the resolved classpath and project runtime on launch. let request = if kotlin::is_kotlin(&s.adapter) && s.request == "launch" { session::start_kotlin_debuggee(s, &mut arguments).await?; "attach" } else { &s.request }; // Both blocks below run before the Kotlin link replaces the JVM's address with its own. if request == "attach" && let Some(target) = jvm_memory::attach_target(&arguments) { let _ = s.attach_target.set(target); } if cfg!(unix) && s.request == "attach" && JVM_MEMORY_ADAPTERS.contains(&s.adapter.as_str()) && let Some(port) = jvm_memory::local_jdwp_port(&arguments) { if jdwp::is_listen_relay(port) { s.listen_relay.store(true, Ordering::Release); } else { let finder = self.jvm_finder.lock().clone(); jvm_memory::find_attached_jvm(s, port, finder).await; } } if kotlin::is_kotlin(&s.adapter) { let host = arguments .get("hostName") .and_then(Value::as_str) .ok_or_else(|| IdeError::invalid("Missing Kotlin JDWP host"))? .to_owned(); let port = arguments .get("port") .and_then(Value::as_u64) .and_then(|p| u16::try_from(p).ok()) .filter(|p| *p != 0) .ok_or_else(|| IdeError::invalid("Invalid Kotlin JDWP port"))?; let (link, port) = ide_jdwp::JdwpLink::start(host, port, kotlin::link_options(&s.adapter)).await?; *s.jvm_inspector.lock() = Some(Arc::new(ide_jdwp::LinkInspector::new(link.clone()))); jvm_memory::watch_link(s, &link); *s.jdwp_link.lock() = Some(link); arguments["hostName"] = json!("127.0.0.1"); arguments["port"] = json!(port); } s.jvm_located.send_replace(true); // Launch/attach may wait for a slow runtime or a remote target. Let the adapter report // failure; Stop cancels configuration and a closed connection fails the pending reply. // Many adapters answer only after `configurationDone`, so don't wait for the reply yet. // GDB 15 is the exception: its `launch` starts the program itself (14 runs at // `configurationDone`, 16+ defers the launch there), so its launch waits below. let mut launch = if launch_in_config { None } else { let reply = s.conn.send_request(request, arguments.clone()).await?; Some(Box::pin(async move { reply.await.unwrap_or(Err(DapError::Closed)) })) }; let mut initialized = s.initialized.subscribe(); let mut launch_result = None; let got_initialized = match launch.as_mut() { Some(launch) => tokio::select! { r = initialized.wait_for(|v| *v) => { r.map_err(|_| DapError::Closed)?; true } r = launch => { r?; launch_result = Some(()); false } }, None => { initialized.wait_for(|v| *v).await.map_err(|_| DapError::Closed)?; true } }; if !got_initialized { // Launched before `initialized`; give the adapter a moment to send it. let _ = tokio::time::timeout(INIT_TIMEOUT, initialized.wait_for(|v| *v)).await; } if s.adapter == "unity" { if launch_result.is_none() && let Some(launch) = launch.as_mut() { launch.await?; launch_result = Some(()); } unity::wait_for_threads(s).await?; } // A fresh adapter has no breakpoints, so a file with none enabled needs no request; the // others go out together, as VS Code sends them, instead of one round trip per file. let (files, idle): (Vec<_>, Vec<_>) = self .breakpoints .lock() .get(&s.owner.key) .map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::>()) .unwrap_or_default() .into_iter() .filter(|(path, _)| s.takes(path)) .partition(|(_, b)| b.iter().any(|b| b.enabled)); let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await; // Breakpoint states follow the owner's first session. let first = self.live_sessions().into_iter().find(|f| f.owner.key == s.owner.key).map(|f| f.id) == Some(s.id); let idle = idle.into_iter().map(|(path, bps)| (path, Ok(unsent(&bps)))); for (path, result) in files.into_iter().map(|(path, _)| path).zip(sent).chain(idle) { match result { Ok(states) => { if first { self.states.lock().insert(path.clone(), states); s.emit(ide_core::event::DebugEvent::BreakpointsChanged { path: path.into() }); } } Err(e) if s.adapter == kotlin::ADAPTER => return Err(e.into()), Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()), } } let functions = self.function_breakpoints(&s.owner.key); if !functions.is_empty() && s.supports("supportsFunctionBreakpoints") && let Err(e) = s.send_function_breakpoints(&functions).await { tracing::debug!("setFunctionBreakpoints failed: {e}"); } let data = self.data_breakpoints(&s.owner.key); if !data.is_empty() && s.supports("supportsDataBreakpoints") && let Err(e) = s.send_data_breakpoints(&data).await { tracing::debug!("setDataBreakpoints failed: {e}"); } let has_filters = s.caps.lock().get("exceptionBreakpointFilters").and_then(Value::as_array).is_some(); { let _turn = s.exception_turn.lock().await; if has_filters { let _ = self.send_exception_breakpoints(s).await; } self.arm_exception_classes(s, false).await; } if s.supports("supportsConfigurationDoneRequest") { if s.adapter == kotlin::ADAPTER { drop(s.conn.send_request("configurationDone", json!({})).await?); } else { s.conn.request_timeout("configurationDone", Value::Null, REQUEST_TIMEOUT).await?; } } s.configured.store(true, Ordering::Release); match launch.as_mut() { Some(launch) => { if launch_result.is_none() { launch.await?; } } None => { // GDB 15: the breakpoints are in, so its `run` cannot miss them. let reply = s.conn.send_request(request, arguments).await?; reply.await.unwrap_or(Err(DapError::Closed))?; } } s.launched.send_replace(true); // A page reports its requests from here on. This is the earliest js-debug takes the // request (before its answer to `launch` the page has no adapter and the request is // never answered), and the page is already loading: its document and first scripts // are not in the list. if js_debug::is_page(s) { let answer = s.conn.send_request("enableNetworking", js_debug::networking_arguments()).await?; let session = s.clone(); // Not waited for here: the page runs on. A refusal is told to the Network view, // which would otherwise wait for requests that never come. tokio::spawn(async move { if matches!(answer.await, Ok(Err(_))) { session.emit(ide_core::event::DebugEvent::JsNetworkUnavailable); } }); } if let Some(link) = s.jdwp_link.lock().as_ref() { link.release(); } if s.adapter == "unity" { unity::settle_startup(s).await; s.emit(ide_core::event::DebugEvent::Initialized); } Ok(()) } /// The connection dropped (adapter exited or `shutdown` finished). pub(crate) fn session_closed(&self, s: &Arc) { s.kill_processes(); let removed = self.sessions.lock().remove(&s.id).is_some(); self.order.lock().retain(|id| *id != s.id); if removed && !s.terminated.swap(true, Ordering::AcqRel) { s.emit(ide_core::event::DebugEvent::Terminated); } } /// Ends a session: `terminate` (when asked and supported) → `disconnect` → kill. pub(crate) async fn shutdown(&self, s: &Arc, terminate: bool) { if terminate { crate::session::remember_debuggee(s).await; } // java-debug runs the program itself and pipes its stdout over DAP. A `disconnect` // ends that DAP session, so every line the program writes while shutting down is lost. // Ask the program to exit ourselves and keep the adapter attached until it has drained // the console (`terminated`), as IDEA does with the process it owns. let pid = s.debuggee_pid.load(Ordering::Acquire); let own_terminate = terminate && s.request == "launch" && pid > 0; // rdbg's terminate exits the Ruby process without terminating its children. let graceful = terminate && s.request == "launch" && s.adapter != "rdbg" && s.supports("supportsTerminateRequest"); // A program suspended in the debugger cannot act on SIGTERM, and on macOS not even die of // SIGKILL while the debugger holds it: it is killed (with what it started) and the adapter // is told to end it. A killed program has no shutdown output to wait for. let killed = own_terminate && !graceful && s.suspended.get(); if killed { crate::session::signal_debuggee(s, true).await; } if !s.conn.is_closed() { if graceful { let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await; } if !graceful && (!own_terminate || killed) { // A native attach to a program a run started for the debugger (an Xcode app launched // with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be // left stopped with the SIGTERM the run's Stop sent while it was traced, and the // simulator then holds its launch (and the next one) forever. let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter)); let _ = s .conn .request_timeout( "disconnect", json!({ "restart": false, "terminateDebuggee": ends_debuggee }), SHUTDOWN_TIMEOUT, ) .await; } } if own_terminate && !graceful && !killed { // Signal before anything else: waiting on a request the adapter may not answer // would delay the shutdown the console is supposed to show. crate::session::signal_debuggee(s, false).await; } if graceful { // java-debug sends `terminated` only after it has drained the program's console // (it waits up to 5 s for the output pump). Close on the process id alone and the // last shutdown lines are dropped, so wait for that event here. let deadline = std::time::Instant::now() + crate::session::DEBUGGEE_EXIT_WAIT; while !s.terminated.load(Ordering::Acquire) && std::time::Instant::now() < deadline { tokio::time::sleep(std::time::Duration::from_millis(50)).await; } } // An adapter answers `disconnect` before the program it launched has exited, and that // program keeps its port until it is gone. Reporting the session as terminated then // lets Run start again into an occupied port, so wait for the program first — with the // connection still open, so a second Stop can find the session and kill it. crate::session::wait_for_debuggee(s, terminate).await; if terminate && s.request == "launch" && !killed { // The adapter reports `terminated` only after it has drained the program's console // (java-debug waits up to 5 s for the pump): closing before that drops the last // shutdown lines from the console. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(6); while !s.terminated.load(Ordering::Acquire) && !s.conn.is_closed() && std::time::Instant::now() < deadline { tokio::time::sleep(std::time::Duration::from_millis(50)).await; } } if graceful && !s.conn.is_closed() { let _ = s .conn .request_timeout( "disconnect", json!({ "restart": false, "terminateDebuggee": false }), SHUTDOWN_TIMEOUT, ) .await; } s.conn.close(); self.session_closed(s); if s.adapter == "delve" && s.spec.server_host.is_none() { let cwd = s.spec.cwd.clone(); tokio::task::spawn_blocking(move || remove_delve_binaries(&cwd)); } } /// `owner`'s breakpoints are kept per file even without a session and sent when one of /// its sessions starts. Returns states from its first live session, or unverified states. pub async fn set_breakpoints( &self, owner: &str, path: PathBuf, breakpoints: Vec, ) -> IdeResult> { { let mut store = self.breakpoints.lock(); let lines = &mut store.entry(owner.to_owned()).or_default().lines; if breakpoints.is_empty() { lines.remove(&path); } else { lines.insert(path.clone(), breakpoints.clone()); } } self.send_file_breakpoints(owner, path, breakpoints).await } /// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending /// the files that changed to its sessions. A file the window no longer lists can't stay /// behind and be sent to every later session, whatever made the two lists diverge (#6116). pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap>) -> IdeResult<()> { let changed: Vec<(PathBuf, Vec)> = { let mut store = self.breakpoints.lock(); let lines = &mut store.entry(owner.to_owned()).or_default().lines; let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect(); let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new())); let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone())); let changed = removed.chain(changed).collect(); *lines = files; changed }; for (path, breakpoints) in changed { self.send_file_breakpoints(owner, path, breakpoints).await?; } Ok(()) } /// Drops `owner`'s breakpoints (its window closed). pub fn forget_breakpoints(&self, owner: &str) { self.breakpoints.lock().remove(owner); } async fn send_file_breakpoints( &self, owner: &str, path: PathBuf, breakpoints: Vec, ) -> IdeResult> { let mut result: Option> = None; for s in self.configured_sessions(owner).into_iter().filter(|s| s.takes(&path)) { match s.send_breakpoints(&path, &breakpoints, None).await { Ok(states) => { result.get_or_insert(states); } Err(e) if s.adapter == kotlin::ADAPTER => return Err(e.into()), Err(e) => tracing::debug!("setBreakpoints on session {} failed: {e}", s.id.0), } } let states = result.unwrap_or_else(|| unsent(&breakpoints)); self.states.lock().insert(path, states.clone()); Ok(states) } /// Refresh fallback copies after an editor save. pub async fn refresh_source_mirrors(&self, owner: &str) -> IdeResult<()> { let sessions: Vec<_> = self.sessions.lock().values().filter(|s| s.owner.key == owner).cloned().collect(); tokio::task::spawn_blocking(move || { for s in sessions { if let Some(mirror) = s.kotlin_mirror.lock().as_mut() && let Err(e) = mirror.refresh() { tracing::warn!("Could not refresh Kotlin debug sources: {e}"); } } Ok(()) }) .await .map_err(|e| IdeError::internal(e.to_string()))? } /// Last known verification states of a file's breakpoints (after `BreakpointsChanged`). pub fn breakpoint_states(&self, path: &Path) -> Vec { self.states.lock().get(path).cloned().unwrap_or_default() } pub(crate) fn update_breakpoint_state(&self, path: &Path, index: usize, bp: &Value) -> bool { let mut states = self.states.lock(); let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false }; let next = session::state_from(bp, slot.line); let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE)); let next = BreakpointState { message: next.message.or(kept), ..next }; let changed = *slot != next; *slot = next; changed } async fn send_exception_breakpoints(&self, s: &Arc) -> IdeResult<()> { let filters = exception_filters_from(&s.caps.lock()); let enabled = enabled_filters(&filters, &self.exception_choices.lock(), &s.adapter); s.conn.request_timeout("setExceptionBreakpoints", json!({ "filters": enabled }), REQUEST_TIMEOUT).await?; Ok(()) } /// Exception filters offered by the adapter of each live session of `owner` (all when `None`). pub fn exception_filters(&self, owner: Option<&str>) -> Vec { self.live_sessions() .iter() .filter(|s| owner.is_none_or(|o| s.owner.key == o)) .map(|s| SessionExceptionFilters { session: s.id, adapter: s.adapter.clone(), filters: exception_filters_from(&s.caps.lock()), classes: exception_classes::support(s), }) .collect() } /// Stores exception filter choices (filter id → enabled; kept without a session, applied on /// start) and sends them to every configured session that offers exception filters. pub async fn set_exception_breakpoints(&self, choices: BTreeMap) -> IdeResult<()> { *self.exception_choices.lock() = choices; for s in self.live_sessions() { if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() { continue; } if exception_filters_from(&s.caps.lock()).is_empty() { continue; } let _turn = s.exception_turn.lock().await; if let Err(e) = self.send_exception_breakpoints(&s).await { tracing::debug!("setExceptionBreakpoints on session {} failed: {e}", s.id.0); } self.arm_exception_classes(&s, false).await; } Ok(()) } /// Changes a variable's value: `setVariable` in its container, or `setExpression` /// on its evaluate name when the adapter only supports that. Returns the new value. pub async fn set_variable( &self, s: DebugSessionId, container: i64, name: String, evaluate_name: Option, frame_id: Option, value: String, ) -> IdeResult { let session = self.session(s)?; let body = if container > 0 && session.supports("supportsSetVariable") { session .conn .request_timeout( "setVariable", json!({ "variablesReference": container, "name": name, "value": value }), REQUEST_TIMEOUT, ) .await? } else if let (Some(expr), true) = (evaluate_name.as_ref(), session.supports("supportsSetExpression")) { let mut args = json!({ "expression": expr, "value": value }); if let Some(f) = frame_id { args["frameId"] = f.into(); } session.conn.request_timeout("setExpression", args, REQUEST_TIMEOUT).await? } else { return Err(IdeError::unavailable(format!("debug adapter `{}` cannot change values", session.adapter))); }; Ok(Variable { name: name.clone(), value: body.get("value").and_then(Value::as_str).unwrap_or(&value).to_owned(), type_name: body.get("type").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_owned), variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0), evaluate_name: evaluate_name.or(Some(name)), lazy: false, memory_reference: memory_reference(&body), }) } pub async fn threads(&self, s: DebugSessionId) -> IdeResult> { let session = self.session(s)?; // Before sending: a stop that overtakes the reply must not take the reply's ids as its own. let stop = session.suspended.ticket(); let body = session.conn.request_timeout("threads", Value::Null, REQUEST_TIMEOUT).await?; let threads: Vec = body .get("threads") .and_then(Value::as_array) .map(|t| { t.iter() .map(|t| ThreadInfo { id: t.get("id").and_then(Value::as_i64).unwrap_or_default(), name: t.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(), }) .collect() }) .unwrap_or_default(); if let Some(quirks) = session.kotlin_lsp_quirks() { quirks.saw_threads(stop, threads.iter().map(|t| t.id)); } Ok(threads) } pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult> { const MAX_FRAMES: u64 = 400; let session = self.session(s)?; session.check_thread(thread_id)?; let request = |start: u64, levels: u64| { session.conn.request_timeout( "stackTrace", json!({ "threadId": thread_id, "startFrame": start, "levels": levels }), REQUEST_TIMEOUT, ) }; let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) { Some(Value::Array(frames)) => frames, _ => Vec::new(), }; let raw = match request(0, MAX_FRAMES).await { Ok(body) => frames_of(body), // java-debug fails the whole request when one frame's source lookup throws (on Windows, // a CGLIB proxy's `` source against `sourcePaths`): the frames come one at a // time instead, without the ones it cannot describe. // ponytail: one request per frame; page around the failing ones if deep stacks get slow. Err(first @ DapError::Failed { .. }) => { let Ok(top) = request(0, 1).await else { return Err(first.into()) }; let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES); let mut raw = frames_of(top); for start in 1..total { if let Ok(body) = request(start, 1).await { raw.extend(frames_of(body)); } } raw } Err(e) => return Err(e.into()), }; let kotlin_lsp = session.kotlin_lsp_quirks().is_some(); let frame = |f: &Value| { let mut frame = frame_from(f); if let Some(client) = frame.path.as_deref().and_then(|p| session.client_path(&p.to_string_lossy())) { frame.path = Some(client.into()); } if kotlin_lsp { frame.name = kotlin_lsp::frame_name(&frame.name).to_owned(); } frame }; Ok(raw.iter().map(frame).collect()) } pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult> { let body = self.session(s)?.conn.request_timeout("scopes", json!({ "frameId": frame_id }), REQUEST_TIMEOUT).await?; Ok(body .get("scopes") .and_then(Value::as_array) .map(|sc| { sc.iter() .map(|sc| Scope { name: sc.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(), variables_reference: sc.get("variablesReference").and_then(Value::as_i64).unwrap_or(0), expensive: sc.get("expensive").and_then(Value::as_bool).unwrap_or(false), }) .collect() }) .unwrap_or_default()) } pub async fn variables(&self, s: DebugSessionId, reference: i64) -> IdeResult> { let session = self.session(s)?; let vars = session_variables(&session, reference).await?; if !session.spec.resolve_lazy_variables { return Ok(vars); } Ok(join_all(vars.into_iter().map(|v| resolve_lazy(&session, v))).await) } /// Computes a lazy variable's value (DAP `presentationHint.lazy`); any other variable, or one /// whose value the adapter does not give as a single variable, comes back unchanged. pub async fn resolve_variable(&self, s: DebugSessionId, variable: Variable) -> IdeResult { resolve_in(&*self.session(s)?, variable).await } /// Evaluates in the `repl` context. pub async fn evaluate(&self, s: DebugSessionId, frame_id: Option, expression: String) -> IdeResult { self.evaluate_in(s, frame_id, expression, None).await } /// Evaluates with an explicit DAP context: `repl` (default), `watch`, `hover`, `clipboard`. pub async fn evaluate_in( &self, s: DebugSessionId, frame_id: Option, expression: String, context: Option, ) -> IdeResult { let session = self.session(s)?; let mut context = context.unwrap_or_else(|| "repl".into()); if context == "hover" && !session.supports("supportsEvaluateForHovers") { context = "watch".into(); } let mut args = json!({ "expression": expression, "context": context }); if let Some(f) = frame_id { args["frameId"] = f.into(); } let body = session.conn.request_timeout("evaluate", args, REQUEST_TIMEOUT).await?; let result = Variable { name: expression.clone(), value: body.get("result").and_then(Value::as_str).unwrap_or_default().to_owned(), type_name: body.get("type").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_owned), variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0), evaluate_name: Some(expression), lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false), memory_reference: memory_reference(&body), }; if !session.spec.resolve_lazy_variables { return Ok(result); } Ok(resolve_lazy(&session, result).await) } /// Completions for `text` at `line` / `column` (0-based, UTF-16) in the frame's scope; none /// when the adapter doesn't offer them. pub async fn completions( &self, s: DebugSessionId, frame_id: Option, text: String, line: u32, column: u32, ) -> IdeResult> { let session = self.session(s)?; if !session.supports("supportsCompletionsRequest") { return Ok(Vec::new()); } let mut args = json!({ "text": text, "line": line + 1, "column": column + 1 }); if let Some(f) = frame_id { args["frameId"] = f.into(); } let body = session.conn.request_timeout("completions", args, REQUEST_TIMEOUT).await?; let text = |v: &Value, key: &str| v.get(key).and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_owned); Ok(body .get("targets") .and_then(Value::as_array) .map(|targets| { targets .iter() .filter_map(|t| { Some(DebugCompletion { label: text(t, "label")?, text: text(t, "text"), kind: text(t, "type"), detail: text(t, "detail"), sort_text: text(t, "sortText"), }) }) .collect() }) .unwrap_or_default()) } pub async fn resume(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<()> { let session = self.session(s)?; session.check_thread(thread_id)?; if let Some(quirks) = session.kotlin_lsp_quirks() { quirks.resume_sent(); } let ticket = session.suspended.ticket(); let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?; // DAP: a response without the flag continued every thread. let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true); session.finish_resume(ticket, thread_id, all); Ok(()) } pub async fn pause(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<()> { self.session(s)?.conn.request_timeout("pause", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?; Ok(()) } /// Types `text` into the terminal the session's program runs in (see [`ide_core::event::DebugEvent::ProgramInput`]). pub fn send_input(&self, s: DebugSessionId, text: &str) -> IdeResult<()> { let session = self.session(s)?; let mut program = session.program.lock(); let program = program .as_mut() .ok_or_else(|| IdeError::invalid("The program doesn't read input from the debug console"))?; program.write(text).map_err(|e| IdeError::internal(format!("cannot write to the program: {e}"))) } /// Flutter's DAP adapter: injects the changed sources into the running app. /// Not part of the DAP standard; adapters that do not know the request reject it. pub async fn hot_reload(&self, s: DebugSessionId, reason: HotReloadReason) -> IdeResult<()> { self.session(s)?.conn.request_timeout("hotReload", json!({ "reason": reason }), REQUEST_TIMEOUT).await?; Ok(()) } /// Flutter's DAP adapter: restarts the app without preserving state. pub async fn hot_restart(&self, s: DebugSessionId) -> IdeResult<()> { self.session(s)?.conn.request_timeout("hotRestart", json!({ "reason": "manual" }), REQUEST_TIMEOUT).await?; Ok(()) } pub async fn step(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> { self.step_with(s, thread_id, kind, json!({ "threadId": thread_id })).await } /// Step Over / Into Instruction: a step by one machine instruction (DAP `granularity`). pub async fn step_instruction(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> { let session = self.session(s)?; if !session.supports("supportsSteppingGranularity") { return Err(IdeError::unavailable(format!( "debug adapter `{}` cannot step by instruction", session.adapter ))); } self.step_with(s, thread_id, kind, json!({ "threadId": thread_id, "granularity": "instruction" })).await } async fn step_with(&self, s: DebugSessionId, thread_id: i64, kind: StepKind, args: Value) -> IdeResult<()> { let command = match kind { StepKind::Over => "next", StepKind::Into => "stepIn", StepKind::Out => "stepOut", }; let session = self.session(s)?; session.check_thread(thread_id)?; if let Some(quirks) = session.kotlin_lsp_quirks() { quirks.step_sent(); } let ticket = session.suspended.ticket(); let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await; step_settled(&session, sent)?; // A step runs its thread; other threads stopped by their own events stay stopped. session.finish_resume(ticket, thread_id, false); Ok(()) } /// Run to cursor: a temporary breakpoint at `line` (0-based) plus `continue`; /// the file's real breakpoints are restored on the next stop. `force` (Force Run /// to Cursor) also suspends every other breakpoint until then. pub async fn run_to( &self, s: DebugSessionId, thread_id: i64, path: PathBuf, line: u32, force: bool, ) -> IdeResult<()> { let session = self.session(s)?; // Before touching breakpoints: a refused `continue` would leave them replaced. session.check_thread(thread_id)?; if force { self.suspend_breakpoints(&session, Some(&path)).await?; } let stored = self.stored_breakpoints(&session.owner.key, &path); let sent: Vec = if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored }; session.send_breakpoints(&path, &sent, Some(line)).await?; session.pending_restore.lock().files.insert(path); self.resume(s, thread_id).await } /// Sends empty breakpoint lists (line, function, data) to `session` until its next /// stop, when the stored ones are restored. `except` is left to the caller. async fn suspend_breakpoints(&self, session: &Arc, except: Option<&Path>) -> IdeResult<()> { // While paused the adapter holds the stored lists: only files with something enabled change. let files: Vec = self .breakpoints .lock() .get(&session.owner.key) .map(|b| { b.lines .iter() .filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled)) .map(|(path, _)| path.clone()) .collect() }) .unwrap_or_default(); let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await; let mut failed = None; for (path, result) in files.into_iter().zip(sent) { match result { Ok(_) => { session.pending_restore.lock().files.insert(path); } Err(e) => failed = failed.or(Some(e)), } } if let Some(e) = failed { return Err(e.into()); } if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints") { session.send_function_breakpoints(&[]).await?; session.pending_restore.lock().functions = true; } if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") { session.send_data_breakpoints(&[]).await?; session.pending_restore.lock().data = true; } Ok(()) } /// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced. pub(crate) async fn restore_breakpoints(&self, session: &Arc) { let pending = std::mem::take(&mut *session.pending_restore.lock()); let files: Vec<(PathBuf, Vec)> = pending .files .into_iter() .map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path))) .collect(); let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await; for ((path, _), result) in files.iter().zip(sent) { if let Err(e) = result { tracing::debug!("restoring breakpoints of {} failed: {e}", path.display()); } } if pending.functions { let functions = self.function_breakpoints(&session.owner.key); if let Err(e) = session.send_function_breakpoints(&functions).await { tracing::debug!("restoring function breakpoints failed: {e}"); } } if pending.data { let data = self.data_breakpoints(&session.owner.key); if let Err(e) = session.send_data_breakpoints(&data).await { tracing::debug!("restoring data breakpoints failed: {e}"); } } } /// Force Step Over: `next` with every breakpoint suspended until the step ends. pub async fn force_step_over(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<()> { let session = self.session(s)?; session.check_thread(thread_id)?; self.suspend_breakpoints(&session, None).await?; self.step(s, thread_id, StepKind::Over).await } /// Step into a specific call of the current line (Smart Step Into). pub async fn step_in_target(&self, s: DebugSessionId, thread_id: i64, target_id: i64) -> IdeResult<()> { let session = self.session(s)?; session.check_thread(thread_id)?; if let Some(quirks) = session.kotlin_lsp_quirks() { quirks.step_sent(); } let ticket = session.suspended.ticket(); let sent = session .conn .request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT) .await; step_settled(&session, sent)?; session.finish_resume(ticket, thread_id, false); Ok(()) } /// Calls on the current line of `frame_id` that can be stepped into. pub async fn step_in_targets(&self, s: DebugSessionId, frame_id: i64) -> IdeResult> { let session = self.session(s)?; if !session.supports("supportsStepInTargetsRequest") { return Err(IdeError::unavailable(format!( "debug adapter `{}` does not support Smart Step Into", session.adapter ))); } let body = session.conn.request_timeout("stepInTargets", json!({ "frameId": frame_id }), REQUEST_TIMEOUT).await?; Ok(body .get("targets") .and_then(Value::as_array) .map(|t| t.iter().map(step_in_target_from).collect()) .unwrap_or_default()) } /// Reset Frame (IDEA's Drop Frame): `restartFrame`, so execution re-enters the frame. pub async fn restart_frame(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<()> { let session = self.session(s)?; if !session.supports("supportsRestartFrame") { return Err(IdeError::unavailable(format!("debug adapter `{}` cannot reset frames", session.adapter))); } session.conn.request_timeout("restartFrame", json!({ "frameId": frame_id }), REQUEST_TIMEOUT).await?; Ok(()) } /// `count` bytes (at most [`MAX_READ`]) from `offset` bytes after `memory_reference`, which /// comes from a variable, an evaluation result or an earlier read's address. pub async fn read_memory( &self, s: DebugSessionId, memory_reference: String, offset: i64, count: u32, ) -> IdeResult { let session = self.session(s)?; if !session.supports("supportsReadMemoryRequest") { return Err(IdeError::unavailable(format!("debug adapter `{}` cannot read memory", session.adapter))); } let count = count.min(MAX_READ); let body = session .conn .request_timeout( "readMemory", json!({ "memoryReference": memory_reference, "offset": offset, "count": count }), REQUEST_TIMEOUT, ) .await?; memory::memory_block(&body, count) } /// `count` instructions (at most [`MAX_INSTRUCTIONS`]) from `before` instructions ahead of /// `memory_reference` (a frame's instruction pointer or an instruction's address). Adapters that /// cannot disassemble backwards start at the reference instead. pub async fn disassemble( &self, s: DebugSessionId, memory_reference: String, before: u32, count: u32, ) -> IdeResult> { let session = self.session(s)?; if !session.supports("supportsDisassembleRequest") { return Err(IdeError::unavailable(format!("debug adapter `{}` cannot disassemble", session.adapter))); } let count = count.clamp(1, MAX_INSTRUCTIONS); let before = before.min(count - 1); let request = |offset: i64, count: u32| { session.conn.request_timeout( "disassemble", json!({ "memoryReference": memory_reference, "offset": 0, "instructionOffset": offset, "instructionCount": count, "resolveSymbols": true, }), REQUEST_TIMEOUT, ) }; if before > 0 { // GDB (up to 17 at least) answers a negative instruction offset with the instructions after // the reference, or fails: only an answer with the reference in its place is used. if let Ok(body) = request(-i64::from(before), count).await { let instructions = disassembly::instructions(&body); if disassembly::at_index(&instructions, &memory_reference, before as usize) { return Ok(instructions.into_iter().flatten().collect()); } } } let body = request(0, count - before).await?; Ok(disassembly::instructions(&body).into_iter().flatten().collect()) } pub fn capabilities(&self, s: DebugSessionId) -> IdeResult { Ok(session_capabilities(&*self.session(s)?)) } /// Class table of the session's JVM (`GC.class_histogram -all`, or counted by the debugger /// while suspended where no histogram can be taken), with deltas against the session's /// previous snapshot from the same source. pub async fn jvm_memory_classes(&self, s: DebugSessionId) -> IdeResult { let session = self.session(s)?; jvm_memory::session_classes(session).await } /// Writes a heap dump of the session's JVM to `dir/dump.hprof`, one class-table or dump /// request per session at a time. Anything but `Ready` deletes `dir`, unless `s` is not a /// session. On `cancel` the result is `Cancelled` at once, while a dump the JVM is writing /// still holds the session's turn until the JVM answers. pub async fn jvm_heap_dump( &self, s: DebugSessionId, dir: PathBuf, cancel: ide_core::CancellationToken, ) -> IdeResult { let session = self.session(s)?; jvm_memory::session_heap_dump(session, dir, cancel).await } /// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK /// 21+ the JSON dump written into `json_dir`. A JVM the debugger holds suspended is asked /// only when it is 17 or later and its listener already runs: otherwise the request would hang /// until the program resumes. pub async fn jvm_thread_dump(&self, s: DebugSessionId, json_dir: Option) -> IdeResult { let session = self.session(s)?; jvm_memory::session_thread_dump(session, json_dir).await } /// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build /// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes /// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON /// dump either. `None` when no session debugs `pid`. pub async fn debugged_jvm_thread_dump( &self, run: RunId, pid: u32, json_dir: Option, ) -> Option> { let session = self.jvm_session_of(run, pid)?; Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await) } /// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan /// found no listener) still holds `pid`. fn jvm_session_of(&self, run: RunId, pid: u32) -> Option> { let sessions = self.live_sessions(); let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid)); linked() .find(|s| jvm_memory::debugs_jvm(s, pid)) .or_else(|| linked().next()) .or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid))) .cloned() } /// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class /// counts; the UI is told to reload the session's capabilities. pub fn set_jvm_inspector( &self, s: DebugSessionId, inspector: Arc, ) -> IdeResult<()> { let session = self.session(s)?; if session.ended.is_cancelled() { return Err(no_session(s)); } jvm_memory::set_inspector(&session, inspector); Ok(()) } /// Up to `limit` (clamped to `1..=MAX_INSTANCES`) instances of `class_name` while suspended. pub async fn jvm_memory_instances( &self, s: DebugSessionId, class_name: String, limit: u32, ) -> IdeResult { jvm_memory::instances(&*self.session(s)?, &class_name, limit).await } pub async fn jvm_memory_fields(&self, s: DebugSessionId, object: JvmObjectRef) -> IdeResult { jvm_memory::fields(&*self.session(s)?, object).await } /// Objects that point at `object`; `limit` 0 means `DEFAULT_REFERRERS`, at most `MAX_REFERRERS`. pub async fn jvm_memory_referrers( &self, s: DebugSessionId, object: JvmObjectRef, limit: u32, ) -> IdeResult { jvm_memory::referrers(&*self.session(s)?, object, limit).await } /// Gives the session the backend for [`Self::stream_trace`] (used by java-debug sessions /// only); the UI is told to reload the session's capabilities. pub fn set_stream_tracer( &self, s: DebugSessionId, tracer: Arc, ) -> IdeResult<()> { let session = self.session(s)?; if session.ended.is_cancelled() { return Err(no_session(s)); } stream_trace::set_tracer(&session, tracer); Ok(()) } /// Traces the stream chain `plan` (the JSON of `ide_streams::RealRunPlan`) while the program /// runs it, from `thread_id` stopped where the chain starts. Leaves the thread stopped right /// after the chain's terminal operation. `cancel` stops keeping records; the program runs on. pub async fn stream_trace( &self, s: DebugSessionId, thread_id: i64, plan: Value, cancel: ide_core::CancellationToken, progress: impl Fn(TraceProgress) + Send + Sync, ) -> IdeResult { let session = self.session(s)?; Ok(stream_trace::run(self, &session, thread_id, &plan, &cancel, &progress).await) } /// Ends the running terminal operation by interrupting its thread, then by throwing into it. /// `None` when no trace runs. pub async fn stream_trace_abort(&self, s: DebugSessionId) -> IdeResult> { stream_trace::abort(&*self.session(s)?).await } /// HotSwap: reloads the classes compiled since the session started (or since the /// last reload) into the debuggee (java-debug `redefineClasses`). pub async fn redefine_classes(&self, s: DebugSessionId) -> IdeResult { let session = self.session(s)?; if !HOT_CODE_REPLACE_ADAPTERS.contains(&session.adapter.as_str()) { return Err(IdeError::unavailable(format!( "debug adapter `{}` cannot reload changed classes", session.adapter ))); } let body = session.conn.request_timeout("redefineClasses", json!({}), HOT_SWAP_TIMEOUT).await?; Ok(hot_swap_result(&body)) } /// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them /// to each of its configured sessions whose adapter supports them. States from the first one. pub async fn set_function_breakpoints( &self, owner: &str, list: Vec, ) -> IdeResult> { self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone(); let mut result = None; for s in self.configured_sessions(owner) { if !s.supports("supportsFunctionBreakpoints") { continue; } match s.send_function_breakpoints(&list).await { Ok(states) => { result.get_or_insert(states); } Err(e) => tracing::debug!("setFunctionBreakpoints on session {} failed: {e}", s.id.0), } } Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled)))) } /// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that /// supports them. pub async fn set_data_breakpoints( &self, owner: &str, list: Vec, ) -> IdeResult> { self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone(); let mut result = None; for s in self.configured_sessions(owner) { if !s.supports("supportsDataBreakpoints") { continue; } match s.send_data_breakpoints(&list).await { Ok(states) => { result.get_or_insert(states); } Err(e) => tracing::debug!("setDataBreakpoints on session {} failed: {e}", s.id.0), } } Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled)))) } /// Whether (and how) `name` in the variables container `container` can be watched. pub async fn data_breakpoint_info( &self, s: DebugSessionId, container: i64, name: String, frame_id: Option, ) -> IdeResult { let session = self.session(s)?; if !session.supports("supportsDataBreakpoints") { return Err(IdeError::unavailable(format!( "debug adapter `{}` does not support field watchpoints", session.adapter ))); } let mut args = json!({ "name": name }); if container > 0 { args["variablesReference"] = container.into(); } if let Some(f) = frame_id { args["frameId"] = f.into(); } let body = session.conn.request_timeout("dataBreakpointInfo", args, REQUEST_TIMEOUT).await?; Ok(DataBreakpointInfo { data_id: body.get("dataId").and_then(Value::as_str).map(str::to_owned), description: body.get("description").and_then(Value::as_str).unwrap_or_default().to_owned(), access_types: body .get("accessTypes") .and_then(Value::as_array) .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect()) .unwrap_or_default(), }) } /// Stops every session `key` started: the window that opened the project is closing. pub async fn stop_key(&self, key: &str) { let ids: Vec = self.sessions(Some(key)).into_iter().map(|s| s.id).collect(); for id in ids { if let Err(e) = self.stop(id).await { tracing::debug!("debug session {id:?} did not stop: {e}"); } } } /// Stops every debug session started from `root` or below — closing a project stops the /// programs it launched even when the session's owner key does not name the window doing /// the closing (window groups, auxiliary windows). pub async fn stop_under(&self, root: &Path) { let ids: Vec = self.live_sessions().into_iter().filter(|s| s.spec.cwd.starts_with(root)).map(|s| s.id).collect(); tracing::info!(root = %root.display(), sessions = ids.len(), "closing project: stopping debug sessions"); for id in ids { if let Err(e) = self.stop(id).await { tracing::debug!("debug session {id:?} did not stop: {e}"); } } } /// Stops a session and its child sessions. A second Stop while the first one waits kills /// the program instead of waiting for it — even after the adapter dropped the session. pub async fn stop(&self, s: DebugSessionId) -> IdeResult<()> { { let in_flight = self.stopping.lock(); if let Some(session) = in_flight.get(&s) { session.stop_force.store(true, Ordering::Release); return Ok(()); } } let session = self.session(s)?; self.stopping.lock().insert(s, session.clone()); let result = self.stop_tree(session).await; self.stopping.lock().remove(&s); result } async fn stop_tree(&self, session: Arc) -> IdeResult<()> { session.startup_cancel.cancel(); let children: Vec> = self.live_sessions().into_iter().filter(|c| c.parent == Some(session.id)).collect(); for child in children { child.startup_cancel.cancel(); self.shutdown(&child, true).await; } self.shutdown(&session, true).await; Ok(()) } } #[cfg(test)] mod tests;