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
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
156pub 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
545pub 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(5))
1072 .unwrap();
1073 let response = client
1074 .request("exercise", json!({}), Duration::from_secs(5))
1075 .unwrap();
1076 assert_eq!(response["reverseRequestsHandled"], true);
1077
1078 let deadline = Instant::now() + Duration::from_secs(3);
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!(matches!(error, DebugError::Protocol(_)));
1114 drop(client);
1115
1116 let (timeout_root, timeout) = python_adapter("import time; time.sleep(30)").unwrap();
1117 let mut client = DapClient::spawn(&timeout_root, &timeout).unwrap();
1118 let error = client
1119 .request("initialize", json!({}), Duration::from_millis(50))
1120 .unwrap_err();
1121 assert!(matches!(error, DebugError::Timeout(_)));
1122 drop(client);
1123 let _ = std::fs::remove_dir_all(root);
1124 let _ = std::fs::remove_dir_all(timeout_root);
1125 }
1126
1127 #[test]
1128 fn loopback_tcp_adapter_transport_is_owned_and_framed() {
1129 let Some((root, mut config)) = python_adapter(TCP_ADAPTER) else {
1130 return;
1131 };
1132 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1133 let address = listener.local_addr().unwrap();
1134 drop(listener);
1135 config.arguments.push(address.port().to_string());
1136 config = config.with_tcp(address, Duration::from_secs(3));
1137 let mut client = DapClient::spawn(&root, &config).unwrap();
1138 let body = client
1139 .request("initialize", json!({}), Duration::from_secs(3))
1140 .unwrap();
1141 assert_eq!(body["transport"], "tcp");
1142 drop(client);
1143 let _ = std::fs::remove_dir_all(root);
1144 }
1145
1146 #[test]
1147 fn real_lldb_adapter_supports_breakpoint_stack_and_continue() {
1148 let Some(adapter) = std::env::var_os("GLASS_LLDB_DAP") else {
1149 return;
1150 };
1151 let root = adapter_test_root("lldb");
1152 std::fs::create_dir_all(&root).unwrap();
1153 let source = root.join("main.rs");
1154 let program = root.join(if cfg!(windows) {
1155 "fixture.exe"
1156 } else {
1157 "fixture"
1158 });
1159 std::fs::write(
1160 &source,
1161 "fn main() {\n let value = 41;\n let answer = value + 1;\n println!(\"{answer}\");\n}\n",
1162 )
1163 .unwrap();
1164 let status = std::process::Command::new("rustc")
1165 .args(["-C", "debuginfo=2", "-C", "opt-level=0"])
1166 .arg(&source)
1167 .arg("-o")
1168 .arg(&program)
1169 .status()
1170 .unwrap();
1171 assert!(status.success());
1172 let config = DebugAdapterConfig::new(PathBuf::from(adapter), []);
1173 let mut debugger =
1174 DebuggerSession::start(&root, &config, "Glass LLDB E2E", Duration::from_secs(20))
1175 .unwrap();
1176 debugger
1177 .launch(json!({"program":program,"cwd":root,"stopOnEntry":false}))
1178 .unwrap();
1179 let breakpoints = debugger.set_breakpoints(&source, &[3]).unwrap();
1180 assert!(
1181 breakpoints["breakpoints"]
1182 .as_array()
1183 .is_some_and(|items| !items.is_empty())
1184 );
1185 debugger.configuration_done().unwrap();
1186 let stopped = wait_for_debug_event(&mut debugger, "stopped", Duration::from_secs(20));
1187 let thread_id = stopped["threadId"].as_i64().unwrap();
1188 let stack = wait_for_stack_trace(&mut debugger, thread_id, Duration::from_secs(20));
1189 assert!(
1190 stack["stackFrames"]
1191 .as_array()
1192 .is_some_and(|items| !items.is_empty())
1193 );
1194 debugger.continue_thread(thread_id).unwrap();
1195 wait_for_debug_end(&mut debugger, Duration::from_secs(20));
1196 debugger.shutdown().unwrap();
1197 let _ = std::fs::remove_dir_all(root);
1198 }
1199
1200 #[test]
1201 fn real_delve_adapter_supports_tcp_breakpoint_stack_and_continue() {
1202 let Some(adapter) = std::env::var_os("GLASS_DELVE") else {
1203 return;
1204 };
1205 let root = adapter_test_root("delve");
1206 std::fs::create_dir_all(&root).unwrap();
1207 let source = root.join("main.go");
1208 std::fs::write(
1209 &source,
1210 "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvalue := 41\n\tfmt.Println(value + 1)\n}\n",
1211 )
1212 .unwrap();
1213 std::fs::write(
1214 root.join("go.mod"),
1215 "module glass.test/debugger\n\ngo 1.22\n",
1216 )
1217 .unwrap();
1218 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1219 let address = listener.local_addr().unwrap();
1220 drop(listener);
1221 let config = DebugAdapterConfig::new(
1222 PathBuf::from(adapter),
1223 ["dap".into(), format!("--listen={address}")],
1224 )
1225 .with_tcp(address, Duration::from_secs(10));
1226 let mut debugger =
1227 DebuggerSession::start(&root, &config, "Glass Delve E2E", Duration::from_secs(30))
1228 .unwrap();
1229 debugger
1230 .launch(json!({"mode":"debug","program":root,"cwd":root,"stopOnEntry":false}))
1231 .unwrap();
1232 let breakpoints = debugger.set_breakpoints(&source, &[7]).unwrap();
1233 assert!(
1234 breakpoints["breakpoints"]
1235 .as_array()
1236 .is_some_and(|items| !items.is_empty())
1237 );
1238 debugger.configuration_done().unwrap();
1239 let stopped = wait_for_debug_event(&mut debugger, "stopped", Duration::from_secs(30));
1240 let thread_id = stopped["threadId"].as_i64().unwrap();
1241 let stack = wait_for_stack_trace(&mut debugger, thread_id, Duration::from_secs(30));
1242 assert!(
1243 stack["stackFrames"]
1244 .as_array()
1245 .is_some_and(|items| !items.is_empty())
1246 );
1247 debugger.continue_thread(thread_id).unwrap();
1248 wait_for_debug_end(&mut debugger, Duration::from_secs(30));
1249 debugger.shutdown().unwrap();
1250 let _ = std::fs::remove_dir_all(root);
1251 }
1252
1253 #[test]
1254 fn real_debugpy_adapter_supports_breakpoint_state_and_continue() {
1255 let Some(python) = std::env::var_os("GLASS_DEBUGPY_PYTHON") else {
1256 return;
1257 };
1258 let root =
1259 std::env::temp_dir().join(format!("glass-debugpy-fixture-{}", std::process::id()));
1260 let _ = std::fs::remove_dir_all(&root);
1261 std::fs::create_dir_all(&root).unwrap();
1262 let program = root.join("program.py");
1263 std::fs::write(&program, "value = 41\nanswer = value + 1\nprint(answer)\n").unwrap();
1264 let config = DebugAdapterConfig::new(
1265 PathBuf::from(python),
1266 ["-m".to_string(), "debugpy.adapter".to_string()],
1267 );
1268 let mut debugger =
1269 DebuggerSession::start(&root, &config, "Glass DebugPy E2E", Duration::from_secs(15))
1270 .unwrap();
1271 debugger
1272 .launch(json!({
1273 "name":"Glass debugpy fixture",
1274 "type":"python",
1275 "request":"launch",
1276 "program":program,
1277 "console":"internalConsole",
1278 "justMyCode":false
1279 }))
1280 .unwrap();
1281 let breakpoints = debugger.set_breakpoints(&program, &[2]).unwrap();
1282 assert_eq!(breakpoints["breakpoints"][0]["verified"], true);
1283 debugger.configuration_done().unwrap();
1284 let stopped = wait_for_debug_event(&mut debugger, "stopped", Duration::from_secs(15));
1285 let thread_id = stopped["threadId"].as_i64().unwrap();
1286 let threads = debugger.threads().unwrap();
1287 assert!(
1288 threads["threads"]
1289 .as_array()
1290 .is_some_and(|items| !items.is_empty())
1291 );
1292 let stack = wait_for_stack_trace(&mut debugger, thread_id, Duration::from_secs(15));
1293 let frame_id = stack["stackFrames"][0]["id"].as_i64().unwrap();
1294 let scopes = debugger.scopes(frame_id).unwrap();
1295 let variables_reference = scopes["scopes"][0]["variablesReference"].as_i64().unwrap();
1296 let variables = debugger.variables(variables_reference).unwrap();
1297 assert!(
1298 variables["variables"]
1299 .as_array()
1300 .is_some_and(|items| { items.iter().any(|variable| variable["name"] == "value") })
1301 );
1302 let evaluated = debugger
1303 .evaluate("value + 1", Some(frame_id), "watch")
1304 .unwrap();
1305 assert_eq!(evaluated["result"], "42");
1306 debugger.continue_thread(thread_id).unwrap();
1307 wait_for_debug_end(&mut debugger, Duration::from_secs(15));
1308 debugger.shutdown().unwrap();
1309 let _ = std::fs::remove_dir_all(root);
1310 }
1311
1312 fn wait_for_debug_event(
1313 debugger: &mut DebuggerSession,
1314 expected: &str,
1315 timeout: Duration,
1316 ) -> Value {
1317 let deadline = Instant::now() + timeout;
1318 loop {
1319 for event in debugger.poll_events().unwrap() {
1320 if event.event == expected {
1321 return event.body;
1322 }
1323 }
1324 assert!(
1325 Instant::now() < deadline,
1326 "timed out waiting for {expected}"
1327 );
1328 std::thread::sleep(Duration::from_millis(10));
1329 }
1330 }
1331
1332 fn wait_for_stack_trace(
1333 debugger: &mut DebuggerSession,
1334 preferred_thread_id: i64,
1335 timeout: Duration,
1336 ) -> Value {
1337 let deadline = Instant::now() + timeout;
1338 loop {
1339 let mut errors = Vec::new();
1340 let mut thread_ids = vec![preferred_thread_id];
1341 if let Ok(threads) = debugger.threads()
1342 && let Some(threads) = threads["threads"].as_array()
1343 {
1344 thread_ids.extend(
1345 threads
1346 .iter()
1347 .filter_map(|thread| thread["id"].as_i64())
1348 .filter(|thread_id| *thread_id != preferred_thread_id),
1349 );
1350 }
1351 for thread_id in thread_ids {
1352 match debugger.stack_trace(thread_id) {
1353 Ok(stack)
1354 if stack["stackFrames"]
1355 .as_array()
1356 .is_some_and(|frames| !frames.is_empty()) =>
1357 {
1358 return stack;
1359 }
1360 Ok(_) => errors.push(format!("thread {thread_id} returned no stack frames")),
1361 Err(error) => errors.push(error.to_string()),
1362 }
1363 }
1364 let last_error = errors
1365 .last()
1366 .map(String::as_str)
1367 .unwrap_or("adapter returned no stack frames");
1368 assert!(
1369 Instant::now() < deadline,
1370 "timed out waiting for stack trace: {last_error}"
1371 );
1372 std::thread::sleep(Duration::from_millis(25));
1373 }
1374 }
1375
1376 fn wait_for_debug_end(debugger: &mut DebuggerSession, timeout: Duration) -> Value {
1377 let deadline = Instant::now() + timeout;
1378 loop {
1379 for event in debugger.poll_events().unwrap() {
1380 if matches!(event.event.as_str(), "exited" | "terminated") {
1381 return event.body;
1382 }
1383 }
1384 assert!(Instant::now() < deadline, "timed out waiting for debug end");
1385 std::thread::sleep(Duration::from_millis(10));
1386 }
1387 }
1388
1389 fn python_adapter(script: &str) -> Option<(PathBuf, DebugAdapterConfig)> {
1390 if std::process::Command::new("python3")
1391 .arg("--version")
1392 .output()
1393 .is_err()
1394 {
1395 return None;
1396 }
1397 let root = adapter_test_root("python");
1398 std::fs::create_dir_all(&root).unwrap();
1399 let adapter = root.join("adapter.py");
1400 std::fs::write(&adapter, script).unwrap();
1401 Some((
1402 root.clone(),
1403 DebugAdapterConfig::new(
1404 PathBuf::from("python3"),
1405 [
1406 "-u".into(),
1407 adapter.display().to_string(),
1408 root.display().to_string(),
1409 ],
1410 ),
1411 ))
1412 }
1413
1414 fn adapter_test_root(label: &str) -> PathBuf {
1415 std::env::temp_dir().join(format!(
1416 "glass-dap-{label}-{}-{}",
1417 std::process::id(),
1418 std::time::SystemTime::now()
1419 .duration_since(std::time::UNIX_EPOCH)
1420 .unwrap()
1421 .as_nanos()
1422 ))
1423 }
1424
1425 #[cfg(unix)]
1426 fn assert_process_exits(process_id: u32) {
1427 let deadline = Instant::now() + Duration::from_secs(3);
1428 loop {
1429 let result = unsafe { libc::kill(process_id as i32, 0) };
1430 if result != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) {
1431 return;
1432 }
1433 assert!(
1434 Instant::now() < deadline,
1435 "debuggee process {process_id} survived owner drop"
1436 );
1437 std::thread::sleep(Duration::from_millis(20));
1438 }
1439 }
1440
1441 #[cfg(not(unix))]
1442 fn assert_process_exits(_process_id: u32) {}
1443}