use serde_json::{json, Value as J};
use std::cell::RefCell;
use std::collections::HashSet;
use std::io::{Read, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use fusevm::{Op, Value, VM};
#[derive(Clone, Copy, PartialEq)]
enum Mode {
Continue,
Step,
}
struct DebugState {
breakpoints: HashSet<u32>,
verified: HashSet<u32>,
mode: Mode,
cur_line: u32,
proto_fd: RawFd,
program: String,
seq: i64,
active: bool,
}
thread_local! {
static DBG: RefCell<DebugState> = RefCell::new(DebugState {
breakpoints: HashSet::new(),
verified: HashSet::new(),
mode: Mode::Continue,
cur_line: 0,
proto_fd: 1,
program: String::new(),
seq: 1,
active: false,
});
}
pub fn run() -> Result<(), String> {
let proto = unsafe { libc::dup(1) };
DBG.with(|d| d.borrow_mut().proto_fd = proto);
let mut input = std::io::stdin();
while let Some(msg) = read_message(&mut input)? {
let command = msg.get("command").and_then(|c| c.as_str()).unwrap_or("");
let req_seq = msg.get("seq").and_then(|s| s.as_i64()).unwrap_or(0);
match command {
"initialize" => {
respond(
req_seq,
command,
json!({
"supportsConfigurationDoneRequest": true,
"supportsEvaluateForHovers": true,
"supportsTerminateRequest": true,
}),
);
event("initialized", json!({}));
}
"setBreakpoints" => set_breakpoints(&msg, req_seq),
"setExceptionBreakpoints" => {
respond(req_seq, command, json!({ "breakpoints": [] }));
}
"evaluate" => {
respond(
req_seq,
command,
json!({ "result": "", "variablesReference": 0 }),
);
}
"pause" => respond(req_seq, command, json!({})),
"configurationDone" => respond(req_seq, command, json!({})),
"threads" => respond(
req_seq,
command,
json!({ "threads": [{ "id": 1, "name": "main" }] }),
),
"launch" => {
let program = msg
.get("arguments")
.and_then(|a| a.get("program"))
.and_then(|p| p.as_str())
.unwrap_or("")
.to_string();
respond(req_seq, command, json!({}));
launch(&program);
}
"disconnect" | "terminate" => {
respond(req_seq, command, json!({}));
break;
}
_ => respond(req_seq, command, json!({})),
}
}
unsafe {
libc::close(proto);
}
Ok(())
}
fn set_breakpoints(msg: &J, req_seq: i64) {
let path = msg
.get("arguments")
.and_then(|a| a.get("source"))
.and_then(|s| s.get("path"))
.and_then(|p| p.as_str())
.unwrap_or("")
.to_string();
let lines: Vec<u32> = msg
.get("arguments")
.and_then(|a| a.get("breakpoints"))
.and_then(|b| b.as_array())
.map(|bps| {
bps.iter()
.filter_map(|b| b.get("line").and_then(|l| l.as_u64()).map(|l| l as u32))
.collect()
})
.unwrap_or_default();
let markers = marker_lines(&path);
DBG.with(|d| {
let mut s = d.borrow_mut();
if !path.is_empty() {
s.program = path;
}
s.breakpoints = lines.iter().copied().collect();
s.verified = markers;
});
let bps: Vec<J> = DBG.with(|d| {
let s = d.borrow();
lines
.iter()
.map(|l| json!({ "verified": s.verified.contains(l), "line": l }))
.collect()
});
respond(req_seq, "setBreakpoints", json!({ "breakpoints": bps }));
}
fn marker_lines(path: &str) -> HashSet<u32> {
let mut set = HashSet::new();
let Ok(src) = std::fs::read_to_string(path) else {
return set;
};
let Ok(chunk) = crate::compile_debug(&src) else {
return set;
};
for (i, op) in chunk.ops.iter().enumerate() {
if let Op::CallBuiltin(id, _) = op {
if *id == crate::compiler::ops::DBG_LINE {
if let Some(l) = chunk.lines.get(i) {
set.insert(*l);
}
}
}
}
set
}
fn launch(program: &str) {
if program.is_empty() {
return;
}
DBG.with(|d| {
let mut s = d.borrow_mut();
if s.program.is_empty() {
s.program = program.to_string();
}
s.mode = Mode::Continue;
s.active = true;
});
let outcome = match std::fs::read_to_string(program) {
Ok(src) => crate::run_messages_debug(&src).map_err(|e| format!("! {}.", e.0)),
Err(e) => Err(format!("texrs: {program}: {e}")),
};
DBG.with(|d| d.borrow_mut().active = false);
match outcome {
Ok(msgs) => {
let body = match msgs.is_empty() {
true => String::new(),
false => format!(" {msgs}"),
};
emit_output("stdout", &format!("(./{program}{body} )\n"));
}
Err(e) => emit_output("stderr", &format!("{e}\n")),
}
event("terminated", json!({}));
}
pub fn on_debug_line(vm: &mut VM, _argc: u8) -> Value {
let line = *vm.chunk.lines.get(vm.ip.saturating_sub(1)).unwrap_or(&0);
if line == 0 {
return Value::Undef;
}
let (stop, reason) = DBG.with(|d| {
let mut s = d.borrow_mut();
s.cur_line = line;
if !s.active {
return (false, "");
}
let bp = s.breakpoints.contains(&line) && s.verified.contains(&line);
let step = s.mode == Mode::Step;
let reason = if bp { "breakpoint" } else { "step" };
(bp || step, reason)
});
if !stop {
return Value::Undef;
}
event(
"stopped",
json!({
"reason": reason,
"threadId": 1,
"allThreadsStopped": true,
}),
);
let mut stdin = std::io::stdin();
loop {
match read_message(&mut stdin) {
Ok(Some(msg)) => {
if handle_stopped(vm, &msg) {
break;
}
}
_ => {
DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
break;
}
}
}
Value::Undef
}
fn current_slots(vm: &VM) -> &[Value] {
match vm.frames.last() {
Some(f) => &f.slots,
None => &[],
}
}
fn count_registers(vm: &VM) -> Vec<(String, String)> {
let mut interesting: Vec<u16> = vm
.chunk
.ops
.iter()
.filter_map(|op| match op {
Op::SetSlot(n) => Some(*n),
_ => None,
})
.collect();
for (i, v) in current_slots(vm).iter().enumerate() {
if !matches!(v, Value::Int(0) | Value::Undef) {
interesting.push(i as u16);
}
}
interesting.sort_unstable();
interesting.dedup();
interesting
.into_iter()
.map(|n| {
let value = match current_slots(vm).get(n as usize) {
Some(Value::Int(i)) => i.to_string(),
Some(Value::Undef) | None => "0".to_string(),
Some(other) => format!("{other:?}"),
};
(format!("\\count{n}"), value)
})
.collect()
}
fn handle_stopped(vm: &VM, msg: &J) -> bool {
let command = msg.get("command").and_then(|c| c.as_str()).unwrap_or("");
let req_seq = msg.get("seq").and_then(|s| s.as_i64()).unwrap_or(0);
match command {
"threads" => {
respond(
req_seq,
command,
json!({ "threads": [{ "id": 1, "name": "main" }] }),
);
false
}
"stackTrace" => {
let (program, line) = DBG.with(|d| {
let s = d.borrow();
(s.program.clone(), s.cur_line)
});
let frames = json!([{
"id": 0,
"name": "main",
"line": line,
"column": 1,
"source": { "path": program },
}]);
respond(
req_seq,
command,
json!({ "stackFrames": frames, "totalFrames": 1 }),
);
false
}
"scopes" => {
respond(
req_seq,
command,
json!({ "scopes": [{ "name": "Count registers", "variablesReference": 1, "expensive": false }] }),
);
false
}
"variables" => {
let vars: Vec<J> = count_registers(vm)
.into_iter()
.map(|(n, v)| json!({ "name": n, "value": v, "variablesReference": 0 }))
.collect();
respond(req_seq, command, json!({ "variables": vars }));
false
}
"setBreakpoints" => {
set_breakpoints(msg, req_seq);
false
}
"setExceptionBreakpoints" => {
respond(req_seq, command, json!({ "breakpoints": [] }));
false
}
"evaluate" => {
let expr = msg
.get("arguments")
.and_then(|a| a.get("expression"))
.and_then(|e| e.as_str())
.unwrap_or("")
.trim()
.to_string();
let result = count_registers(vm)
.into_iter()
.find(|(n, _)| *n == expr)
.map(|(_, v)| v)
.unwrap_or_else(|| {
if expr.is_empty() {
String::new()
} else {
format!("<cannot evaluate `{expr}`>")
}
});
respond(
req_seq,
command,
json!({ "result": result, "variablesReference": 0 }),
);
false
}
"pause" => {
respond(req_seq, command, json!({}));
false
}
"continue" => {
DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
respond(req_seq, command, json!({ "allThreadsContinued": true }));
true
}
"next" | "stepIn" | "stepOut" => {
DBG.with(|d| d.borrow_mut().mode = Mode::Step);
respond(req_seq, command, json!({}));
true
}
"disconnect" | "terminate" => {
DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
respond(req_seq, command, json!({}));
true
}
_ => {
respond(req_seq, command, json!({}));
false
}
}
}
fn emit_output(category: &str, text: &str) {
if text.is_empty() {
return;
}
event("output", json!({ "category": category, "output": text }));
}
fn read_message(input: &mut std::io::Stdin) -> Result<Option<J>, String> {
let mut header = Vec::new();
let mut byte = [0u8; 1];
loop {
match input.read(&mut byte) {
Ok(0) => return Ok(None),
Ok(_) => {
header.push(byte[0]);
if header.ends_with(b"\r\n\r\n") {
break;
}
}
Err(e) => return Err(format!("dap read: {e}")),
}
}
let header = String::from_utf8_lossy(&header);
let len: usize = header
.lines()
.find_map(|l| l.strip_prefix("Content-Length:"))
.and_then(|v| v.trim().parse().ok())
.ok_or("dap: missing Content-Length")?;
let mut body = vec![0u8; len];
input
.read_exact(&mut body)
.map_err(|e| format!("dap body: {e}"))?;
serde_json::from_slice(&body)
.map(Some)
.map_err(|e| format!("dap json: {e}"))
}
fn send(msg: &J) {
let body = msg.to_string();
let frame = format!("Content-Length: {}\r\n\r\n{}", body.len(), body);
let fd = DBG.with(|d| d.borrow().proto_fd);
unsafe {
let mut f = std::mem::ManuallyDrop::new(std::fs::File::from_raw_fd(fd));
let _ = f.write_all(frame.as_bytes());
let _ = f.flush();
}
}
fn next_seq() -> i64 {
DBG.with(|d| {
let mut s = d.borrow_mut();
let n = s.seq;
s.seq += 1;
n
})
}
fn respond(req_seq: i64, command: &str, body: J) {
send(&json!({
"seq": next_seq(),
"type": "response",
"request_seq": req_seq,
"success": true,
"command": command,
"body": body,
}));
}
fn event(ev: &str, body: J) {
send(&json!({ "seq": next_seq(), "type": "event", "event": ev, "body": body }));
}