detrix-rs 1.1.0

Detrix client library for debug-on-demand observability in Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! LLDB process lifecycle management.

use std::io::{BufRead, BufReader};
use std::net::TcpStream;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use tracing::{debug, trace, warn};

use crate::error::{Error, Result, ResultExt};

/// Maximum number of port allocation retries.
const MAX_PORT_RETRIES: u32 = 3;

/// Information about a running lldb-dap process.
#[derive(Debug)]
pub struct LldbProcess {
    /// Child process handle.
    pub child: Child,

    /// Host the DAP server is listening on.
    #[allow(dead_code)]
    pub host: String,

    /// Port the DAP server is listening on.
    pub port: u16,
}

/// Manager for lldb-dap process lifecycle.
pub struct LldbManager {
    /// Path to lldb-dap binary.
    lldb_dap_path: PathBuf,

    /// Timeout for lldb-dap to start.
    timeout: Duration,
}

impl LldbManager {
    /// Create a new LLDB manager.
    pub fn new(lldb_dap_path: PathBuf, timeout: Duration) -> Self {
        Self {
            lldb_dap_path,
            timeout,
        }
    }

    /// Spawn lldb-dap and attach to the current process.
    ///
    /// When port is 0, an ephemeral port is allocated. Due to a TOCTOU race
    /// (the port may be taken between allocation and lldb-dap startup), this
    /// operation is retried up to MAX_PORT_RETRIES times.
    pub fn spawn_and_attach(&self, host: &str, port: u16) -> Result<LldbProcess> {
        // If port is specified (non-zero), no retries needed
        if port != 0 {
            return self.spawn_lldb(host, port);
        }

        // Port 0: ephemeral port allocation with retry logic
        let mut last_err = None;
        for attempt in 0..MAX_PORT_RETRIES {
            // Allocate an ephemeral port
            let actual_port = allocate_port(host)?;
            debug!(
                "Attempt {}: allocated ephemeral port {}",
                attempt + 1,
                actual_port
            );

            match self.spawn_lldb(host, actual_port) {
                Ok(process) => return Ok(process),
                Err(e) => {
                    if is_port_bind_error(&e) {
                        warn!("Port {} taken (TOCTOU race), retrying...", actual_port);
                        last_err = Some(e);
                        continue;
                    }
                    return Err(e);
                }
            }
        }

        Err(last_err
            .unwrap_or_else(|| Error::LldbStartFailed("failed after max port retries".to_string())))
    }

    /// Spawn lldb-dap on the specified port.
    ///
    /// IMPORTANT: We do NOT send the DAP attach request here! The Detrix daemon
    /// (a separate process) will connect to lldb-dap and send the attach request.
    /// If we tried to send attach from within this process, lldb-dap would use
    /// ptrace to stop us, causing a deadlock.
    fn spawn_lldb(&self, host: &str, port: u16) -> Result<LldbProcess> {
        // Build command:
        // lldb-dap --connection listen://host:port
        let listen_addr = format!("listen://{}:{}", host, port);

        debug!(
            "Starting lldb-dap: {:?} --connection {}",
            self.lldb_dap_path, listen_addr
        );

        let mut child = Command::new(&self.lldb_dap_path)
            .args(["--connection", &listen_addr])
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .lldb("failed to start process")?;

        // Wait for lldb-dap to accept connections
        if let Err(e) = self.wait_for_ready(host, port, &mut child) {
            // Kill process if startup failed
            let _ = self.kill_process(&mut child);
            return Err(e);
        }

        debug!(
            "lldb-dap ready on {}:{}, daemon will attach to PID {}",
            host,
            port,
            std::process::id()
        );

        // NOTE: We do NOT send DAP initialize/attach here.
        // The Detrix daemon will connect and handle the DAP protocol.
        // This avoids a deadlock where lldb-dap would stop this process
        // via ptrace while we're waiting for its response.

        Ok(LldbProcess {
            child,
            host: host.to_string(),
            port,
        })
    }

    /// Wait for lldb-dap to accept connections.
    fn wait_for_ready(&self, host: &str, port: u16, child: &mut Child) -> Result<()> {
        let deadline = Instant::now() + self.timeout;
        let check_interval = Duration::from_millis(100);

        while Instant::now() < deadline {
            // Check if process died
            if let Ok(Some(status)) = child.try_wait() {
                // Read stderr for error message
                let stderr = child
                    .stderr
                    .take()
                    .map(|s| {
                        BufReader::new(s)
                            .lines()
                            .take(10)
                            .filter_map(|l| l.ok())
                            .collect::<Vec<_>>()
                            .join("\n")
                    })
                    .unwrap_or_default();

                return Err(Error::LldbStartFailed(format!(
                    "lldb-dap exited with status {}: {}",
                    status, stderr
                )));
            }

            // Try to connect
            let addr = format!("{}:{}", host, port);
            if TcpStream::connect_timeout(&addr.parse().lldb("invalid address")?, check_interval)
                .is_ok()
            {
                trace!("lldb-dap accepting connections on {}", addr);
                return Ok(());
            }

            std::thread::sleep(check_interval);
        }

        Err(Error::Timeout(format!(
            "lldb-dap did not become ready within {:?}",
            self.timeout
        )))
    }

    /// Send DAP initialize and attach requests.
    ///
    /// NOTE: This is kept for potential standalone testing, but is NOT used
    /// in normal operation. The Detrix daemon handles the DAP protocol.
    #[allow(dead_code)]
    fn send_attach_request(&self, host: &str, port: u16, pid: u32) -> Result<()> {
        let addr = format!("{}:{}", host, port);
        debug!("Connecting to lldb-dap at {}", addr);
        let mut stream = TcpStream::connect(&addr).lldb("failed to connect to lldb-dap")?;
        debug!("Connected to lldb-dap");

        stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
        stream.set_write_timeout(Some(Duration::from_secs(5))).ok();

        // Send DAP initialize request
        let init_request = serde_json::json!({
            "seq": 1,
            "type": "request",
            "command": "initialize",
            "arguments": {
                "clientID": "detrix-rust-client",
                "clientName": "Detrix Rust Client",
                "adapterID": "lldb-dap",
                "pathFormat": "path",
                "linesStartAt1": true,
                "columnsStartAt1": true,
                "supportsVariableType": true,
                "supportsVariablePaging": true,
                "supportsRunInTerminalRequest": false,
                "locale": "en-US"
            }
        });

        debug!("Sending initialize request");
        send_dap_message(&mut stream, &init_request)?;

        // Read initialize response
        debug!("Waiting for initialize response");
        let response = read_dap_response(&mut stream, "initialize")?;
        debug!("Initialize response: {:?}", response);

        if response.get("success") != Some(&serde_json::Value::Bool(true)) {
            let message = response
                .get("message")
                .and_then(|m| m.as_str())
                .unwrap_or("unknown error");
            return Err(Error::LldbStartFailed(format!(
                "initialize failed: {}",
                message
            )));
        }

        // Send attach request
        let attach_request = serde_json::json!({
            "seq": 2,
            "type": "request",
            "command": "attach",
            "arguments": {
                "pid": pid,
                "stopOnEntry": false
            }
        });

        debug!("Sending attach request for PID {}", pid);
        send_dap_message(&mut stream, &attach_request)?;

        // Read attach response - NOTE: lldb-dap may send events before the response
        debug!("Waiting for attach response (may receive events first)");
        let response = read_dap_response(&mut stream, "attach")?;
        debug!("Attach response: {:?}", response);

        if response.get("success") != Some(&serde_json::Value::Bool(true)) {
            let message = response
                .get("message")
                .and_then(|m| m.as_str())
                .unwrap_or("unknown error");
            return Err(Error::LldbStartFailed(format!(
                "attach failed: {}",
                message
            )));
        }

        // Send configurationDone request
        let config_done_request = serde_json::json!({
            "seq": 3,
            "type": "request",
            "command": "configurationDone",
            "arguments": {}
        });

        debug!("Sending configurationDone request");
        send_dap_message(&mut stream, &config_done_request)?;

        // Read configurationDone response
        debug!("Waiting for configurationDone response");
        let response = read_dap_response(&mut stream, "configurationDone")?;
        debug!("ConfigurationDone response: {:?}", response);

        // Keep the connection open for the daemon to use
        // The stream will be closed when it goes out of scope

        debug!("lldb-dap attached to PID {}", pid);
        Ok(())
    }

    /// Kill the lldb-dap process gracefully.
    pub fn kill(&self, process: &mut LldbProcess) -> Result<()> {
        self.kill_process(&mut process.child)
    }

    /// Kill a child process gracefully.
    fn kill_process(&self, child: &mut Child) -> Result<()> {
        #[cfg(unix)]
        {
            use nix::sys::signal::{kill, Signal};
            use nix::unistd::Pid;

            let pid = Pid::from_raw(child.id() as i32);

            // Try graceful shutdown first (SIGTERM)
            if kill(pid, Signal::SIGTERM).is_ok() {
                // Wait with timeout
                let deadline = Instant::now() + Duration::from_secs(2);
                while Instant::now() < deadline {
                    if child.try_wait().ok().flatten().is_some() {
                        return Ok(());
                    }
                    std::thread::sleep(Duration::from_millis(100));
                }
            }

            // Force kill
            let _ = child.kill();
            let _ = child.wait();
        }

        #[cfg(not(unix))]
        {
            let _ = child.kill();
            let _ = child.wait();
        }

        Ok(())
    }
}

/// Allocate an ephemeral port.
fn allocate_port(host: &str) -> Result<u16> {
    use std::net::TcpListener;

    let addr = format!("{}:0", host);
    let listener = TcpListener::bind(&addr).port_bind("failed to bind")?;

    let port = listener
        .local_addr()
        .port_bind("failed to get local addr")?
        .port();

    // Drop listener to release port for lldb-dap
    drop(listener);

    Ok(port)
}

/// Check if the error indicates a port bind failure.
fn is_port_bind_error(err: &Error) -> bool {
    match err {
        Error::PortBindError(_) => true,
        Error::LldbStartFailed(msg) => {
            msg.contains("address already in use") || msg.contains("bind")
        }
        _ => false,
    }
}

/// Send a DAP message over the stream.
fn send_dap_message(stream: &mut TcpStream, message: &serde_json::Value) -> Result<()> {
    use std::io::Write;

    let body = serde_json::to_string(message)?;
    let header = format!("Content-Length: {}\r\n\r\n", body.len());

    stream
        .write_all(header.as_bytes())
        .lldb("failed to write header")?;
    stream
        .write_all(body.as_bytes())
        .lldb("failed to write body")?;
    stream.flush().lldb("failed to flush")?;

    Ok(())
}

/// Read a DAP response, skipping any events that come before it.
fn read_dap_response(stream: &mut TcpStream, expected_command: &str) -> Result<serde_json::Value> {
    let start = Instant::now();
    let timeout = Duration::from_secs(10);

    loop {
        if start.elapsed() > timeout {
            return Err(Error::Timeout(format!(
                "timed out waiting for {} response",
                expected_command
            )));
        }

        let msg = read_dap_message(stream)?;
        let msg_type = msg.get("type").and_then(|t| t.as_str()).unwrap_or("");

        match msg_type {
            "response" => {
                // This is what we're looking for
                return Ok(msg);
            }
            "event" => {
                // Skip events, but log them
                let event_name = msg.get("event").and_then(|e| e.as_str()).unwrap_or("?");
                eprintln!("[LLDB] Skipping event: {}", event_name);
                continue;
            }
            other => {
                eprintln!("[LLDB] Unexpected message type: {}", other);
                continue;
            }
        }
    }
}

/// Read a DAP message from the stream.
fn read_dap_message(stream: &mut TcpStream) -> Result<serde_json::Value> {
    use std::io::{BufRead, BufReader, Read};

    let mut reader = BufReader::new(stream.try_clone().lldb("failed to clone stream")?);

    // Read headers
    let mut content_length: Option<usize> = None;
    loop {
        let mut line = String::new();
        reader.read_line(&mut line).lldb("failed to read header")?;

        let line = line.trim();
        if line.is_empty() {
            break;
        }

        if let Some(value) = line.strip_prefix("Content-Length:") {
            content_length = value.trim().parse().ok();
        }
    }

    let content_length = content_length
        .ok_or_else(|| Error::LldbStartFailed("missing Content-Length header".to_string()))?;

    // Read body
    let mut body = vec![0u8; content_length];
    reader.read_exact(&mut body).lldb("failed to read body")?;

    serde_json::from_slice(&body).lldb("failed to parse response")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_allocate_port() {
        let port = allocate_port("127.0.0.1").unwrap();
        assert!(port > 0);
    }

    #[test]
    fn test_is_port_bind_error() {
        assert!(is_port_bind_error(&Error::PortBindError(
            "test".to_string()
        )));
        assert!(is_port_bind_error(&Error::LldbStartFailed(
            "address already in use".to_string()
        )));
        assert!(!is_port_bind_error(&Error::LldbNotFound(
            "test".to_string()
        )));
    }
}