1use 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#[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 verified: HashSet<u32>,
42 function_breakpoints: HashSet<String>,
44 last_depth: usize,
47 mode: Mode,
48 proto_fd: RawFd,
51 pipe_r: RawFd,
54 program: String,
56 seq: i64,
57 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
76pub fn run() -> Result<(), String> {
78 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 respond(req_seq, command, json!({ "breakpoints": [] }));
108 }
109 "evaluate" => {
110 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
148fn 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
190fn 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
213fn 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
228fn 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 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
268fn 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 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 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
323pub fn on_ext(vm: &mut VM, id: u16) {
330 if id == crate::host::ops::DBG_LINE {
331 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
340pub 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 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 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 DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
408 break;
409 }
410 }
411 }
412}
413
414fn 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 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
532fn 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
555fn 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
588fn 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 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}