Skip to main content

glass_dev/
debugger.rs

1//! Resident Debug Adapter Protocol runtime.
2//!
3//! The runtime owns one adapter process and speaks bounded DAP framing over
4//! stdio. Higher-level debugger methods retain adapter-neutral JSON bodies so
5//! LLDB, debugpy, Delve and JavaScript adapters can share one implementation.
6
7use crate::development::{ProcessManager, ProcessSnapshot};
8use serde::{Deserialize, Serialize};
9use serde_json::{Value, json};
10use std::collections::{BTreeMap, VecDeque};
11use std::fmt;
12use std::io::{BufRead, BufReader, Read, Write};
13use std::net::{SocketAddr, TcpStream};
14use std::path::{Path, PathBuf};
15use std::process::{Child, Command, Stdio};
16use std::sync::mpsc::{self, Receiver, RecvTimeoutError, TrySendError};
17use std::thread::JoinHandle;
18use std::time::{Duration, Instant};
19
20const MAX_DAP_HEADER_BYTES: usize = 8 * 1024;
21const MAX_DAP_MESSAGE_BYTES: usize = 4 * 1024 * 1024;
22const MAX_PENDING_MESSAGES: usize = 512;
23type DapWriter = Box<dyn Write + Send>;
24type DapReader = Box<dyn Read + Send>;
25type AdapterStreams = (DapWriter, DapReader, Vec<JoinHandle<()>>);
26
27pub type DebugResult<T> = Result<T, DebugError>;
28
29#[derive(Debug)]
30pub enum DebugError {
31    Io(std::io::Error),
32    InvalidInput(String),
33    Protocol(String),
34    Adapter(String),
35    Timeout(String),
36}
37
38impl fmt::Display for DebugError {
39    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::Io(error) => write!(formatter, "debug adapter I/O error: {error}"),
42            Self::InvalidInput(message) => write!(formatter, "invalid debugger input: {message}"),
43            Self::Protocol(message) => write!(formatter, "debug adapter protocol error: {message}"),
44            Self::Adapter(message) => {
45                write!(formatter, "debug adapter rejected request: {message}")
46            }
47            Self::Timeout(message) => write!(formatter, "debug adapter timeout: {message}"),
48        }
49    }
50}
51
52impl std::error::Error for DebugError {}
53
54impl From<std::io::Error> for DebugError {
55    fn from(error: std::io::Error) -> Self {
56        Self::Io(error)
57    }
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
61pub struct DebugAdapterConfig {
62    pub command: PathBuf,
63    #[serde(default)]
64    pub arguments: Vec<String>,
65    #[serde(default)]
66    pub transport: DebugAdapterTransport,
67}
68
69#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
70#[serde(tag = "kind", rename_all = "camelCase")]
71pub enum DebugAdapterTransport {
72    #[default]
73    Stdio,
74    Tcp {
75        address: SocketAddr,
76        #[serde(default = "default_connect_timeout_ms")]
77        connect_timeout_ms: u64,
78    },
79}
80
81const fn default_connect_timeout_ms() -> u64 {
82    5_000
83}
84
85impl DebugAdapterConfig {
86    pub fn new(command: impl Into<PathBuf>, arguments: impl IntoIterator<Item = String>) -> Self {
87        Self {
88            command: command.into(),
89            arguments: arguments.into_iter().collect(),
90            transport: DebugAdapterTransport::Stdio,
91        }
92    }
93
94    pub fn with_tcp(mut self, address: SocketAddr, connect_timeout: Duration) -> Self {
95        self.transport = DebugAdapterTransport::Tcp {
96            address,
97            connect_timeout_ms: u64::try_from(connect_timeout.as_millis()).unwrap_or(u64::MAX),
98        };
99        self
100    }
101}
102
103#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
104#[serde(rename_all = "camelCase")]
105pub enum DebugSessionState {
106    Starting,
107    Initialized,
108    Running,
109    Stopped,
110    Terminated,
111    Failed,
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
115pub struct DebugEvent {
116    pub event: String,
117    #[serde(default)]
118    pub body: Value,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
122#[serde(rename_all = "camelCase")]
123pub struct DebuggerSnapshot {
124    pub state: DebugSessionState,
125    pub adapter_process_id: u32,
126    pub capabilities: Value,
127    pub breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
128    pub watches: Vec<String>,
129    pub events: Vec<DebugEvent>,
130    pub debuggee_processes: Vec<ProcessSnapshot>,
131}
132
133#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
134#[serde(rename_all = "camelCase")]
135pub struct SourceBreakpoint {
136    pub line: u64,
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub condition: Option<String>,
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub hit_condition: Option<String>,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub log_message: Option<String>,
143}
144
145impl SourceBreakpoint {
146    pub fn line(line: u64) -> Self {
147        Self {
148            line,
149            condition: None,
150            hit_condition: None,
151            log_message: None,
152        }
153    }
154}
155
156/// One owned DAP adapter process with bounded request and event queues.
157pub struct DapClient {
158    child: Child,
159    stdin: DapWriter,
160    messages: Receiver<DebugResult<Value>>,
161    reader: Option<JoinHandle<()>>,
162    output_drains: Vec<JoinHandle<()>>,
163    pending: VecDeque<Value>,
164    next_sequence: u64,
165    root: PathBuf,
166    debuggees: ProcessManager,
167}
168
169impl DapClient {
170    pub fn spawn(root: &Path, config: &DebugAdapterConfig) -> DebugResult<Self> {
171        if !root.is_dir() {
172            return Err(DebugError::InvalidInput(format!(
173                "debugger project root is not a directory: {}",
174                root.display()
175            )));
176        }
177        if config.command.as_os_str().is_empty() {
178            return Err(DebugError::InvalidInput(
179                "debug adapter command must not be empty".into(),
180            ));
181        }
182        let mut child = Command::new(&config.command)
183            .args(&config.arguments)
184            .current_dir(root)
185            .stdin(Stdio::piped())
186            .stdout(Stdio::piped())
187            .stderr(Stdio::piped())
188            .spawn()?;
189        let child_stdin = child
190            .stdin
191            .take()
192            .ok_or_else(|| DebugError::Protocol("adapter stdin was unavailable".into()))?;
193        let child_stdout = child
194            .stdout
195            .take()
196            .ok_or_else(|| DebugError::Protocol("adapter stdout was unavailable".into()))?;
197        let child_stderr = child
198            .stderr
199            .take()
200            .ok_or_else(|| DebugError::Protocol("adapter stderr was unavailable".into()))?;
201        let (stdin, stdout, output_drains): AdapterStreams = match config.transport {
202            DebugAdapterTransport::Stdio => (
203                Box::new(child_stdin),
204                Box::new(child_stdout),
205                vec![spawn_output_drain(child_stderr)],
206            ),
207            DebugAdapterTransport::Tcp {
208                address,
209                connect_timeout_ms,
210            } => {
211                if !address.ip().is_loopback() || connect_timeout_ms == 0 {
212                    let _ = child.kill();
213                    let _ = child.wait();
214                    return Err(DebugError::InvalidInput(
215                        "DAP TCP transport requires a loopback address and positive timeout".into(),
216                    ));
217                }
218                drop(child_stdin);
219                let output_drains = vec![
220                    spawn_output_drain(child_stdout),
221                    spawn_output_drain(child_stderr),
222                ];
223                let deadline = Instant::now() + Duration::from_millis(connect_timeout_ms);
224                let stream = loop {
225                    match TcpStream::connect_timeout(&address, Duration::from_millis(100)) {
226                        Ok(stream) => break stream,
227                        Err(error) => {
228                            if child.try_wait()?.is_some() {
229                                return Err(DebugError::Protocol(format!(
230                                    "TCP debug adapter exited before accepting {address}: {error}"
231                                )));
232                            }
233                            if Instant::now() >= deadline {
234                                let _ = child.kill();
235                                let _ = child.wait();
236                                return Err(DebugError::Timeout(format!(
237                                    "TCP debug adapter did not accept {address} within {connect_timeout_ms} ms"
238                                )));
239                            }
240                        }
241                    }
242                };
243                let reader = stream.try_clone()?;
244                (Box::new(stream), Box::new(reader), output_drains)
245            }
246        };
247        let (sender, messages) = mpsc::sync_channel(MAX_PENDING_MESSAGES);
248        let reader = std::thread::spawn(move || {
249            let mut stdout = BufReader::new(stdout);
250            loop {
251                match read_dap_message(&mut stdout) {
252                    Ok(Some(message)) => match sender.try_send(Ok(message)) {
253                        Ok(()) => {}
254                        Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => break,
255                    },
256                    Ok(None) => break,
257                    Err(error) => {
258                        let _ = sender.try_send(Err(error));
259                        break;
260                    }
261                }
262            }
263        });
264        Ok(Self {
265            child,
266            stdin,
267            messages,
268            reader: Some(reader),
269            output_drains,
270            pending: VecDeque::new(),
271            next_sequence: 1,
272            root: root.to_path_buf(),
273            debuggees: ProcessManager::new(root),
274        })
275    }
276
277    pub fn process_id(&self) -> u32 {
278        self.child.id()
279    }
280
281    pub fn request(
282        &mut self,
283        command: &str,
284        arguments: Value,
285        timeout: Duration,
286    ) -> DebugResult<Value> {
287        let sequence = self.send_request(command, arguments)?;
288        self.wait_for_response(sequence, command, timeout)
289    }
290
291    fn send_request(&mut self, command: &str, arguments: Value) -> DebugResult<u64> {
292        if command.is_empty() || command.len() > 128 {
293            return Err(DebugError::InvalidInput(
294                "DAP command must contain 1..=128 bytes".into(),
295            ));
296        }
297        let sequence = self.take_sequence()?;
298        write_dap_message(
299            &mut self.stdin,
300            &json!({
301                "seq": sequence,
302                "type": "request",
303                "command": command,
304                "arguments": arguments,
305            }),
306        )?;
307
308        Ok(sequence)
309    }
310
311    fn wait_for_response(
312        &mut self,
313        sequence: u64,
314        command: &str,
315        timeout: Duration,
316    ) -> DebugResult<Value> {
317        let deadline = Instant::now() + timeout;
318        loop {
319            if let Some(response) = take_response(&mut self.pending, sequence) {
320                return response_body(response, command);
321            }
322            let remaining = deadline.saturating_duration_since(Instant::now());
323            if remaining.is_zero() {
324                return Err(DebugError::Timeout(format!(
325                    "request {command} exceeded {} ms",
326                    timeout.as_millis()
327                )));
328            }
329            match self.messages.recv_timeout(remaining) {
330                Ok(Ok(message)) => {
331                    let Some(message) = self.route_inbound(message)? else {
332                        continue;
333                    };
334                    if is_response_for(&message, sequence) {
335                        return response_body(message, command);
336                    }
337                    push_pending(&mut self.pending, message)?;
338                }
339                Ok(Err(error)) => return Err(error),
340                Err(RecvTimeoutError::Timeout) => {
341                    return Err(DebugError::Timeout(format!(
342                        "request {command} exceeded {} ms",
343                        timeout.as_millis()
344                    )));
345                }
346                Err(RecvTimeoutError::Disconnected) => {
347                    return Err(DebugError::Protocol(
348                        "debug adapter event stream closed".into(),
349                    ));
350                }
351            }
352        }
353    }
354
355    pub fn poll_events(&mut self) -> DebugResult<Vec<DebugEvent>> {
356        while let Ok(message) = self.messages.try_recv() {
357            if let Some(message) = self.route_inbound(message?)? {
358                push_pending(&mut self.pending, message)?;
359            }
360        }
361        let mut events = Vec::new();
362        let mut retained = VecDeque::new();
363        while let Some(message) = self.pending.pop_front() {
364            if message.get("type").and_then(Value::as_str) == Some("event") {
365                let event = message
366                    .get("event")
367                    .and_then(Value::as_str)
368                    .ok_or_else(|| DebugError::Protocol("DAP event has no name".into()))?;
369                events.push(DebugEvent {
370                    event: event.to_string(),
371                    body: message.get("body").cloned().unwrap_or(Value::Null),
372                });
373            } else {
374                retained.push_back(message);
375            }
376        }
377        self.pending = retained;
378        Ok(events)
379    }
380
381    fn route_inbound(&mut self, message: Value) -> DebugResult<Option<Value>> {
382        if message.get("type").and_then(Value::as_str) != Some("request") {
383            return Ok(Some(message));
384        }
385        let request_sequence = message
386            .get("seq")
387            .and_then(Value::as_u64)
388            .ok_or_else(|| DebugError::Protocol("DAP reverse request has no sequence".into()))?;
389        let command = message
390            .get("command")
391            .and_then(Value::as_str)
392            .ok_or_else(|| DebugError::Protocol("DAP reverse request has no command".into()))?;
393        let result = match command {
394            "runInTerminal" => self.run_in_terminal(
395                request_sequence,
396                message
397                    .get("arguments")
398                    .cloned()
399                    .unwrap_or_else(|| json!({})),
400            ),
401            _ => Err(DebugError::Adapter(format!(
402                "unsupported reverse request {command}"
403            ))),
404        };
405        let (success, body, error) = match result {
406            Ok(body) => (true, body, None),
407            Err(error) => (false, Value::Null, Some(error.to_string())),
408        };
409        let response_sequence = self.take_sequence()?;
410        let mut response = json!({
411            "seq": response_sequence,
412            "type": "response",
413            "request_seq": request_sequence,
414            "success": success,
415            "command": command,
416        });
417        if success {
418            response["body"] = body.clone();
419        } else if let Some(error) = &error {
420            response["message"] = json!(error);
421        }
422        write_dap_message(&mut self.stdin, &response)?;
423        push_pending(
424            &mut self.pending,
425            json!({
426                "type":"event",
427                "event":"glass/reverseRequest",
428                "body":{
429                    "command":command,
430                    "requestSequence":request_sequence,
431                    "success":success,
432                    "response":body,
433                    "error":error,
434                }
435            }),
436        )?;
437        Ok(None)
438    }
439
440    fn run_in_terminal(&mut self, sequence: u64, arguments: Value) -> DebugResult<Value> {
441        let argv = arguments
442            .get("args")
443            .and_then(Value::as_array)
444            .ok_or_else(|| DebugError::InvalidInput("runInTerminal requires args".into()))?
445            .iter()
446            .map(|argument| {
447                argument.as_str().map(str::to_string).ok_or_else(|| {
448                    DebugError::InvalidInput("runInTerminal args must be strings".into())
449                })
450            })
451            .collect::<DebugResult<Vec<_>>>()?;
452        let cwd = arguments
453            .get("cwd")
454            .and_then(Value::as_str)
455            .map(PathBuf::from)
456            .unwrap_or_else(|| self.root.clone());
457        let mut environment = BTreeMap::new();
458        if let Some(values) = arguments.get("env") {
459            let values = values.as_object().ok_or_else(|| {
460                DebugError::InvalidInput("runInTerminal env must be an object".into())
461            })?;
462            for (key, value) in values {
463                if value.is_null() {
464                    continue;
465                }
466                let value = value.as_str().ok_or_else(|| {
467                    DebugError::InvalidInput(
468                        "runInTerminal environment values must be strings or null".into(),
469                    )
470                })?;
471                environment.insert(key.clone(), value.to_string());
472            }
473        }
474        let name = format!("dap-{sequence}");
475        let snapshot = self
476            .debuggees
477            .start_argv(&name, &argv, &cwd, &environment)
478            .map_err(|error| DebugError::Adapter(error.to_string()))?;
479        Ok(json!({
480            "processId": snapshot.pid,
481            "shellProcessId": snapshot.pid,
482            "glassProcess": snapshot,
483        }))
484    }
485
486    fn take_sequence(&mut self) -> DebugResult<u64> {
487        let sequence = self.next_sequence;
488        self.next_sequence = self
489            .next_sequence
490            .checked_add(1)
491            .ok_or_else(|| DebugError::Protocol("DAP sequence overflowed".into()))?;
492        Ok(sequence)
493    }
494
495    pub fn debuggee_processes(&mut self) -> DebugResult<Vec<ProcessSnapshot>> {
496        self.debuggees
497            .list_checked()
498            .map_err(|error| DebugError::Adapter(error.to_string()))
499    }
500
501    pub fn shutdown(&mut self) -> DebugResult<()> {
502        if self.child.try_wait()?.is_none() {
503            let _ = self.request(
504                "disconnect",
505                json!({"terminateDebuggee": true}),
506                Duration::from_secs(2),
507            );
508            if self.child.try_wait()?.is_none() {
509                self.child.kill()?;
510            }
511            let _ = self.child.wait();
512        }
513        if let Some(reader) = self.reader.take() {
514            let _ = reader.join();
515        }
516        for drain in self.output_drains.drain(..) {
517            let _ = drain.join();
518        }
519        Ok(())
520    }
521}
522
523impl Drop for DapClient {
524    fn drop(&mut self) {
525        if self.child.try_wait().ok().flatten().is_none() {
526            let _ = self.child.kill();
527            let _ = self.child.wait();
528        }
529        if let Some(reader) = self.reader.take() {
530            let _ = reader.join();
531        }
532        for drain in self.output_drains.drain(..) {
533            let _ = drain.join();
534        }
535    }
536}
537
538fn spawn_output_drain(mut output: impl Read + Send + 'static) -> JoinHandle<()> {
539    std::thread::spawn(move || {
540        let mut sink = std::io::sink();
541        let _ = std::io::copy(&mut output, &mut sink);
542    })
543}
544
545/// Adapter-neutral debugger session state and typed operations.
546pub struct DebuggerSession {
547    client: DapClient,
548    state: DebugSessionState,
549    capabilities: Value,
550    timeout: Duration,
551    pending_start: Option<(u64, &'static str)>,
552    breakpoints: BTreeMap<PathBuf, Vec<SourceBreakpoint>>,
553    watches: Vec<String>,
554    events: VecDeque<DebugEvent>,
555}
556
557impl DebuggerSession {
558    pub fn start(
559        root: &Path,
560        config: &DebugAdapterConfig,
561        client_name: &str,
562        timeout: Duration,
563    ) -> DebugResult<Self> {
564        let mut client = DapClient::spawn(root, config)?;
565        let capabilities = client.request(
566            "initialize",
567            json!({
568                "clientID": "glass-dev",
569                "clientName": client_name,
570                "adapterID": "glass",
571                "pathFormat": "path",
572                "linesStartAt1": true,
573                "columnsStartAt1": true,
574                "supportsVariableType": true,
575                "supportsVariablePaging": true,
576                "supportsRunInTerminalRequest": true,
577            }),
578            timeout,
579        )?;
580        Ok(Self {
581            client,
582            state: DebugSessionState::Initialized,
583            capabilities,
584            timeout,
585            pending_start: None,
586            breakpoints: BTreeMap::new(),
587            watches: Vec::new(),
588            events: VecDeque::new(),
589        })
590    }
591
592    pub fn state(&self) -> DebugSessionState {
593        self.state
594    }
595
596    pub fn capabilities(&self) -> &Value {
597        &self.capabilities
598    }
599
600    pub fn launch(&mut self, arguments: Value) -> DebugResult<Value> {
601        self.begin_start("launch", arguments)
602    }
603
604    pub fn attach(&mut self, arguments: Value) -> DebugResult<Value> {
605        self.begin_start("attach", arguments)
606    }
607
608    pub fn configuration_done(&mut self) -> DebugResult<Value> {
609        let configuration = self
610            .client
611            .request("configurationDone", json!({}), self.timeout)?;
612        let startup = if let Some((sequence, command)) = self.pending_start.take() {
613            self.client
614                .wait_for_response(sequence, command, self.timeout)?
615        } else {
616            Value::Null
617        };
618        self.state = DebugSessionState::Running;
619        Ok(json!({"configurationDone": configuration, "startup": startup}))
620    }
621
622    fn begin_start(&mut self, command: &'static str, arguments: Value) -> DebugResult<Value> {
623        if self.pending_start.is_some() {
624            return Err(DebugError::InvalidInput(
625                "a debugger launch or attach request is already pending".into(),
626            ));
627        }
628        let sequence = self.client.send_request(command, arguments)?;
629        self.pending_start = Some((sequence, command));
630        self.state = DebugSessionState::Starting;
631        Ok(json!({"pending": true, "requestSequence": sequence}))
632    }
633
634    pub fn restart(&mut self, arguments: Value) -> DebugResult<Value> {
635        let body = self.client.request("restart", arguments, self.timeout)?;
636        self.state = DebugSessionState::Running;
637        Ok(body)
638    }
639
640    pub fn set_breakpoints(&mut self, path: &Path, lines: &[u64]) -> DebugResult<Value> {
641        let breakpoints = lines
642            .iter()
643            .copied()
644            .map(SourceBreakpoint::line)
645            .collect::<Vec<_>>();
646        self.set_source_breakpoints(path, &breakpoints)
647    }
648
649    pub fn set_source_breakpoints(
650        &mut self,
651        path: &Path,
652        breakpoints: &[SourceBreakpoint],
653    ) -> DebugResult<Value> {
654        if breakpoints.len() > 256 || breakpoints.iter().any(|item| item.line == 0) {
655            return Err(DebugError::InvalidInput(
656                "breakpoints require at most 256 positive line numbers".into(),
657            ));
658        }
659        let result = self.client.request(
660            "setBreakpoints",
661            json!({
662                "source": {"path": path},
663                "breakpoints": breakpoints,
664                "sourceModified": false,
665            }),
666            self.timeout,
667        )?;
668        if breakpoints.is_empty() {
669            self.breakpoints.remove(path);
670        } else {
671            self.breakpoints
672                .insert(path.to_path_buf(), breakpoints.to_vec());
673        }
674        Ok(result)
675    }
676
677    pub fn set_exception_breakpoints(&mut self, filters: &[String]) -> DebugResult<Value> {
678        self.client.request(
679            "setExceptionBreakpoints",
680            json!({"filters": filters}),
681            self.timeout,
682        )
683    }
684
685    pub fn continue_thread(&mut self, thread_id: i64) -> DebugResult<Value> {
686        let body = self.client.request(
687            "continue",
688            json!({"threadId": positive_id(thread_id, "thread")?}),
689            self.timeout,
690        )?;
691        self.state = DebugSessionState::Running;
692        Ok(body)
693    }
694
695    pub fn pause(&mut self, thread_id: i64) -> DebugResult<Value> {
696        self.client.request(
697            "pause",
698            json!({"threadId": positive_id(thread_id, "thread")?}),
699            self.timeout,
700        )
701    }
702
703    pub fn next(&mut self, thread_id: i64) -> DebugResult<Value> {
704        self.step("next", thread_id)
705    }
706
707    pub fn step_in(&mut self, thread_id: i64) -> DebugResult<Value> {
708        self.step("stepIn", thread_id)
709    }
710
711    pub fn step_out(&mut self, thread_id: i64) -> DebugResult<Value> {
712        self.step("stepOut", thread_id)
713    }
714
715    fn step(&mut self, command: &str, thread_id: i64) -> DebugResult<Value> {
716        let body = self.client.request(
717            command,
718            json!({"threadId": positive_id(thread_id, "thread")?}),
719            self.timeout,
720        )?;
721        self.state = DebugSessionState::Running;
722        Ok(body)
723    }
724
725    pub fn threads(&mut self) -> DebugResult<Value> {
726        self.client.request("threads", json!({}), self.timeout)
727    }
728
729    pub fn stack_trace(&mut self, thread_id: i64) -> DebugResult<Value> {
730        self.client.request(
731            "stackTrace",
732            json!({"threadId": positive_id(thread_id, "thread")?}),
733            self.timeout,
734        )
735    }
736
737    pub fn scopes(&mut self, frame_id: i64) -> DebugResult<Value> {
738        self.client.request(
739            "scopes",
740            json!({"frameId": positive_id(frame_id, "frame")?}),
741            self.timeout,
742        )
743    }
744
745    pub fn variables(&mut self, variables_reference: i64) -> DebugResult<Value> {
746        self.client.request(
747            "variables",
748            json!({"variablesReference": positive_id(variables_reference, "variables reference")?}),
749            self.timeout,
750        )
751    }
752
753    pub fn evaluate(
754        &mut self,
755        expression: &str,
756        frame_id: Option<i64>,
757        context: &str,
758    ) -> DebugResult<Value> {
759        if expression.is_empty() || expression.len() > 64 * 1024 {
760            return Err(DebugError::InvalidInput(
761                "debug evaluation expression must contain 1..=65536 bytes".into(),
762            ));
763        }
764        let mut arguments = json!({"expression": expression, "context": context});
765        if let Some(frame_id) = frame_id {
766            arguments["frameId"] = json!(positive_id(frame_id, "frame")?);
767        }
768        let result = self.client.request("evaluate", arguments, self.timeout)?;
769        if context == "watch" && !self.watches.iter().any(|watch| watch == expression) {
770            if self.watches.len() == 128 {
771                self.watches.remove(0);
772            }
773            self.watches.push(expression.to_string());
774        }
775        Ok(result)
776    }
777
778    pub fn poll_events(&mut self) -> DebugResult<Vec<DebugEvent>> {
779        let events = self.client.poll_events()?;
780        for event in &events {
781            match event.event.as_str() {
782                "stopped" => self.state = DebugSessionState::Stopped,
783                "continued" => self.state = DebugSessionState::Running,
784                "terminated" | "exited" => self.state = DebugSessionState::Terminated,
785                _ => {}
786            }
787            if self.events.len() == 256 {
788                self.events.pop_front();
789            }
790            self.events.push_back(event.clone());
791        }
792        Ok(events)
793    }
794
795    pub fn debuggee_processes(&mut self) -> DebugResult<Vec<ProcessSnapshot>> {
796        self.client.debuggee_processes()
797    }
798
799    pub fn snapshot(&mut self) -> DebugResult<DebuggerSnapshot> {
800        Ok(DebuggerSnapshot {
801            state: self.state,
802            adapter_process_id: self.client.process_id(),
803            capabilities: self.capabilities.clone(),
804            breakpoints: self.breakpoints.clone(),
805            watches: self.watches.clone(),
806            events: self.events.iter().cloned().collect(),
807            debuggee_processes: self.client.debuggee_processes()?,
808        })
809    }
810
811    pub fn disconnect(&mut self, terminate_debuggee: bool) -> DebugResult<Value> {
812        let result = self.client.request(
813            "disconnect",
814            json!({"terminateDebuggee": terminate_debuggee}),
815            self.timeout,
816        );
817        self.state = DebugSessionState::Terminated;
818        result
819    }
820
821    pub fn terminate(&mut self, restart: bool) -> DebugResult<Value> {
822        let result = self
823            .client
824            .request("terminate", json!({"restart": restart}), self.timeout);
825        self.state = if restart {
826            DebugSessionState::Starting
827        } else {
828            DebugSessionState::Terminated
829        };
830        result
831    }
832
833    pub fn shutdown(&mut self) -> DebugResult<()> {
834        self.state = DebugSessionState::Terminated;
835        self.client.shutdown()
836    }
837}
838
839fn positive_id(value: i64, description: &str) -> DebugResult<i64> {
840    (value > 0).then_some(value).ok_or_else(|| {
841        DebugError::InvalidInput(format!("{description} ID must be a positive integer"))
842    })
843}
844
845fn push_pending(pending: &mut VecDeque<Value>, message: Value) -> DebugResult<()> {
846    if pending.len() == MAX_PENDING_MESSAGES {
847        return Err(DebugError::Protocol(format!(
848            "debug adapter exceeded the {MAX_PENDING_MESSAGES} pending message limit"
849        )));
850    }
851    pending.push_back(message);
852    Ok(())
853}
854
855fn take_response(pending: &mut VecDeque<Value>, sequence: u64) -> Option<Value> {
856    let position = pending
857        .iter()
858        .position(|message| is_response_for(message, sequence))?;
859    pending.remove(position)
860}
861
862fn is_response_for(message: &Value, sequence: u64) -> bool {
863    message.get("type").and_then(Value::as_str) == Some("response")
864        && message.get("request_seq").and_then(Value::as_u64) == Some(sequence)
865}
866
867fn response_body(message: Value, command: &str) -> DebugResult<Value> {
868    if message.get("success").and_then(Value::as_bool) != Some(true) {
869        let detail = message
870            .get("message")
871            .and_then(Value::as_str)
872            .unwrap_or("adapter returned an unsuccessful response");
873        return Err(DebugError::Adapter(format!("{command}: {detail}")));
874    }
875    Ok(message.get("body").cloned().unwrap_or(Value::Null))
876}
877
878fn read_dap_message(reader: &mut impl BufRead) -> DebugResult<Option<Value>> {
879    let mut content_length = None;
880    let mut header_bytes = 0usize;
881    loop {
882        let mut line = String::new();
883        let read = reader.read_line(&mut line)?;
884        if read == 0 {
885            return if header_bytes == 0 {
886                Ok(None)
887            } else {
888                Err(DebugError::Protocol("truncated DAP header".into()))
889            };
890        }
891        header_bytes = header_bytes
892            .checked_add(read)
893            .ok_or_else(|| DebugError::Protocol("DAP header length overflowed".into()))?;
894        if header_bytes > MAX_DAP_HEADER_BYTES {
895            return Err(DebugError::Protocol(format!(
896                "DAP header exceeds {MAX_DAP_HEADER_BYTES} bytes"
897            )));
898        }
899        if line == "\r\n" || line == "\n" {
900            break;
901        }
902        if let Some((name, value)) = line.trim().split_once(':')
903            && name.eq_ignore_ascii_case("Content-Length")
904        {
905            content_length =
906                Some(value.trim().parse::<usize>().map_err(|_| {
907                    DebugError::Protocol("invalid DAP Content-Length header".into())
908                })?);
909        }
910    }
911    let content_length = content_length
912        .ok_or_else(|| DebugError::Protocol("DAP message has no Content-Length header".into()))?;
913    if content_length == 0 || content_length > MAX_DAP_MESSAGE_BYTES {
914        return Err(DebugError::Protocol(format!(
915            "DAP message length must be 1..={MAX_DAP_MESSAGE_BYTES} bytes"
916        )));
917    }
918    let mut body = vec![0; content_length];
919    reader.read_exact(&mut body)?;
920    serde_json::from_slice(&body)
921        .map_err(|error| DebugError::Protocol(format!("invalid DAP JSON: {error}")))
922}
923
924fn write_dap_message(writer: &mut impl Write, message: &Value) -> DebugResult<()> {
925    let body = serde_json::to_vec(message)
926        .map_err(|error| DebugError::Protocol(format!("could not encode DAP JSON: {error}")))?;
927    if body.is_empty() || body.len() > MAX_DAP_MESSAGE_BYTES {
928        return Err(DebugError::Protocol(format!(
929            "DAP message length must be 1..={MAX_DAP_MESSAGE_BYTES} bytes"
930        )));
931    }
932    write!(writer, "Content-Length: {}\r\n\r\n", body.len())?;
933    writer.write_all(&body)?;
934    writer.flush()?;
935    Ok(())
936}
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941    use std::io::Cursor;
942
943    const REVERSE_ADAPTER: &str = r#"
944import json, sys
945
946def read_message():
947    length = None
948    while True:
949        line = sys.stdin.buffer.readline()
950        if not line:
951            return None
952        if line in (b'\r\n', b'\n'):
953            break
954        name, value = line.decode().strip().split(':', 1)
955        if name.lower() == 'content-length':
956            length = int(value)
957    return json.loads(sys.stdin.buffer.read(length))
958
959def send(message):
960    body = json.dumps(message, separators=(',', ':')).encode()
961    sys.stdout.buffer.write(('Content-Length: %d\r\n\r\n' % len(body)).encode() + body)
962    sys.stdout.buffer.flush()
963
964request = read_message()
965send({'seq': 1, 'type': 'response', 'request_seq': request['seq'], 'success': True,
966      'command': request['command'], 'body': {}})
967request = read_message()
968send({'seq': 2, 'type': 'request', 'command': 'runInTerminal', 'arguments': {
969    'kind': 'integrated', 'cwd': sys.argv[1],
970    'args': [sys.executable, '-c', 'import time; print(\"glass-debuggee-ready\", flush=True); time.sleep(30)'],
971    'env': {'GLASS_DAP_TEST': '1'}}})
972terminal = read_message()
973if terminal.get('success') is not True or not terminal.get('body', {}).get('processId'):
974    raise SystemExit(41)
975send({'seq': 3, 'type': 'request', 'command': 'startDebugging', 'arguments': {}})
976unsupported = read_message()
977if unsupported.get('success') is not False:
978    raise SystemExit(42)
979send({'seq': 4, 'type': 'response', 'request_seq': request['seq'], 'success': True,
980      'command': request['command'], 'body': {'reverseRequestsHandled': True}})
981for request in iter(read_message, None):
982    if request.get('command') == 'disconnect':
983        raise SystemExit(0)
984    send({'seq': 5, 'type': 'response', 'request_seq': request['seq'], 'success': True,
985          'command': request['command'], 'body': {}})
986"#;
987
988    const TCP_ADAPTER: &str = r#"
989import json, socket, sys
990server = socket.socket()
991server.bind(('127.0.0.1', int(sys.argv[-1])))
992server.listen(1)
993stream, _ = server.accept()
994reader = stream.makefile('rb')
995writer = stream.makefile('wb')
996length = None
997while True:
998    line = reader.readline()
999    if line in (b'\r\n', b'\n'):
1000        break
1001    name, value = line.decode().strip().split(':', 1)
1002    if name.lower() == 'content-length':
1003        length = int(value)
1004request = json.loads(reader.read(length))
1005body = json.dumps({'seq': 1, 'type': 'response', 'request_seq': request['seq'],
1006                   'success': True, 'command': request['command'],
1007                   'body': {'transport': 'tcp'}}).encode()
1008writer.write(('Content-Length: %d\r\n\r\n' % len(body)).encode() + body)
1009writer.flush()
1010"#;
1011
1012    #[test]
1013    fn dap_framing_round_trips_json() {
1014        let message = json!({"seq": 7, "type": "event", "event": "stopped"});
1015        let mut encoded = Vec::new();
1016        write_dap_message(&mut encoded, &message).unwrap();
1017        assert_eq!(
1018            read_dap_message(&mut BufReader::new(Cursor::new(encoded))).unwrap(),
1019            Some(message)
1020        );
1021    }
1022
1023    #[test]
1024    fn dap_framing_rejects_missing_and_oversized_lengths() {
1025        let missing = b"X-Test: true\r\n\r\n{}";
1026        assert!(read_dap_message(&mut BufReader::new(&missing[..])).is_err());
1027        let oversized = format!("Content-Length: {}\r\n\r\n", MAX_DAP_MESSAGE_BYTES + 1);
1028        assert!(read_dap_message(&mut BufReader::new(oversized.as_bytes())).is_err());
1029    }
1030
1031    #[test]
1032    fn unsuccessful_adapter_response_is_typed() {
1033        let error = response_body(
1034            json!({
1035                "type": "response",
1036                "request_seq": 1,
1037                "success": false,
1038                "message": "breakpoint refused"
1039            }),
1040            "setBreakpoints",
1041        )
1042        .unwrap_err();
1043        assert!(error.to_string().contains("breakpoint refused"));
1044    }
1045
1046    #[test]
1047    fn debugger_ids_and_breakpoint_limits_fail_closed() {
1048        assert!(positive_id(0, "thread").is_err());
1049        assert!(positive_id(-1, "frame").is_err());
1050        assert_eq!(positive_id(1, "thread").unwrap(), 1);
1051
1052        let breakpoint = SourceBreakpoint {
1053            line: 42,
1054            condition: Some("inventory == 0".into()),
1055            hit_condition: None,
1056            log_message: Some("inventory={inventory}".into()),
1057        };
1058        let encoded = serde_json::to_value(breakpoint).unwrap();
1059        assert_eq!(encoded["line"], 42);
1060        assert_eq!(encoded["condition"], "inventory == 0");
1061        assert!(encoded.get("hitCondition").is_none());
1062    }
1063
1064    #[test]
1065    fn reverse_requests_are_supervised_bounded_and_observable() {
1066        let Some((root, config)) = python_adapter(REVERSE_ADAPTER) else {
1067            return;
1068        };
1069        let mut client = DapClient::spawn(&root, &config).unwrap();
1070        client
1071            .request("initialize", json!({}), Duration::from_secs(15))
1072            .unwrap();
1073        let response = client
1074            .request("exercise", json!({}), Duration::from_secs(15))
1075            .unwrap();
1076        assert_eq!(response["reverseRequestsHandled"], true);
1077
1078        let deadline = Instant::now() + Duration::from_secs(10);
1079        let processes = loop {
1080            let processes = client.debuggee_processes().unwrap();
1081            if processes
1082                .first()
1083                .is_some_and(|process| process.output.contains("glass-debuggee-ready"))
1084            {
1085                break processes;
1086            }
1087            assert!(
1088                Instant::now() < deadline,
1089                "debuggee output was not observed"
1090            );
1091            std::thread::sleep(Duration::from_millis(10));
1092        };
1093        assert!(processes[0].pty);
1094        let process_id = processes[0].pid.unwrap();
1095        let events = client.poll_events().unwrap();
1096        assert_eq!(events.len(), 2);
1097        assert!(events[0].body["success"].as_bool().unwrap());
1098        assert!(!events[1].body["success"].as_bool().unwrap());
1099        drop(client);
1100        assert_process_exits(process_id);
1101        let _ = std::fs::remove_dir_all(root);
1102    }
1103
1104    #[test]
1105    fn adapter_crash_and_timeout_are_typed_failures() {
1106        let Some((root, crash)) = python_adapter("raise SystemExit(7)") else {
1107            return;
1108        };
1109        let mut client = DapClient::spawn(&root, &crash).unwrap();
1110        let error = client
1111            .request("initialize", json!({}), Duration::from_secs(2))
1112            .unwrap_err();
1113        assert!(
1114            matches!(
1115                &error,
1116                DebugError::Io(_) | DebugError::Protocol(_) | DebugError::Timeout(_)
1117            ),
1118            "unexpected adapter crash error: {error}"
1119        );
1120        drop(client);
1121
1122        let (timeout_root, timeout) = python_adapter("import time; time.sleep(30)").unwrap();
1123        let mut client = DapClient::spawn(&timeout_root, &timeout).unwrap();
1124        let error = client
1125            .request("initialize", json!({}), Duration::from_millis(50))
1126            .unwrap_err();
1127        assert!(matches!(error, DebugError::Timeout(_)));
1128        drop(client);
1129        let _ = std::fs::remove_dir_all(root);
1130        let _ = std::fs::remove_dir_all(timeout_root);
1131    }
1132
1133    #[test]
1134    fn loopback_tcp_adapter_transport_is_owned_and_framed() {
1135        let Some((root, mut config)) = python_adapter(TCP_ADAPTER) else {
1136            return;
1137        };
1138        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1139        let address = listener.local_addr().unwrap();
1140        drop(listener);
1141        config.arguments.push(address.port().to_string());
1142        config = config.with_tcp(address, Duration::from_secs(15));
1143        let mut client = DapClient::spawn(&root, &config).unwrap();
1144        let body = client
1145            .request("initialize", json!({}), Duration::from_secs(10))
1146            .unwrap();
1147        assert_eq!(body["transport"], "tcp");
1148        drop(client);
1149        let _ = std::fs::remove_dir_all(root);
1150    }
1151
1152    #[test]
1153    fn real_lldb_adapter_supports_breakpoint_stack_and_continue() {
1154        let Some(adapter) = std::env::var_os("GLASS_LLDB_DAP") else {
1155            return;
1156        };
1157        let root = adapter_test_root("lldb");
1158        std::fs::create_dir_all(&root).unwrap();
1159        let source = root.join("main.rs");
1160        let program = root.join(if cfg!(windows) {
1161            "fixture.exe"
1162        } else {
1163            "fixture"
1164        });
1165        std::fs::write(
1166            &source,
1167            "fn main() {\n    let value = 41;\n    let answer = value + 1;\n    println!(\"{answer}\");\n}\n",
1168        )
1169        .unwrap();
1170        let status = std::process::Command::new("rustc")
1171            .args(["-C", "debuginfo=2", "-C", "opt-level=0"])
1172            .arg(&source)
1173            .arg("-o")
1174            .arg(&program)
1175            .status()
1176            .unwrap();
1177        assert!(status.success());
1178        let config = DebugAdapterConfig::new(PathBuf::from(adapter), []);
1179        let mut debugger =
1180            DebuggerSession::start(&root, &config, "Glass LLDB E2E", Duration::from_secs(20))
1181                .unwrap();
1182        debugger
1183            .launch(json!({"program":program,"cwd":root,"stopOnEntry":false}))
1184            .unwrap();
1185        let breakpoints = debugger.set_breakpoints(&source, &[3]).unwrap();
1186        assert!(
1187            breakpoints["breakpoints"]
1188                .as_array()
1189                .is_some_and(|items| !items.is_empty())
1190        );
1191        debugger.configuration_done().unwrap();
1192        let stopped = wait_for_debug_event(&mut debugger, "stopped", Duration::from_secs(20));
1193        let thread_id = stopped["threadId"].as_i64().unwrap();
1194        let stack = wait_for_stack_trace(&mut debugger, thread_id, Duration::from_secs(20));
1195        assert!(
1196            stack["stackFrames"]
1197                .as_array()
1198                .is_some_and(|items| !items.is_empty())
1199        );
1200        debugger.continue_thread(thread_id).unwrap();
1201        wait_for_debug_end(&mut debugger, Duration::from_secs(20));
1202        debugger.shutdown().unwrap();
1203        let _ = std::fs::remove_dir_all(root);
1204    }
1205
1206    #[test]
1207    fn real_delve_adapter_supports_tcp_breakpoint_stack_and_continue() {
1208        let Some(adapter) = std::env::var_os("GLASS_DELVE") else {
1209            return;
1210        };
1211        let root = adapter_test_root("delve");
1212        std::fs::create_dir_all(&root).unwrap();
1213        let source = root.join("main.go");
1214        std::fs::write(
1215            &source,
1216            "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvalue := 41\n\tfmt.Println(value + 1)\n}\n",
1217        )
1218        .unwrap();
1219        std::fs::write(
1220            root.join("go.mod"),
1221            "module glass.test/debugger\n\ngo 1.22\n",
1222        )
1223        .unwrap();
1224        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1225        let address = listener.local_addr().unwrap();
1226        drop(listener);
1227        let config = DebugAdapterConfig::new(
1228            PathBuf::from(adapter),
1229            ["dap".into(), format!("--listen={address}")],
1230        )
1231        .with_tcp(address, Duration::from_secs(10));
1232        let mut debugger =
1233            DebuggerSession::start(&root, &config, "Glass Delve E2E", Duration::from_secs(30))
1234                .unwrap();
1235        debugger
1236            .launch(json!({"mode":"debug","program":root,"cwd":root,"stopOnEntry":false}))
1237            .unwrap();
1238        let breakpoints = debugger.set_breakpoints(&source, &[7]).unwrap();
1239        assert!(
1240            breakpoints["breakpoints"]
1241                .as_array()
1242                .is_some_and(|items| !items.is_empty())
1243        );
1244        debugger.configuration_done().unwrap();
1245        let stopped = wait_for_debug_event(&mut debugger, "stopped", Duration::from_secs(30));
1246        let thread_id = stopped["threadId"].as_i64().unwrap();
1247        let stack = wait_for_stack_trace(&mut debugger, thread_id, Duration::from_secs(30));
1248        assert!(
1249            stack["stackFrames"]
1250                .as_array()
1251                .is_some_and(|items| !items.is_empty())
1252        );
1253        debugger.continue_thread(thread_id).unwrap();
1254        wait_for_debug_end(&mut debugger, Duration::from_secs(30));
1255        debugger.shutdown().unwrap();
1256        let _ = std::fs::remove_dir_all(root);
1257    }
1258
1259    #[test]
1260    fn real_debugpy_adapter_supports_breakpoint_state_and_continue() {
1261        let Some(python) = std::env::var_os("GLASS_DEBUGPY_PYTHON") else {
1262            return;
1263        };
1264        let root =
1265            std::env::temp_dir().join(format!("glass-debugpy-fixture-{}", std::process::id()));
1266        let _ = std::fs::remove_dir_all(&root);
1267        std::fs::create_dir_all(&root).unwrap();
1268        let program = root.join("program.py");
1269        std::fs::write(&program, "value = 41\nanswer = value + 1\nprint(answer)\n").unwrap();
1270        let config = DebugAdapterConfig::new(
1271            PathBuf::from(python),
1272            ["-m".to_string(), "debugpy.adapter".to_string()],
1273        );
1274        let mut debugger =
1275            DebuggerSession::start(&root, &config, "Glass DebugPy E2E", Duration::from_secs(15))
1276                .unwrap();
1277        debugger
1278            .launch(json!({
1279                "name":"Glass debugpy fixture",
1280                "type":"python",
1281                "request":"launch",
1282                "program":program,
1283                "console":"internalConsole",
1284                "justMyCode":false
1285            }))
1286            .unwrap();
1287        let breakpoints = debugger.set_breakpoints(&program, &[2]).unwrap();
1288        assert_eq!(breakpoints["breakpoints"][0]["verified"], true);
1289        debugger.configuration_done().unwrap();
1290        let stopped = wait_for_debug_event(&mut debugger, "stopped", Duration::from_secs(15));
1291        let thread_id = stopped["threadId"].as_i64().unwrap();
1292        let threads = debugger.threads().unwrap();
1293        assert!(
1294            threads["threads"]
1295                .as_array()
1296                .is_some_and(|items| !items.is_empty())
1297        );
1298        let stack = wait_for_stack_trace(&mut debugger, thread_id, Duration::from_secs(15));
1299        let frame_id = stack["stackFrames"][0]["id"].as_i64().unwrap();
1300        let scopes = debugger.scopes(frame_id).unwrap();
1301        let variables_reference = scopes["scopes"][0]["variablesReference"].as_i64().unwrap();
1302        let variables = debugger.variables(variables_reference).unwrap();
1303        assert!(
1304            variables["variables"]
1305                .as_array()
1306                .is_some_and(|items| { items.iter().any(|variable| variable["name"] == "value") })
1307        );
1308        let evaluated = debugger
1309            .evaluate("value + 1", Some(frame_id), "watch")
1310            .unwrap();
1311        assert_eq!(evaluated["result"], "42");
1312        debugger.continue_thread(thread_id).unwrap();
1313        wait_for_debug_end(&mut debugger, Duration::from_secs(15));
1314        debugger.shutdown().unwrap();
1315        let _ = std::fs::remove_dir_all(root);
1316    }
1317
1318    fn wait_for_debug_event(
1319        debugger: &mut DebuggerSession,
1320        expected: &str,
1321        timeout: Duration,
1322    ) -> Value {
1323        let deadline = Instant::now() + timeout;
1324        loop {
1325            for event in debugger.poll_events().unwrap() {
1326                if event.event == expected {
1327                    return event.body;
1328                }
1329            }
1330            assert!(
1331                Instant::now() < deadline,
1332                "timed out waiting for {expected}"
1333            );
1334            std::thread::sleep(Duration::from_millis(10));
1335        }
1336    }
1337
1338    fn wait_for_stack_trace(
1339        debugger: &mut DebuggerSession,
1340        preferred_thread_id: i64,
1341        timeout: Duration,
1342    ) -> Value {
1343        let deadline = Instant::now() + timeout;
1344        loop {
1345            let mut errors = Vec::new();
1346            let mut thread_ids = vec![preferred_thread_id];
1347            if let Ok(threads) = debugger.threads()
1348                && let Some(threads) = threads["threads"].as_array()
1349            {
1350                thread_ids.extend(
1351                    threads
1352                        .iter()
1353                        .filter_map(|thread| thread["id"].as_i64())
1354                        .filter(|thread_id| *thread_id != preferred_thread_id),
1355                );
1356            }
1357            for thread_id in thread_ids {
1358                match debugger.stack_trace(thread_id) {
1359                    Ok(stack)
1360                        if stack["stackFrames"]
1361                            .as_array()
1362                            .is_some_and(|frames| !frames.is_empty()) =>
1363                    {
1364                        return stack;
1365                    }
1366                    Ok(_) => errors.push(format!("thread {thread_id} returned no stack frames")),
1367                    Err(error) => errors.push(error.to_string()),
1368                }
1369            }
1370            let last_error = errors
1371                .last()
1372                .map(String::as_str)
1373                .unwrap_or("adapter returned no stack frames");
1374            assert!(
1375                Instant::now() < deadline,
1376                "timed out waiting for stack trace: {last_error}"
1377            );
1378            std::thread::sleep(Duration::from_millis(25));
1379        }
1380    }
1381
1382    fn wait_for_debug_end(debugger: &mut DebuggerSession, timeout: Duration) -> Value {
1383        let deadline = Instant::now() + timeout;
1384        loop {
1385            for event in debugger.poll_events().unwrap() {
1386                if matches!(event.event.as_str(), "exited" | "terminated") {
1387                    return event.body;
1388                }
1389            }
1390            assert!(Instant::now() < deadline, "timed out waiting for debug end");
1391            std::thread::sleep(Duration::from_millis(10));
1392        }
1393    }
1394
1395    fn python_adapter(script: &str) -> Option<(PathBuf, DebugAdapterConfig)> {
1396        if std::process::Command::new("python3")
1397            .arg("--version")
1398            .output()
1399            .is_err()
1400        {
1401            return None;
1402        }
1403        let root = adapter_test_root("python");
1404        std::fs::create_dir_all(&root).unwrap();
1405        let adapter = root.join("adapter.py");
1406        std::fs::write(&adapter, script).unwrap();
1407        Some((
1408            root.clone(),
1409            DebugAdapterConfig::new(
1410                PathBuf::from("python3"),
1411                [
1412                    "-u".into(),
1413                    adapter.display().to_string(),
1414                    root.display().to_string(),
1415                ],
1416            ),
1417        ))
1418    }
1419
1420    fn adapter_test_root(label: &str) -> PathBuf {
1421        std::env::temp_dir().join(format!(
1422            "glass-dap-{label}-{}-{}",
1423            std::process::id(),
1424            std::time::SystemTime::now()
1425                .duration_since(std::time::UNIX_EPOCH)
1426                .unwrap()
1427                .as_nanos()
1428        ))
1429    }
1430
1431    #[cfg(unix)]
1432    fn assert_process_exits(process_id: u32) {
1433        let deadline = Instant::now() + Duration::from_secs(3);
1434        loop {
1435            let result = unsafe { libc::kill(process_id as i32, 0) };
1436            if result != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) {
1437                return;
1438            }
1439            assert!(
1440                Instant::now() < deadline,
1441                "debuggee process {process_id} survived owner drop"
1442            );
1443            std::thread::sleep(Duration::from_millis(20));
1444        }
1445    }
1446
1447    #[cfg(not(unix))]
1448    fn assert_process_exits(_process_id: u32) {}
1449}