Skip to main content

nodejs/
dap.rs

1//! Debug Adapter Protocol over stdio (`node --dap`).
2//!
3//! A single-threaded source-line debugger. The program is compiled with
4//! per-statement line markers (`Op::CallBuiltin(DBG_LINE, 1)`, emitted only in
5//! this mode — normal runs carry zero extra ops) and run on the pure interpreter
6//! (the tracing JIT would compile hot loops and skip the markers, so `--dap`
7//! compiles with `set_debug_mode(true)`, which installs the marker hook instead
8//! of `enable_tracing_jit`). The `DBG_LINE` builtin fires synchronously at each
9//! marker; when it lands on a breakpoint or a step target it pauses IN PLACE and
10//! services DAP requests (`stackTrace`/`scopes`/`variables`/`continue`/`next`/
11//! `stepIn`/`stepOut`) from stdin until a resume command, then returns control to
12//! the VM.
13//!
14//! Because it is single-threaded, an async `pause` of a free-running program is
15//! not supported (the adapter only reads requests while stopped at a marker);
16//! breakpoints and stepping — the load-bearing features — work inside function,
17//! loop, and try/catch bodies. Program stdout is redirected to a pipe during the
18//! run and forwarded as `output` events, so `console.log`/`process.stdout.write`
19//! never corrupt the JSON protocol channel on the saved stdout fd.
20
21use serde_json::{json, Value as J};
22use std::cell::RefCell;
23use std::collections::HashSet;
24use std::io::{Read, Write};
25use std::os::unix::io::{FromRawFd, RawFd};
26
27use fusevm::{Op, VM};
28
29/// How the debuggee should proceed from a stop.
30#[derive(Clone, Copy, PartialEq)]
31enum Mode {
32    Continue,
33    StepIn,
34    StepOver(usize),
35    StepOut(usize),
36}
37
38struct DebugState {
39    breakpoints: HashSet<u32>,
40    /// Lines that actually carry a marker (so a breakpoint on them can fire).
41    verified: HashSet<u32>,
42    /// Function names on which to break at entry (`setFunctionBreakpoints`).
43    function_breakpoints: HashSet<String>,
44    /// Frame depth seen at the previous marker; a jump upward means a call was
45    /// entered — the trigger for a function breakpoint.
46    last_depth: usize,
47    mode: Mode,
48    /// Real stdout, saved before the program's stdout is redirected to a pipe;
49    /// all DAP protocol is written here.
50    proto_fd: RawFd,
51    /// Read end of the program-stdout pipe (non-blocking), drained into `output`
52    /// events. `-1` until `launch` sets it up.
53    pipe_r: RawFd,
54    /// Source path reported in stack frames.
55    program: String,
56    seq: i64,
57    /// True once `launch` has redirected stdout and the debuggee is running.
58    active: bool,
59}
60
61thread_local! {
62    static DBG: RefCell<DebugState> = RefCell::new(DebugState {
63        breakpoints: HashSet::new(),
64        verified: HashSet::new(),
65        function_breakpoints: HashSet::new(),
66        last_depth: 0,
67        mode: Mode::Continue,
68        proto_fd: 1,
69        pipe_r: -1,
70        program: String::new(),
71        seq: 1,
72        active: false,
73    });
74}
75
76/// Entry point for `node --dap`.
77pub fn run() -> Result<(), String> {
78    // Save the real stdout up front; all DAP protocol goes here even after the
79    // program's stdout is redirected to a pipe during `launch`.
80    let proto = unsafe { libc::dup(1) };
81    DBG.with(|d| d.borrow_mut().proto_fd = proto);
82
83    let mut input = std::io::stdin();
84    while let Some(msg) = read_message(&mut input)? {
85        let command = msg.get("command").and_then(|c| c.as_str()).unwrap_or("");
86        let req_seq = msg.get("seq").and_then(|s| s.as_i64()).unwrap_or(0);
87        match command {
88            "initialize" => {
89                respond(
90                    req_seq,
91                    command,
92                    json!({
93                        "supportsConfigurationDoneRequest": true,
94                        "supportsEvaluateForHovers": true,
95                        "supportsFunctionBreakpoints": true,
96                        "supportsTerminateRequest": true,
97                    }),
98                );
99                event("initialized", json!({}));
100            }
101            "setBreakpoints" => set_breakpoints(&msg, req_seq),
102            "setFunctionBreakpoints" => set_function_breakpoints(&msg, req_seq),
103            "setExceptionBreakpoints" => {
104                // Accepted so clients that always send it proceed; the
105                // single-threaded adapter does not stop on exceptions (the VM has
106                // already returned control by the time one surfaces).
107                respond(req_seq, command, json!({ "breakpoints": [] }));
108            }
109            "evaluate" => {
110                // Nothing is on the stack before `launch`; ack with an empty
111                // result so a watch/hover registered up front does not error.
112                respond(
113                    req_seq,
114                    command,
115                    json!({ "result": "", "variablesReference": 0 }),
116                );
117            }
118            "pause" => respond(req_seq, command, json!({})),
119            "configurationDone" => respond(req_seq, command, json!({})),
120            "threads" => respond(
121                req_seq,
122                command,
123                json!({ "threads": [{ "id": 1, "name": "main" }] }),
124            ),
125            "launch" => {
126                let program = msg
127                    .get("arguments")
128                    .and_then(|a| a.get("program"))
129                    .and_then(|p| p.as_str())
130                    .unwrap_or("")
131                    .to_string();
132                respond(req_seq, command, json!({}));
133                launch(&program);
134            }
135            "disconnect" | "terminate" => {
136                respond(req_seq, command, json!({}));
137                break;
138            }
139            _ => respond(req_seq, command, json!({})),
140        }
141    }
142    unsafe {
143        libc::close(proto);
144    }
145    Ok(())
146}
147
148/// `setBreakpoints`: store the requested lines and report each verified only if
149/// the program actually emits a marker on that line (a blank/comment line with no
150/// compiled statement is reported unverified — a breakpoint there would never
151/// fire).
152fn set_breakpoints(msg: &J, req_seq: i64) {
153    let path = msg
154        .get("arguments")
155        .and_then(|a| a.get("source"))
156        .and_then(|s| s.get("path"))
157        .and_then(|p| p.as_str())
158        .unwrap_or("")
159        .to_string();
160    let lines: Vec<u32> = msg
161        .get("arguments")
162        .and_then(|a| a.get("breakpoints"))
163        .and_then(|b| b.as_array())
164        .map(|bps| {
165            bps.iter()
166                .filter_map(|b| b.get("line").and_then(|l| l.as_u64()).map(|l| l as u32))
167                .collect()
168        })
169        .unwrap_or_default();
170
171    let markers = marker_lines(&path);
172    DBG.with(|d| {
173        let mut s = d.borrow_mut();
174        if !path.is_empty() {
175            s.program = path;
176        }
177        s.breakpoints = lines.iter().copied().collect();
178        s.verified = markers;
179    });
180    let bps: Vec<J> = DBG.with(|d| {
181        let s = d.borrow();
182        lines
183            .iter()
184            .map(|l| json!({ "verified": s.verified.contains(l), "line": l }))
185            .collect()
186    });
187    respond(req_seq, "setBreakpoints", json!({ "breakpoints": bps }));
188}
189
190/// `setFunctionBreakpoints`: store the requested function names. Each is reported
191/// verified; the marker hook stops on the first marker executed inside a frame
192/// whose name matches — break-on-entry, see [`on_debug_line`].
193fn set_function_breakpoints(msg: &J, req_seq: i64) {
194    let names: Vec<String> = msg
195        .get("arguments")
196        .and_then(|a| a.get("breakpoints"))
197        .and_then(|b| b.as_array())
198        .map(|arr| {
199            arr.iter()
200                .filter_map(|b| b.get("name").and_then(|n| n.as_str()).map(String::from))
201                .collect()
202        })
203        .unwrap_or_default();
204    DBG.with(|d| d.borrow_mut().function_breakpoints = names.iter().cloned().collect());
205    let bps: Vec<J> = names.iter().map(|_| json!({ "verified": true })).collect();
206    respond(
207        req_seq,
208        "setFunctionBreakpoints",
209        json!({ "breakpoints": bps }),
210    );
211}
212
213/// Evaluate a debugger expression. v1 resolves a bare variable name against the
214/// paused frame's locals (mirrors awkrs's snapshot lookup); anything else returns
215/// a hint rather than spawning a sub-interpreter.
216fn evaluate_expression(expr: &str) -> String {
217    if expr.is_empty() {
218        return String::new();
219    }
220    for (name, repr) in crate::host::with_host(|h| h.dbg_locals()) {
221        if name == expr {
222            return repr;
223        }
224    }
225    format!("<cannot evaluate `{expr}`>")
226}
227
228/// The set of source lines that carry a `DBG_LINE` marker in the compiled program
229/// (module main + every function body + every try/catch/finally block) — the
230/// lines on which a breakpoint can actually stop.
231fn marker_lines(path: &str) -> HashSet<u32> {
232    let mut set = HashSet::new();
233    let Ok(src) = std::fs::read_to_string(path) else {
234        return set;
235    };
236    let Ok(prog) = crate::compile_debug(&src) else {
237        return set;
238    };
239    let mut scan = |chunk: &fusevm::Chunk| {
240        for (i, op) in chunk.ops.iter().enumerate() {
241            if let Op::CallBuiltin(id, _) = op {
242                // The marker's operand — the `LoadInt(line)` before it — is
243                // the line; `chunk.lines` holds source positions, not lines.
244                if *id == crate::host::ops::DBG_LINE {
245                    if let Some(Op::LoadInt(l)) = i.checked_sub(1).map(|p| &chunk.ops[p]) {
246                        set.insert(*l as u32);
247                    }
248                }
249            }
250        }
251    };
252    scan(&prog.main);
253    for (_, f) in &prog.functions {
254        scan(&f.chunk);
255    }
256    for t in &prog.tries {
257        scan(&t.block);
258        if let Some((_name, handler)) = &t.handler {
259            scan(handler);
260        }
261        if let Some(finalizer) = &t.finalizer {
262            scan(finalizer);
263        }
264    }
265    set
266}
267
268/// Run the program under the debugger: redirect its stdout to a pipe, run with
269/// the debug marker hook (which pauses at breakpoints/steps), then restore
270/// stdout, flush remaining output, and emit `terminated`.
271fn launch(program: &str) {
272    if program.is_empty() {
273        return;
274    }
275    DBG.with(|d| {
276        let mut s = d.borrow_mut();
277        if s.program.is_empty() {
278            s.program = program.to_string();
279        }
280    });
281    // SAFETY: standard pipe + dup2 on the process's own stdout fd; the read end
282    // is set non-blocking so `drain_output` never stalls the debugger.
283    let pipe_r = unsafe {
284        let mut fds = [0i32; 2];
285        if libc::pipe(fds.as_mut_ptr()) != 0 {
286            -1
287        } else {
288            libc::dup2(fds[1], 1);
289            libc::close(fds[1]);
290            let flags = libc::fcntl(fds[0], libc::F_GETFL);
291            libc::fcntl(fds[0], libc::F_SETFL, flags | libc::O_NONBLOCK);
292            fds[0]
293        }
294    };
295    DBG.with(|d| {
296        let mut s = d.borrow_mut();
297        s.pipe_r = pipe_r;
298        s.mode = Mode::Continue;
299        s.active = true;
300    });
301
302    if let Err(e) = crate::eval_file_debug(program) {
303        eprintln!("node: {e}");
304    }
305
306    // Restore stdout, drain any trailing program output, then close the pipe.
307    let _ = std::io::stdout().flush();
308    DBG.with(|d| d.borrow_mut().active = false);
309    drain_output();
310    let saved = DBG.with(|d| d.borrow().proto_fd);
311    unsafe {
312        if saved >= 0 {
313            libc::dup2(saved, 1);
314        }
315        if pipe_r >= 0 {
316            libc::close(pipe_r);
317        }
318    }
319    DBG.with(|d| d.borrow_mut().pipe_r = -1);
320    event("terminated", json!({}));
321}
322
323/// Extension-handler shim kept for the `Op::Extended` dispatch seam registered in
324/// `host::run_chunk_on`. node-js emits `DBG_LINE` as `Op::CallBuiltin`, not
325/// `Op::Extended`, so in the current wiring the live hook is `on_debug_line`
326/// (invoked from the `DBG_LINE` builtin — see `builtins::b_dbg_line`). This shim
327/// routes an `Extended(DBG_LINE)` marker to the same logic should the emission
328/// seam ever be switched, and is a no-op for every other extension id.
329pub fn on_ext(vm: &mut VM, id: u16) {
330    if id == crate::host::ops::DBG_LINE {
331        // The marker's operand is the `LoadInt(line)` just before it.
332        let line = match vm.ip.checked_sub(2).and_then(|p| vm.chunk.ops.get(p)) {
333            Some(Op::LoadInt(l)) => *l as u32,
334            _ => 0,
335        };
336        on_debug_line(line);
337    }
338}
339
340/// Called by the VM at each statement marker (via the `DBG_LINE` builtin, which
341/// passes the marker's source `line`). If it is a breakpoint or the active step
342/// target, pauses and services DAP requests until a resume command.
343pub fn on_debug_line(line: u32) {
344    if line == 0 {
345        return;
346    }
347    let (depth, fname) = crate::host::with_host(|h| {
348        h.set_cur_line(line);
349        (
350            h.frame_depth(),
351            h.dbg_stack()
352                .first()
353                .map(|(n, _)| n.clone())
354                .unwrap_or_default(),
355        )
356    });
357    let (stop, reason) = DBG.with(|d| {
358        let mut s = d.borrow_mut();
359        if !s.active {
360            s.last_depth = depth;
361            return (false, "");
362        }
363        let bp = s.breakpoints.contains(&line) && s.verified.contains(&line);
364        // A deeper frame than the previous marker means a call was just entered;
365        // stop if that frame's name matches a function breakpoint.
366        let fbp = depth > s.last_depth && s.function_breakpoints.contains(&fname);
367        let step = match s.mode {
368            Mode::Continue => false,
369            Mode::StepIn => true,
370            Mode::StepOver(d0) => depth <= d0,
371            Mode::StepOut(d0) => depth < d0,
372        };
373        s.last_depth = depth;
374        let reason = if bp {
375            "breakpoint"
376        } else if fbp {
377            "function breakpoint"
378        } else {
379            "step"
380        };
381        (bp || fbp || step, reason)
382    });
383    if !stop {
384        return;
385    }
386    drain_output();
387    event(
388        "stopped",
389        json!({
390            "reason": reason,
391            "threadId": 1,
392            "allThreadsStopped": true,
393        }),
394    );
395
396    // Service requests until a resume command returns control to the VM.
397    let mut stdin = std::io::stdin();
398    loop {
399        match read_message(&mut stdin) {
400            Ok(Some(msg)) => {
401                if handle_stopped(&msg, depth) {
402                    break;
403                }
404            }
405            _ => {
406                // EOF / read error: let the program run to completion.
407                DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
408                break;
409            }
410        }
411    }
412}
413
414/// Handle one request while stopped. Returns true when a resume command
415/// (`continue`/`next`/`stepIn`/`stepOut`) was processed and the VM should run on.
416fn handle_stopped(msg: &J, depth: usize) -> bool {
417    let command = msg.get("command").and_then(|c| c.as_str()).unwrap_or("");
418    let req_seq = msg.get("seq").and_then(|s| s.as_i64()).unwrap_or(0);
419    match command {
420        "threads" => {
421            respond(
422                req_seq,
423                command,
424                json!({ "threads": [{ "id": 1, "name": "main" }] }),
425            );
426            false
427        }
428        "stackTrace" => {
429            let program = DBG.with(|d| d.borrow().program.clone());
430            let frames: Vec<J> = crate::host::with_host(|h| h.dbg_stack())
431                .into_iter()
432                .enumerate()
433                .map(|(i, (name, line))| {
434                    json!({
435                        "id": i,
436                        "name": name,
437                        "line": line,
438                        "column": 1,
439                        "source": { "path": program },
440                    })
441                })
442                .collect();
443            respond(
444                req_seq,
445                command,
446                json!({ "stackFrames": frames, "totalFrames": frames.len() }),
447            );
448            false
449        }
450        "scopes" => {
451            respond(
452                req_seq,
453                command,
454                json!({ "scopes": [{ "name": "Locals", "variablesReference": 1, "expensive": false }] }),
455            );
456            false
457        }
458        "variables" => {
459            let vars: Vec<J> = crate::host::with_host(|h| h.dbg_locals())
460                .into_iter()
461                .map(|(n, v)| json!({ "name": n, "value": v, "variablesReference": 0 }))
462                .collect();
463            respond(req_seq, command, json!({ "variables": vars }));
464            false
465        }
466        "setBreakpoints" => {
467            set_breakpoints(msg, req_seq);
468            false
469        }
470        "setFunctionBreakpoints" => {
471            set_function_breakpoints(msg, req_seq);
472            false
473        }
474        "setExceptionBreakpoints" => {
475            respond(req_seq, command, json!({ "breakpoints": [] }));
476            false
477        }
478        "evaluate" => {
479            let expr = msg
480                .get("arguments")
481                .and_then(|a| a.get("expression"))
482                .and_then(|e| e.as_str())
483                .unwrap_or("")
484                .trim()
485                .to_string();
486            let result = evaluate_expression(&expr);
487            respond(
488                req_seq,
489                command,
490                json!({ "result": result, "variablesReference": 0 }),
491            );
492            false
493        }
494        "pause" => {
495            // Already stopped at this marker; `pause` is a no-op ack for the
496            // single-threaded adapter.
497            respond(req_seq, command, json!({}));
498            false
499        }
500        "continue" => {
501            DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
502            respond(req_seq, command, json!({ "allThreadsContinued": true }));
503            true
504        }
505        "next" => {
506            DBG.with(|d| d.borrow_mut().mode = Mode::StepOver(depth));
507            respond(req_seq, command, json!({}));
508            true
509        }
510        "stepIn" => {
511            DBG.with(|d| d.borrow_mut().mode = Mode::StepIn);
512            respond(req_seq, command, json!({}));
513            true
514        }
515        "stepOut" => {
516            DBG.with(|d| d.borrow_mut().mode = Mode::StepOut(depth));
517            respond(req_seq, command, json!({}));
518            true
519        }
520        "disconnect" | "terminate" => {
521            DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
522            respond(req_seq, command, json!({}));
523            true
524        }
525        _ => {
526            respond(req_seq, command, json!({}));
527            false
528        }
529    }
530}
531
532/// Read whatever the program has written to its stdout pipe so far (non-blocking)
533/// and forward it as an `output` event.
534fn drain_output() {
535    let fd = DBG.with(|d| d.borrow().pipe_r);
536    if fd < 0 {
537        return;
538    }
539    let mut out = Vec::new();
540    let mut buf = [0u8; 4096];
541    loop {
542        let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
543        if n > 0 {
544            out.extend_from_slice(&buf[..n as usize]);
545        } else {
546            break;
547        }
548    }
549    if !out.is_empty() {
550        let text = String::from_utf8_lossy(&out).to_string();
551        event("output", json!({ "category": "stdout", "output": text }));
552    }
553}
554
555// ---- wire protocol --------------------------------------------------------
556
557/// Read one `Content-Length`-framed JSON message; `None` at EOF.
558fn read_message(input: &mut std::io::Stdin) -> Result<Option<J>, String> {
559    let mut header = Vec::new();
560    let mut byte = [0u8; 1];
561    loop {
562        match input.read(&mut byte) {
563            Ok(0) => return Ok(None),
564            Ok(_) => {
565                header.push(byte[0]);
566                if header.ends_with(b"\r\n\r\n") {
567                    break;
568                }
569            }
570            Err(e) => return Err(format!("dap read: {e}")),
571        }
572    }
573    let header = String::from_utf8_lossy(&header);
574    let len: usize = header
575        .lines()
576        .find_map(|l| l.strip_prefix("Content-Length:"))
577        .and_then(|v| v.trim().parse().ok())
578        .ok_or("dap: missing Content-Length")?;
579    let mut body = vec![0u8; len];
580    input
581        .read_exact(&mut body)
582        .map_err(|e| format!("dap body: {e}"))?;
583    serde_json::from_slice(&body)
584        .map(Some)
585        .map_err(|e| format!("dap json: {e}"))
586}
587
588/// Write a framed JSON message to the saved protocol fd (never to fd 1, which is
589/// the program's redirected stdout during a run).
590fn send(msg: &J) {
591    let body = msg.to_string();
592    let frame = format!("Content-Length: {}\r\n\r\n{}", body.len(), body);
593    let fd = DBG.with(|d| d.borrow().proto_fd);
594    // SAFETY: `fd` is a valid duplicated stdout fd owned by this process; wrapped
595    // in ManuallyDrop so the File does not close it on drop.
596    unsafe {
597        let mut f = std::mem::ManuallyDrop::new(std::fs::File::from_raw_fd(fd));
598        let _ = f.write_all(frame.as_bytes());
599        let _ = f.flush();
600    }
601}
602
603fn next_seq() -> i64 {
604    DBG.with(|d| {
605        let mut s = d.borrow_mut();
606        let n = s.seq;
607        s.seq += 1;
608        n
609    })
610}
611
612fn respond(req_seq: i64, command: &str, body: J) {
613    send(&json!({
614        "seq": next_seq(),
615        "type": "response",
616        "request_seq": req_seq,
617        "success": true,
618        "command": command,
619        "body": body,
620    }));
621}
622
623fn event(ev: &str, body: J) {
624    send(&json!({ "seq": next_seq(), "type": "event", "event": ev, "body": body }));
625}