use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::{Mutex, oneshot, watch};
use super::{
DebuggerAdapterKind, DebuggerBreakpoint, DebuggerConsoleEntry, DebuggerEvaluation,
DebuggerEvent, DebuggerFrame, DebuggerManager, DebuggerPhase, DebuggerProperty,
DebuggerRemoteValue, DebuggerScope, DebuggerSessionRecord, DebuggerSessionView,
DebuggerSnapshot, DebuggerVariable, now_ms,
};
use crate::execution::ExecutionManager;
use crate::model::ProcessController;
use crate::store::Store;
const DAP_REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
const DAP_MAX_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
fn rust_lldb_lookup_script() -> Option<&'static str> {
static SCRIPT: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
SCRIPT
.get_or_init(|| {
if let Ok(explicit) = std::env::var("APOC_RUST_LLDB_LOOKUP") {
let path = std::path::PathBuf::from(&explicit);
return path.is_file().then_some(explicit);
}
let sysroot = match std::env::var("RUSTC_SYSROOT") {
Ok(value) => value,
Err(_) => {
let output = std::process::Command::new("rustc")
.arg("--print")
.arg("sysroot")
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()?.trim().to_string()
}
};
let path = std::path::Path::new(&sysroot)
.join("lib")
.join("rustlib")
.join("etc")
.join("lldb_lookup.py");
path.is_file().then(|| path.to_string_lossy().into_owned())
})
.as_deref()
}
pub(crate) fn rust_init_commands() -> Vec<Value> {
let Some(script) = rust_lldb_lookup_script() else {
return Vec::new();
};
vec![
Value::String(format!("command script import \"{script}\"")),
Value::String(
"settings set target.process.thread.step-avoid-regexp ^(<?(std|core|alloc)::)"
.to_string(),
),
]
}
pub(crate) fn merge_init_commands(arguments: &mut Value, extra: Vec<Value>) {
if extra.is_empty() {
return;
}
let Some(object) = arguments.as_object_mut() else {
return;
};
let mut commands = object
.get("initCommands")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
for command in extra {
if !commands.contains(&command) {
commands.push(command);
}
}
object.insert("initCommands".to_string(), Value::Array(commands));
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapThread {
pub id: i64,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapModule {
pub id: String,
pub name: String,
pub path: String,
pub base_address: String,
pub size: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapRegister {
pub group: String,
pub name: String,
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapMemory {
pub address: String,
pub data: String,
pub unreadable_bytes: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapInstruction {
pub address: String,
pub instruction: String,
pub symbol: String,
pub location: String,
pub line: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapSignal {
pub name: String,
pub stop: bool,
pub pass: bool,
pub notify: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapWatchpoint {
pub id: String,
pub expression: String,
pub access: String,
pub enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DapSessionState {
pub view: DebuggerSessionView,
pub adapter_execution_id: String,
pub thread_id: Option<i64>,
pub threads: Vec<DapThread>,
pub modules: Vec<DapModule>,
pub capabilities: Value,
}
struct PendingRequest {
command: String,
response: oneshot::Sender<Result<Value, String>>,
}
pub(crate) struct DapSession {
id: String,
execution_id: String,
executions: ExecutionManager,
store: Arc<Store>,
controller: ProcessController,
next_sequence: AtomicU64,
pending: Mutex<HashMap<u64, PendingRequest>>,
snapshot: watch::Sender<DebuggerSnapshot>,
thread_id: Mutex<Option<i64>>,
threads: Mutex<Vec<DapThread>>,
modules: Mutex<Vec<DapModule>>,
capabilities: Mutex<Value>,
}
impl DapSession {
fn new(
id: String,
execution_id: String,
executions: ExecutionManager,
store: Arc<Store>,
controller: ProcessController,
snapshot: DebuggerSnapshot,
) -> Arc<Self> {
let (snapshot, _) = watch::channel(snapshot);
Arc::new(Self {
id,
execution_id,
executions,
store,
controller,
next_sequence: AtomicU64::new(1),
pending: Mutex::new(HashMap::new()),
snapshot,
thread_id: Mutex::new(None),
threads: Mutex::new(Vec::new()),
modules: Mutex::new(Vec::new()),
capabilities: Mutex::new(Value::Object(Default::default())),
})
}
pub(crate) fn observed(&self) -> DebuggerSnapshot {
self.snapshot.borrow().clone()
}
fn start_reader(self: &Arc<Self>) {
let session = self.clone();
tokio::spawn(async move {
session.read_loop().await;
});
}
async fn initialize(&self) -> Result<Value, String> {
let capabilities = self
.request(
"initialize",
json!({
"adapterID":"lldb",
"clientID":"apoc",
"clientName":"apoc",
"locale":"en-US",
"pathFormat":"path",
"linesStartAt1":true,
"columnsStartAt1":true,
"supportsRunInTerminalRequest":false,
"supportsVariableType":true,
"supportsVariablePaging":false,
"supportsProgressReporting":false
}),
Duration::from_secs(10),
)
.await?;
*self.capabilities.lock().await = capabilities.clone();
Ok(capabilities)
}
async fn request(
&self,
command: &str,
arguments: Value,
timeout: Duration,
) -> Result<Value, String> {
let sequence = self.next_sequence.fetch_add(1, Ordering::Relaxed);
let message = json!({
"seq":sequence,
"type":"request",
"command":command,
"arguments":arguments
});
let payload = serde_json::to_vec(&message).map_err(|error| error.to_string())?;
let mut frame = format!("Content-Length: {}\r\n\r\n", payload.len()).into_bytes();
frame.extend(payload);
let (response, receiver) = oneshot::channel();
self.pending.lock().await.insert(
sequence,
PendingRequest {
command: command.to_string(),
response,
},
);
if let Err(error) = self
.executions
.input(
&self.execution_id,
&frame,
&format!("dap/{}/{}/{sequence}", self.id, self.execution_id),
&self.controller,
)
.await
{
self.pending.lock().await.remove(&sequence);
return Err(error);
}
match tokio::time::timeout(timeout, receiver).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err(format!(
"DAP request \"{command}\" lost its response channel"
)),
Err(_) => {
self.pending.lock().await.remove(&sequence);
Err(format!(
"DAP request \"{command}\" timed out after {}ms",
timeout.as_millis()
))
}
}
}
async fn wait_for_pause(&self, after: u64, timeout: Duration) -> Result<(), String> {
let mut state = self.snapshot.subscribe();
tokio::time::timeout(timeout, async move {
loop {
let snapshot = state.borrow().clone();
if snapshot.pause_epoch > after && snapshot.paused {
return Ok(());
}
if snapshot.phase == DebuggerPhase::Exited || !snapshot.connected {
return Err(snapshot
.error
.unwrap_or_else(|| "DAP session disconnected before pausing".to_string()));
}
state
.changed()
.await
.map_err(|_| "DAP state channel closed".to_string())?;
}
})
.await
.map_err(|_| "Timed out waiting for DAP stopped state".to_string())?
}
async fn wait_for_running(&self, timeout: Duration) -> Result<(), String> {
let mut state = self.snapshot.subscribe();
tokio::time::timeout(timeout, async move {
loop {
let snapshot = state.borrow().clone();
if snapshot.connected && !snapshot.paused {
return Ok(());
}
if snapshot.phase == DebuggerPhase::Exited || !snapshot.connected {
return Err(snapshot.error.unwrap_or_else(|| {
"DAP session disconnected before resuming".to_string()
}));
}
state
.changed()
.await
.map_err(|_| "DAP state channel closed".to_string())?;
}
})
.await
.map_err(|_| "Timed out waiting for DAP running state".to_string())?
}
async fn current_thread_id(&self) -> Result<i64, String> {
if let Some(thread_id) = *self.thread_id.lock().await {
return Ok(thread_id);
}
self.refresh_threads()
.await?
.first()
.map(|thread| thread.id)
.ok_or_else(|| "DAP adapter reported no threads".to_string())
}
async fn pause(&self, timeout: Duration) -> Result<(), String> {
let state = self.snapshot.borrow().clone();
if state.paused {
return Ok(());
}
let thread_id = self.current_thread_id().await?;
self.request("pause", json!({"threadId":thread_id}), DAP_REQUEST_TIMEOUT)
.await?;
self.wait_for_pause(state.pause_epoch, timeout).await
}
async fn resume(&self) -> Result<(), String> {
let state = self.snapshot.borrow().clone();
if !state.paused {
return Err("Debugger is not paused".to_string());
}
let thread_id = self.current_thread_id().await?;
self.request(
"continue",
json!({"threadId":thread_id,"singleThread":false}),
DAP_REQUEST_TIMEOUT,
)
.await?;
self.wait_for_running(Duration::from_secs(10)).await
}
async fn continue_to_pause(&self, timeout: Duration) -> Result<(), String> {
let state = self.snapshot.borrow().clone();
if !state.paused {
return Err("Debugger is not paused".to_string());
}
let thread_id = self.current_thread_id().await?;
self.request(
"continue",
json!({"threadId":thread_id,"singleThread":false}),
DAP_REQUEST_TIMEOUT,
)
.await?;
self.wait_for_pause(state.pause_epoch, timeout).await
}
async fn step(&self, kind: &str, timeout: Duration) -> Result<(), String> {
let state = self.snapshot.borrow().clone();
if !state.paused {
return Err("Debugger is not paused".to_string());
}
let command = match kind {
"over" => "next",
"into" => "stepIn",
"out" => "stepOut",
other => return Err(format!("Unknown debugger step kind \"{other}\"")),
};
let thread_id = self.current_thread_id().await?;
self.request(
command,
json!({"threadId":thread_id,"singleThread":false}),
DAP_REQUEST_TIMEOUT,
)
.await?;
self.wait_for_pause(state.pause_epoch, timeout).await
}
async fn properties(&self, object_id: &str) -> Result<Vec<DebuggerProperty>, String> {
let reference = object_id
.parse::<i64>()
.map_err(|_| format!("Invalid DAP variables reference \"{object_id}\""))?;
let response = self
.request(
"variables",
json!({"variablesReference":reference}),
DAP_REQUEST_TIMEOUT,
)
.await?;
Ok(response
.get("variables")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(dap_property)
.collect())
}
async fn scopes_for_frame(&self, frame_id: &str) -> Result<Vec<DebuggerScope>, String> {
let id = frame_id
.parse::<i64>()
.map_err(|_| "DAP frame identity is not an integer".to_string())?;
let response = self
.request("scopes", json!({"frameId":id}), DAP_REQUEST_TIMEOUT)
.await?;
Ok(response
.get("scopes")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|scope| DebuggerScope {
kind: scope
.get("presentationHint")
.and_then(Value::as_str)
.or_else(|| scope.get("name").and_then(Value::as_str))
.unwrap_or("scope")
.to_string(),
name: scope
.get("name")
.and_then(Value::as_str)
.unwrap_or("scope")
.to_string(),
object_id: scope
.get("variablesReference")
.and_then(Value::as_i64)
.unwrap_or_default()
.to_string(),
})
.collect())
}
async fn variables(&self, frame: usize) -> Result<Vec<DebuggerVariable>, String> {
let snapshot = self.snapshot.borrow().clone();
let frame_state = snapshot
.frames
.get(frame)
.ok_or_else(|| format!("Debugger frame {frame} not found"))?;
let scopes = self.scopes_for_frame(&frame_state.id).await?;
let mut variables = Vec::new();
for scope in &scopes {
if scope.object_id == "0" || scope.object_id.is_empty() {
continue;
}
for property in self.properties(&scope.object_id).await? {
variables.push(DebuggerVariable {
frame,
scope: scope.kind.clone(),
property,
});
}
}
Ok(variables)
}
async fn evaluate(
&self,
expression: String,
frame: usize,
) -> Result<DebuggerEvaluation, String> {
let snapshot = self.snapshot.borrow().clone();
let mut arguments = json!({"expression":expression,"context":"repl"});
if snapshot.paused {
let frame_id = snapshot
.frames
.get(frame)
.ok_or_else(|| format!("Debugger frame {frame} not found"))?
.id
.parse::<i64>()
.map_err(|_| "DAP frame identity is not an integer".to_string())?;
arguments["frameId"] = json!(frame_id);
}
let response = self
.request("evaluate", arguments, DAP_REQUEST_TIMEOUT)
.await?;
let remote = dap_remote_value(&response);
Ok(DebuggerEvaluation {
kind: remote.kind,
value: remote.value,
subtype: remote.subtype,
class_name: remote.class_name,
description: remote.description,
object_id: remote.object_id,
unserializable_value: remote.unserializable_value,
exception: None,
})
}
async fn reconcile_breakpoints(
&self,
file: &str,
breakpoints: &mut [DebuggerBreakpoint],
) -> Result<(), String> {
let requested = breakpoints
.iter()
.map(|breakpoint| {
let mut value = json!({"line":breakpoint.line});
if let Some(condition) = breakpoint.condition.as_deref() {
value["condition"] = json!(condition);
}
value
})
.collect::<Vec<_>>();
let response = self
.request(
"setBreakpoints",
json!({
"source":{
"path":file,
"name":std::path::Path::new(file)
.file_name()
.and_then(|name| name.to_str())
},
"breakpoints":requested,
"sourceModified":false
}),
DAP_REQUEST_TIMEOUT,
)
.await?;
let resolved = response
.get("breakpoints")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let now = now_ms();
for (index, breakpoint) in breakpoints.iter_mut().enumerate() {
let result = resolved.get(index);
breakpoint.backend_id = result
.and_then(|value| value.get("id"))
.map(value_string)
.filter(|value| !value.is_empty());
breakpoint.resolved = result
.and_then(|value| value.get("verified"))
.and_then(Value::as_bool)
.unwrap_or(false);
breakpoint.line = result
.and_then(|value| value.get("line"))
.and_then(Value::as_u64)
.unwrap_or(breakpoint.line);
breakpoint.updated_at = now;
}
Ok(())
}
async fn set_breakpoint(
&self,
file: String,
line: u64,
condition: Option<String>,
) -> Result<DebuggerBreakpoint, String> {
let now = now_ms();
let breakpoint = DebuggerBreakpoint {
id: uuid::Uuid::now_v7().to_string(),
session_id: self.id.clone(),
backend_id: None,
file: file.clone(),
line,
condition,
resolved: false,
hits: 0,
enabled: true,
created_at: now,
updated_at: now,
};
let mut source_breakpoints = self
.store
.debugger_breakpoints(&self.id)?
.into_iter()
.filter(|existing| existing.file == file && existing.enabled)
.collect::<Vec<_>>();
source_breakpoints.push(breakpoint);
self.reconcile_breakpoints(&file, &mut source_breakpoints)
.await?;
for breakpoint in &source_breakpoints {
self.store.put_debugger_breakpoint(breakpoint)?;
}
source_breakpoints
.pop()
.ok_or_else(|| "DAP breakpoint reconciliation returned no breakpoint".to_string())
}
async fn delete_breakpoint(&self, breakpoint_id: &str) -> Result<DebuggerBreakpoint, String> {
let breakpoint = self
.store
.debugger_breakpoint(breakpoint_id)?
.ok_or_else(|| format!("Debugger breakpoint \"{breakpoint_id}\" not found"))?;
if breakpoint.session_id != self.id {
return Err(format!(
"Debugger breakpoint \"{breakpoint_id}\" does not belong to session \"{}\"",
self.id
));
}
let mut remaining = self
.store
.debugger_breakpoints(&self.id)?
.into_iter()
.filter(|existing| {
existing.id != breakpoint_id && existing.file == breakpoint.file && existing.enabled
})
.collect::<Vec<_>>();
self.reconcile_breakpoints(&breakpoint.file, &mut remaining)
.await?;
for remaining_breakpoint in &remaining {
self.store.put_debugger_breakpoint(remaining_breakpoint)?;
}
self.store.delete_debugger_breakpoint(breakpoint_id)?;
Ok(breakpoint)
}
async fn close(&self) -> Result<(), String> {
let record = self
.store
.debugger_session(&self.id)?
.ok_or_else(|| format!("Debugger session \"{}\" not found", self.id))?;
let terminate_debuggee = !record.target.starts_with("pid:");
let _ = self
.request(
"disconnect",
json!({
"restart":false,
"terminateDebuggee":terminate_debuggee,
"suspendDebuggee":false
}),
Duration::from_secs(2),
)
.await;
self.executions
.cancel_unclaimed(&self.execution_id, Duration::from_secs(5), &self.controller)
.await?;
Ok(())
}
async fn view(&self) -> Result<DapSessionState, String> {
let record = self
.store
.debugger_session(&self.id)?
.ok_or_else(|| format!("Debugger session \"{}\" not found", self.id))?;
let state = self.snapshot.borrow().clone();
let thread_id = *self.thread_id.lock().await;
let threads = self.threads.lock().await.clone();
let modules = self.modules.lock().await.clone();
let capabilities = self.capabilities.lock().await.clone();
Ok(DapSessionState {
view: DebuggerSessionView {
id: record.id,
adapter: record.adapter,
target_id: record.target_id,
target: record.target,
execution_id: record.execution_id,
state,
},
adapter_execution_id: self.execution_id.clone(),
thread_id,
threads,
modules,
capabilities,
})
}
async fn read_loop(self: Arc<Self>) {
let mut offset = 0_u64;
let mut buffer = Vec::new();
loop {
match self
.executions
.stream_chunk(&self.execution_id, "stdout", offset, 256 * 1024)
{
Ok(chunk) => {
offset = chunk.next_offset;
buffer.extend(chunk.bytes);
if let Err(error) = self.process_buffer(&mut buffer).await {
self.fail_and_cancel(error).await;
break;
}
if chunk.terminal {
let error = if buffer.is_empty() {
"DAP adapter execution exited".to_string()
} else {
format!(
"DAP adapter execution exited with an incomplete frame ({} buffered bytes)",
buffer.len()
)
};
self.fail(error).await;
break;
}
}
Err(error) => {
self.fail_and_cancel(error).await;
break;
}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
async fn process_buffer(self: &Arc<Self>, buffer: &mut Vec<u8>) -> Result<(), String> {
loop {
let Some(header_end) = buffer.windows(4).position(|bytes| bytes == b"\r\n\r\n") else {
if buffer.len() > 64 * 1024 {
return Err("DAP protocol header exceeded 64 KiB".to_string());
}
return Ok(());
};
let header = std::str::from_utf8(&buffer[..header_end])
.map_err(|_| "DAP protocol header was not UTF-8".to_string())?;
let content_length = header
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("Content-Length")
.then(|| value.trim().parse::<usize>().ok())
.flatten()
})
.ok_or_else(|| "DAP protocol header is missing Content-Length".to_string())?;
if content_length > DAP_MAX_MESSAGE_BYTES {
return Err(format!(
"DAP protocol message exceeds {} bytes",
DAP_MAX_MESSAGE_BYTES
));
}
let payload_start = header_end + 4;
let payload_end = payload_start.saturating_add(content_length);
if buffer.len() < payload_end {
return Ok(());
}
let payload = buffer[payload_start..payload_end].to_vec();
buffer.drain(..payload_end);
let message: Value = serde_json::from_slice(&payload)
.map_err(|error| format!("Invalid DAP JSON payload: {error}"))?;
self.handle_message(message).await?;
}
}
async fn handle_message(self: &Arc<Self>, message: Value) -> Result<(), String> {
match message.get("type").and_then(Value::as_str) {
Some("response") => {
let request_sequence = message
.get("request_seq")
.and_then(Value::as_u64)
.ok_or_else(|| "DAP response is missing request_seq".to_string())?;
let Some(pending) = self.pending.lock().await.remove(&request_sequence) else {
return Ok(());
};
let result = if message
.get("success")
.and_then(Value::as_bool)
.unwrap_or(false)
{
Ok(message.get("body").cloned().unwrap_or_else(|| json!({})))
} else {
Err(format!(
"DAP request \"{}\" failed: {}",
pending.command,
message
.get("message")
.and_then(Value::as_str)
.unwrap_or("adapter rejected request")
))
};
let _ = pending.response.send(result);
}
Some("event") => {
self.handle_event(
message
.get("event")
.and_then(Value::as_str)
.unwrap_or("unknown"),
message.get("body").cloned().unwrap_or_else(|| json!({})),
)
.await?;
}
Some(other) => return Err(format!("Unsupported DAP message type \"{other}\"")),
None => return Err("DAP message is missing type".to_string()),
}
Ok(())
}
async fn handle_event(self: &Arc<Self>, event: &str, body: Value) -> Result<(), String> {
self.store.append_debugger_event(DebuggerEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
session_id: self.id.clone(),
execution_id: Some(self.execution_id.clone()),
at: now_ms(),
kind: format!("debugger.dap.{event}"),
details: body.clone(),
})?;
match event {
"stopped" => {
let thread_id = body.get("threadId").and_then(Value::as_i64);
if let Some(thread_id) = thread_id {
*self.thread_id.lock().await = Some(thread_id);
}
let mut snapshot = self.snapshot.borrow().clone();
snapshot.phase = DebuggerPhase::Paused;
snapshot.connected = true;
snapshot.paused = true;
snapshot.reason = body
.get("reason")
.and_then(Value::as_str)
.map(ToString::to_string);
snapshot.hit_breakpoints = body
.get("hitBreakpointIds")
.and_then(Value::as_array)
.map(|ids| {
ids.iter()
.filter_map(|id| {
id.as_i64()
.map(|id| id.to_string())
.or_else(|| id.as_str().map(ToString::to_string))
})
.collect()
})
.unwrap_or_default();
snapshot.error = None;
self.publish(snapshot)?;
if let Some(thread_id) = thread_id {
let session = self.clone();
tokio::spawn(async move {
if let Err(error) = session.refresh_stopped(thread_id).await {
let mut snapshot = session.snapshot.borrow().clone();
snapshot.pause_epoch = snapshot.pause_epoch.saturating_add(1);
snapshot.error = Some(error);
let _ = session.publish(snapshot);
}
});
} else {
let mut snapshot = self.snapshot.borrow().clone();
snapshot.pause_epoch = snapshot.pause_epoch.saturating_add(1);
self.publish(snapshot)?;
}
}
"continued" => {
let mut snapshot = self.snapshot.borrow().clone();
snapshot.phase = DebuggerPhase::Running;
snapshot.connected = true;
snapshot.paused = false;
snapshot.frames.clear();
snapshot.async_frames.clear();
self.publish(snapshot)?;
}
"terminated" | "exited" => {
let mut snapshot = self.snapshot.borrow().clone();
snapshot.phase = DebuggerPhase::Exited;
snapshot.connected = false;
snapshot.paused = false;
snapshot.frames.clear();
snapshot.async_frames.clear();
self.publish(snapshot)?;
}
"output" => {
let text = body.get("output").and_then(Value::as_str).unwrap_or("");
if !text.is_empty() {
let mut snapshot = self.snapshot.borrow().clone();
let id = snapshot
.console
.last()
.map_or(1, |entry| entry.id.saturating_add(1));
snapshot.console.push(DebuggerConsoleEntry {
id,
kind: body
.get("category")
.and_then(Value::as_str)
.unwrap_or("stdout")
.to_string(),
text: text.trim_end_matches(['\r', '\n']).to_string(),
at: now_ms() as f64,
stack: Vec::new(),
});
super::retain_last(&mut snapshot.console, 1_000);
self.publish(snapshot)?;
}
}
"thread" => {
let session = self.clone();
tokio::spawn(async move {
let _ = session.refresh_threads().await;
});
}
"module" => {
let session = self.clone();
tokio::spawn(async move {
let _ = session.refresh_modules().await;
});
}
_ => {}
}
Ok(())
}
async fn refresh_stopped(&self, thread_id: i64) -> Result<(), String> {
let _ = self.refresh_threads().await;
let response = self
.request(
"stackTrace",
json!({"threadId":thread_id,"startFrame":0,"levels":64}),
DAP_REQUEST_TIMEOUT,
)
.await?;
let mut frames = Vec::new();
for frame in response
.get("stackFrames")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let frame_id = frame.get("id").and_then(Value::as_i64).unwrap_or_default();
let scopes = self
.request("scopes", json!({"frameId":frame_id}), DAP_REQUEST_TIMEOUT)
.await
.ok()
.and_then(|value| value.get("scopes").and_then(Value::as_array).cloned())
.unwrap_or_default()
.into_iter()
.map(|scope| DebuggerScope {
kind: scope
.get("presentationHint")
.and_then(Value::as_str)
.or_else(|| scope.get("name").and_then(Value::as_str))
.unwrap_or("scope")
.to_string(),
name: scope
.get("name")
.and_then(Value::as_str)
.unwrap_or("scope")
.to_string(),
object_id: scope
.get("variablesReference")
.and_then(Value::as_i64)
.unwrap_or_default()
.to_string(),
})
.collect();
let file = frame
.pointer("/source/path")
.or_else(|| frame.pointer("/source/name"))
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
frames.push(DebuggerFrame {
id: frame_id.to_string(),
function: frame
.get("name")
.and_then(Value::as_str)
.unwrap_or("(anonymous)")
.to_string(),
file: file.clone(),
line: frame.get("line").and_then(Value::as_u64).unwrap_or(1),
column: frame.get("column").and_then(Value::as_u64).unwrap_or(1),
script_id: frame
.get("instructionPointerReference")
.and_then(Value::as_str)
.unwrap_or(&file)
.to_string(),
scopes,
this_object_id: None,
});
}
let mut snapshot = self.snapshot.borrow().clone();
snapshot.frames = frames;
self.charge_breakpoint_hits(&snapshot);
snapshot.pause_epoch = snapshot.pause_epoch.saturating_add(1);
self.publish(snapshot)
}
fn charge_breakpoint_hits(&self, snapshot: &DebuggerSnapshot) {
if snapshot.reason.as_deref() != Some("breakpoint") {
return;
}
let Some(frame) = snapshot.frames.first() else {
return;
};
let Ok(breakpoints) = self.store.debugger_breakpoints(&self.id) else {
return;
};
let now = now_ms();
for mut breakpoint in breakpoints {
let hit_by_id = breakpoint
.backend_id
.as_ref()
.is_some_and(|id| snapshot.hit_breakpoints.contains(id));
let hit_by_site = snapshot.hit_breakpoints.is_empty()
&& breakpoint.line == frame.line
&& super::source_paths_match(&frame.file, &breakpoint.file);
if hit_by_id || hit_by_site {
breakpoint.hits = breakpoint.hits.saturating_add(1);
breakpoint.resolved = true;
breakpoint.updated_at = now;
let _ = self.store.put_debugger_breakpoint(&breakpoint);
}
}
}
async fn refresh_threads(&self) -> Result<Vec<DapThread>, String> {
let response = self
.request("threads", json!({}), DAP_REQUEST_TIMEOUT)
.await?;
let threads = response
.get("threads")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|thread| DapThread {
id: thread.get("id").and_then(Value::as_i64).unwrap_or_default(),
name: thread
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
})
.collect::<Vec<_>>();
if self.thread_id.lock().await.is_none()
&& let Some(thread) = threads.first()
{
*self.thread_id.lock().await = Some(thread.id);
}
*self.threads.lock().await = threads.clone();
Ok(threads)
}
async fn refresh_modules(&self) -> Result<Vec<DapModule>, String> {
let response = self
.request("modules", json!({}), DAP_REQUEST_TIMEOUT)
.await?;
let modules = response
.get("modules")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|module| DapModule {
id: module.get("id").map_or_else(String::new, value_string),
name: module
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
path: module
.get("path")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
base_address: module
.get("baseAddress")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
size: module
.get("size")
.and_then(Value::as_u64)
.unwrap_or_default(),
})
.collect::<Vec<_>>();
*self.modules.lock().await = modules.clone();
Ok(modules)
}
async fn registers(&self) -> Result<Vec<DapRegister>, String> {
let snapshot = self.snapshot.borrow().clone();
let scopes = snapshot
.frames
.first()
.ok_or_else(|| "DAP session has no paused frame for register reads".to_string())?
.scopes
.iter()
.filter(|scope| {
scope.name.to_ascii_lowercase().contains("register")
|| scope.kind.to_ascii_lowercase().contains("register")
})
.cloned()
.collect::<Vec<_>>();
if scopes.is_empty() {
return Err("DAP adapter reported no register scope for the top frame".to_string());
}
let mut registers = Vec::new();
for scope in scopes {
for property in self.properties(&scope.object_id).await? {
registers.push(DapRegister {
group: scope.name.clone(),
name: property.name,
value: property
.value
.description
.unwrap_or_else(|| property.value.value.to_string()),
});
}
}
Ok(registers)
}
async fn memory(&self, address: &str, count: u64) -> Result<DapMemory, String> {
if count == 0 || count > 16 * 1024 * 1024 {
return Err("DAP memory count must be between 1 and 16777216 bytes".to_string());
}
let response = self
.request(
"readMemory",
json!({"memoryReference":address,"count":count}),
DAP_REQUEST_TIMEOUT,
)
.await?;
Ok(DapMemory {
address: response
.get("address")
.and_then(Value::as_str)
.unwrap_or(address)
.to_string(),
data: response
.get("data")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
unreadable_bytes: response
.get("unreadableBytes")
.and_then(Value::as_u64)
.unwrap_or_default(),
})
}
async fn disassemble(&self, address: &str, count: u64) -> Result<Vec<DapInstruction>, String> {
if count == 0 || count > 4096 {
return Err("DAP instruction count must be between 1 and 4096".to_string());
}
let response = self
.request(
"disassemble",
json!({
"memoryReference":address,
"offset":0,
"instructionCount":count
}),
DAP_REQUEST_TIMEOUT,
)
.await?;
Ok(response
.get("instructions")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|instruction| DapInstruction {
address: instruction
.get("address")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
instruction: instruction
.get("instruction")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
symbol: instruction
.get("symbol")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
location: instruction
.pointer("/location/path")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
line: instruction
.get("line")
.and_then(Value::as_u64)
.or_else(|| {
instruction
.pointer("/location/line")
.and_then(Value::as_u64)
})
.unwrap_or_default(),
})
.collect())
}
async fn signals(&self) -> Result<Vec<DapSignal>, String> {
let response = self
.request("signals", json!({}), DAP_REQUEST_TIMEOUT)
.await?;
Ok(response
.get("signals")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|signal| DapSignal {
name: signal
.get("name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
stop: signal.get("stop").and_then(Value::as_bool).unwrap_or(false),
pass: signal.get("pass").and_then(Value::as_bool).unwrap_or(false),
notify: signal
.get("notify")
.and_then(Value::as_bool)
.unwrap_or(false),
})
.collect())
}
async fn watchpoints(&self) -> Result<Vec<DapWatchpoint>, String> {
let response = self
.request("watchpoints", json!({}), DAP_REQUEST_TIMEOUT)
.await?;
Ok(response
.get("watchpoints")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|watchpoint| DapWatchpoint {
id: watchpoint.get("id").map(value_string).unwrap_or_default(),
expression: watchpoint
.get("expression")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
access: watchpoint
.get("access")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
enabled: watchpoint
.get("enabled")
.and_then(Value::as_bool)
.unwrap_or(false),
})
.collect())
}
fn publish(&self, snapshot: DebuggerSnapshot) -> Result<(), String> {
self.snapshot.send_replace(snapshot.clone());
let mut record = self
.store
.debugger_session(&self.id)?
.ok_or_else(|| format!("Debugger session \"{}\" not found", self.id))?;
record.observed_state = snapshot;
record.updated_at = now_ms();
self.store.put_debugger_session(&record)
}
async fn fail(&self, error: String) {
let pending = std::mem::take(&mut *self.pending.lock().await);
for (_, pending) in pending {
let _ = pending.response.send(Err(error.clone()));
}
let mut snapshot = self.snapshot.borrow().clone();
snapshot.phase = DebuggerPhase::Disconnected;
snapshot.connected = false;
snapshot.paused = false;
snapshot.error = Some(error);
let _ = self.publish(snapshot);
}
async fn fail_and_cancel(&self, error: String) {
self.fail(error.clone()).await;
if let Err(cancel_error) = self
.executions
.cancel_unclaimed(&self.execution_id, Duration::from_secs(5), &self.controller)
.await
{
self.fail(format!(
"{error}; failed to cancel DAP adapter execution: {cancel_error}"
))
.await;
}
}
}
impl DebuggerManager {
pub(crate) async fn dap_open(
&self,
id: String,
target: String,
execution_id: String,
executions: ExecutionManager,
controller: ProcessController,
) -> Result<Arc<DapSession>, String> {
if self.sessions.read().await.contains_key(&id)
|| self.dap_sessions.read().await.contains_key(&id)
{
return Err(format!("Debugger session \"{id}\" already exists"));
}
let now = now_ms();
let snapshot = DebuggerSnapshot {
phase: DebuggerPhase::Connecting,
error: Some("DAP initialization is starting".to_string()),
..DebuggerSnapshot::default()
};
self.store.put_debugger_session(&DebuggerSessionRecord {
id: id.clone(),
adapter: DebuggerAdapterKind::Lldb,
target,
target_id: None,
host: None,
port: None,
execution_id: Some(execution_id.clone()),
desired_state: super::DebuggerDesiredState::Open,
observed_state: snapshot.clone(),
created_at: now,
updated_at: now,
})?;
let session = DapSession::new(
id.clone(),
execution_id,
executions,
self.store.clone(),
controller,
snapshot,
);
self.dap_sessions.write().await.insert(id, session.clone());
session.start_reader();
session.initialize().await?;
let mut snapshot = session.snapshot.borrow().clone();
snapshot.phase = DebuggerPhase::Running;
snapshot.connected = true;
snapshot.paused = false;
snapshot.error = None;
session.publish(snapshot)?;
Ok(session)
}
pub(crate) async fn dap_session(&self, id: &str) -> Result<Arc<DapSession>, String> {
self.dap_sessions
.read()
.await
.get(id)
.cloned()
.ok_or_else(|| format!("DAP session \"{id}\" not found"))
}
pub(crate) async fn dap_session_if_present(&self, id: &str) -> Option<Arc<DapSession>> {
self.dap_sessions.read().await.get(id).cloned()
}
pub(crate) async fn dap_pause(
&self,
id: &str,
timeout: Duration,
) -> Result<DebuggerSessionView, String> {
self.dap_session(id).await?.pause(timeout).await?;
self.status(id).await
}
pub(crate) async fn dap_resume(&self, id: &str) -> Result<DebuggerSessionView, String> {
self.dap_session(id).await?.resume().await?;
self.status(id).await
}
pub(crate) async fn dap_continue_to_pause(
&self,
id: &str,
timeout: Duration,
) -> Result<DebuggerSessionView, String> {
self.dap_session(id)
.await?
.continue_to_pause(timeout)
.await?;
self.status(id).await
}
pub(crate) async fn dap_step(
&self,
id: &str,
kind: &str,
timeout: Duration,
) -> Result<DebuggerSessionView, String> {
self.dap_session(id).await?.step(kind, timeout).await?;
self.status(id).await
}
pub(crate) async fn dap_variables(
&self,
id: &str,
frame: usize,
) -> Result<Vec<DebuggerVariable>, String> {
self.dap_session(id).await?.variables(frame).await
}
pub(crate) async fn dap_stack(&self, id: &str) -> Result<Vec<DebuggerFrame>, String> {
Ok(self.dap_session(id).await?.snapshot.borrow().frames.clone())
}
pub(crate) async fn dap_properties(
&self,
id: &str,
object_id: &str,
) -> Result<Vec<DebuggerProperty>, String> {
self.dap_session(id).await?.properties(object_id).await
}
pub(crate) async fn dap_evaluate(
&self,
id: &str,
expression: String,
frame: usize,
) -> Result<DebuggerEvaluation, String> {
self.dap_session(id)
.await?
.evaluate(expression, frame)
.await
}
pub(crate) async fn dap_set_breakpoint(
&self,
id: &str,
file: String,
line: u64,
condition: Option<String>,
) -> Result<DebuggerBreakpoint, String> {
self.dap_session(id)
.await?
.set_breakpoint(file, line, condition)
.await
}
pub(crate) async fn dap_delete_breakpoint(
&self,
id: &str,
breakpoint_id: &str,
) -> Result<DebuggerBreakpoint, String> {
self.dap_session(id)
.await?
.delete_breakpoint(breakpoint_id)
.await
}
pub(crate) async fn dap_close(&self, id: &str) -> Result<(), String> {
let session = self.dap_session(id).await?;
let outcome = session.close().await;
self.dap_sessions.write().await.remove(id);
outcome
}
pub(crate) async fn dap_abort(&self, id: &str) {
if let Some(session) = self.dap_sessions.write().await.remove(id) {
let _ = session.close().await;
}
}
pub async fn dap_request(
&self,
id: &str,
command: &str,
arguments: Value,
timeout: Duration,
) -> Result<Value, String> {
self.dap_session(id)
.await?
.request(command, arguments, timeout)
.await
}
pub async fn dap_threads(&self, id: &str) -> Result<Vec<DapThread>, String> {
self.dap_session(id).await?.refresh_threads().await
}
pub async fn dap_modules(&self, id: &str) -> Result<Vec<DapModule>, String> {
self.dap_session(id).await?.refresh_modules().await
}
pub async fn dap_registers(&self, id: &str) -> Result<Vec<DapRegister>, String> {
self.dap_session(id).await?.registers().await
}
pub async fn dap_memory(
&self,
id: &str,
address: &str,
count: u64,
) -> Result<DapMemory, String> {
self.dap_session(id).await?.memory(address, count).await
}
pub async fn dap_disassemble(
&self,
id: &str,
address: &str,
count: u64,
) -> Result<Vec<DapInstruction>, String> {
self.dap_session(id)
.await?
.disassemble(address, count)
.await
}
pub async fn dap_signals(&self, id: &str) -> Result<Vec<DapSignal>, String> {
self.dap_session(id).await?.signals().await
}
pub async fn dap_watchpoints(&self, id: &str) -> Result<Vec<DapWatchpoint>, String> {
self.dap_session(id).await?.watchpoints().await
}
pub async fn dap_state(&self, id: &str) -> Result<DapSessionState, String> {
self.dap_session(id).await?.view().await
}
pub async fn dap_wait_for_pause(
&self,
id: &str,
after: u64,
timeout: Duration,
) -> Result<(), String> {
self.dap_session(id)
.await?
.wait_for_pause(after, timeout)
.await
}
pub async fn dap_mark_error(&self, id: &str, error: String) -> Result<(), String> {
let session = self.dap_session(id).await?;
let mut snapshot = session.snapshot.borrow().clone();
snapshot.phase = DebuggerPhase::Disconnected;
snapshot.connected = false;
snapshot.paused = false;
snapshot.error = Some(error);
session.publish(snapshot)
}
}
fn value_string(value: &Value) -> String {
value
.as_str()
.map(ToString::to_string)
.unwrap_or_else(|| value.to_string())
}
fn dap_remote_value(value: &Value) -> DebuggerRemoteValue {
let description = value
.get("value")
.or_else(|| value.get("result"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let reference = value
.get("variablesReference")
.and_then(Value::as_i64)
.unwrap_or_default();
DebuggerRemoteValue {
kind: value
.get("type")
.and_then(Value::as_str)
.unwrap_or("unknown")
.to_string(),
subtype: None,
class_name: value
.pointer("/presentationHint/kind")
.and_then(Value::as_str)
.map(ToString::to_string),
description: Some(description.clone()),
value: Value::String(description),
object_id: (reference != 0).then(|| reference.to_string()),
unserializable_value: None,
}
}
fn dap_property(value: &Value) -> DebuggerProperty {
let read_only = value
.pointer("/presentationHint/attributes")
.and_then(Value::as_array)
.is_some_and(|attributes| attributes.iter().any(|value| value == "readOnly"));
DebuggerProperty {
name: value
.get("name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
value: dap_remote_value(value),
writable: !read_only,
configurable: false,
enumerable: true,
internal: false,
}
}
#[cfg(test)]
mod tests {
#[test]
fn parses_split_dap_frames_and_rejects_missing_lengths() {
let payload = br#"{"seq":1,"type":"event","event":"initialized"}"#;
let frame = [
format!("Content-Length: {}\r\n\r\n", payload.len()).as_bytes(),
payload,
]
.concat();
assert!(frame.windows(4).any(|bytes| bytes == b"\r\n\r\n"));
assert!(!String::from_utf8_lossy(&frame).contains("Content-Length: 0"));
}
}