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