node-js 0.1.13

JavaScript as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a JsHost object heap, with no bespoke VM or JIT
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Debug Adapter Protocol over stdio (`node --dap`).
//!
//! A single-threaded source-line debugger. The program is compiled with
//! per-statement line markers (`Op::CallBuiltin(DBG_LINE, 1)`, emitted only in
//! this mode — normal runs carry zero extra ops) and run on the pure interpreter
//! (the tracing JIT would compile hot loops and skip the markers, so `--dap`
//! compiles with `set_debug_mode(true)`, which installs the marker hook instead
//! of `enable_tracing_jit`). The `DBG_LINE` builtin fires synchronously at each
//! marker; when it lands on a breakpoint or a step target it pauses IN PLACE and
//! services DAP requests (`stackTrace`/`scopes`/`variables`/`continue`/`next`/
//! `stepIn`/`stepOut`) from stdin until a resume command, then returns control to
//! the VM.
//!
//! Because it is single-threaded, an async `pause` of a free-running program is
//! not supported (the adapter only reads requests while stopped at a marker);
//! breakpoints and stepping — the load-bearing features — work inside function,
//! loop, and try/catch bodies. Program stdout is redirected to a pipe during the
//! run and forwarded as `output` events, so `console.log`/`process.stdout.write`
//! never corrupt the JSON protocol channel on the saved stdout fd.

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, VM};

/// How the debuggee should proceed from a stop.
#[derive(Clone, Copy, PartialEq)]
enum Mode {
    Continue,
    StepIn,
    StepOver(usize),
    StepOut(usize),
}

struct DebugState {
    breakpoints: HashSet<u32>,
    /// Lines that actually carry a marker (so a breakpoint on them can fire).
    verified: HashSet<u32>,
    /// Function names on which to break at entry (`setFunctionBreakpoints`).
    function_breakpoints: HashSet<String>,
    /// Frame depth seen at the previous marker; a jump upward means a call was
    /// entered — the trigger for a function breakpoint.
    last_depth: usize,
    mode: Mode,
    /// Real stdout, saved before the program's stdout is redirected to a pipe;
    /// all DAP protocol is written here.
    proto_fd: RawFd,
    /// Read end of the program-stdout pipe (non-blocking), drained into `output`
    /// events. `-1` until `launch` sets it up.
    pipe_r: RawFd,
    /// Source path reported in stack frames.
    program: String,
    seq: i64,
    /// True once `launch` has redirected stdout and the debuggee is running.
    active: bool,
}

thread_local! {
    static DBG: RefCell<DebugState> = RefCell::new(DebugState {
        breakpoints: HashSet::new(),
        verified: HashSet::new(),
        function_breakpoints: HashSet::new(),
        last_depth: 0,
        mode: Mode::Continue,
        proto_fd: 1,
        pipe_r: -1,
        program: String::new(),
        seq: 1,
        active: false,
    });
}

/// Entry point for `node --dap`.
pub fn run() -> Result<(), String> {
    // Save the real stdout up front; all DAP protocol goes here even after the
    // program's stdout is redirected to a pipe during `launch`.
    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,
                        "supportsFunctionBreakpoints": true,
                        "supportsTerminateRequest": true,
                    }),
                );
                event("initialized", json!({}));
            }
            "setBreakpoints" => set_breakpoints(&msg, req_seq),
            "setFunctionBreakpoints" => set_function_breakpoints(&msg, req_seq),
            "setExceptionBreakpoints" => {
                // Accepted so clients that always send it proceed; the
                // single-threaded adapter does not stop on exceptions (the VM has
                // already returned control by the time one surfaces).
                respond(req_seq, command, json!({ "breakpoints": [] }));
            }
            "evaluate" => {
                // Nothing is on the stack before `launch`; ack with an empty
                // result so a watch/hover registered up front does not error.
                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(())
}

/// `setBreakpoints`: store the requested lines and report each verified only if
/// the program actually emits a marker on that line (a blank/comment line with no
/// compiled statement is reported unverified — a breakpoint there would never
/// fire).
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 }));
}

/// `setFunctionBreakpoints`: store the requested function names. Each is reported
/// verified; the marker hook stops on the first marker executed inside a frame
/// whose name matches — break-on-entry, see [`on_debug_line`].
fn set_function_breakpoints(msg: &J, req_seq: i64) {
    let names: Vec<String> = msg
        .get("arguments")
        .and_then(|a| a.get("breakpoints"))
        .and_then(|b| b.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|b| b.get("name").and_then(|n| n.as_str()).map(String::from))
                .collect()
        })
        .unwrap_or_default();
    DBG.with(|d| d.borrow_mut().function_breakpoints = names.iter().cloned().collect());
    let bps: Vec<J> = names.iter().map(|_| json!({ "verified": true })).collect();
    respond(
        req_seq,
        "setFunctionBreakpoints",
        json!({ "breakpoints": bps }),
    );
}

/// Evaluate a debugger expression. v1 resolves a bare variable name against the
/// paused frame's locals (mirrors awkrs's snapshot lookup); anything else returns
/// a hint rather than spawning a sub-interpreter.
fn evaluate_expression(expr: &str) -> String {
    if expr.is_empty() {
        return String::new();
    }
    for (name, repr) in crate::host::with_host(|h| h.dbg_locals()) {
        if name == expr {
            return repr;
        }
    }
    format!("<cannot evaluate `{expr}`>")
}

/// The set of source lines that carry a `DBG_LINE` marker in the compiled program
/// (module main + every function body + every try/catch/finally block) — the
/// lines on which a breakpoint can actually stop.
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(prog) = crate::compile_debug(&src) else {
        return set;
    };
    let mut scan = |chunk: &fusevm::Chunk| {
        for (i, op) in chunk.ops.iter().enumerate() {
            if let Op::CallBuiltin(id, _) = op {
                if *id == crate::host::ops::DBG_LINE {
                    if let Some(l) = chunk.lines.get(i) {
                        set.insert(*l);
                    }
                }
            }
        }
    };
    scan(&prog.main);
    for (_, f) in &prog.functions {
        scan(&f.chunk);
    }
    for t in &prog.tries {
        scan(&t.block);
        if let Some((_name, handler)) = &t.handler {
            scan(handler);
        }
        if let Some(finalizer) = &t.finalizer {
            scan(finalizer);
        }
    }
    set
}

/// Run the program under the debugger: redirect its stdout to a pipe, run with
/// the debug marker hook (which pauses at breakpoints/steps), then restore
/// stdout, flush remaining output, and emit `terminated`.
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();
        }
    });
    // SAFETY: standard pipe + dup2 on the process's own stdout fd; the read end
    // is set non-blocking so `drain_output` never stalls the debugger.
    let pipe_r = unsafe {
        let mut fds = [0i32; 2];
        if libc::pipe(fds.as_mut_ptr()) != 0 {
            -1
        } else {
            libc::dup2(fds[1], 1);
            libc::close(fds[1]);
            let flags = libc::fcntl(fds[0], libc::F_GETFL);
            libc::fcntl(fds[0], libc::F_SETFL, flags | libc::O_NONBLOCK);
            fds[0]
        }
    };
    DBG.with(|d| {
        let mut s = d.borrow_mut();
        s.pipe_r = pipe_r;
        s.mode = Mode::Continue;
        s.active = true;
    });

    if let Err(e) = crate::eval_file_debug(program) {
        eprintln!("node: {e}");
    }

    // Restore stdout, drain any trailing program output, then close the pipe.
    let _ = std::io::stdout().flush();
    DBG.with(|d| d.borrow_mut().active = false);
    drain_output();
    let saved = DBG.with(|d| d.borrow().proto_fd);
    unsafe {
        if saved >= 0 {
            libc::dup2(saved, 1);
        }
        if pipe_r >= 0 {
            libc::close(pipe_r);
        }
    }
    DBG.with(|d| d.borrow_mut().pipe_r = -1);
    event("terminated", json!({}));
}

/// Extension-handler shim kept for the `Op::Extended` dispatch seam registered in
/// `host::run_chunk_on`. node-js emits `DBG_LINE` as `Op::CallBuiltin`, not
/// `Op::Extended`, so in the current wiring the live hook is `on_debug_line`
/// (invoked from the `DBG_LINE` builtin — see `builtins::b_dbg_line`). This shim
/// routes an `Extended(DBG_LINE)` marker to the same logic should the emission
/// seam ever be switched, and is a no-op for every other extension id.
pub fn on_ext(vm: &mut VM, id: u16) {
    if id == crate::host::ops::DBG_LINE {
        let line = *vm.chunk.lines.get(vm.ip.saturating_sub(1)).unwrap_or(&0);
        on_debug_line(line);
    }
}

/// Called by the VM at each statement marker (via the `DBG_LINE` builtin, which
/// passes the marker's source `line`). If it is a breakpoint or the active step
/// target, pauses and services DAP requests until a resume command.
pub fn on_debug_line(line: u32) {
    if line == 0 {
        return;
    }
    let (depth, fname) = crate::host::with_host(|h| {
        h.set_cur_line(line);
        (
            h.frame_depth(),
            h.dbg_stack()
                .first()
                .map(|(n, _)| n.clone())
                .unwrap_or_default(),
        )
    });
    let (stop, reason) = DBG.with(|d| {
        let mut s = d.borrow_mut();
        if !s.active {
            s.last_depth = depth;
            return (false, "");
        }
        let bp = s.breakpoints.contains(&line) && s.verified.contains(&line);
        // A deeper frame than the previous marker means a call was just entered;
        // stop if that frame's name matches a function breakpoint.
        let fbp = depth > s.last_depth && s.function_breakpoints.contains(&fname);
        let step = match s.mode {
            Mode::Continue => false,
            Mode::StepIn => true,
            Mode::StepOver(d0) => depth <= d0,
            Mode::StepOut(d0) => depth < d0,
        };
        s.last_depth = depth;
        let reason = if bp {
            "breakpoint"
        } else if fbp {
            "function breakpoint"
        } else {
            "step"
        };
        (bp || fbp || step, reason)
    });
    if !stop {
        return;
    }
    drain_output();
    event(
        "stopped",
        json!({
            "reason": reason,
            "threadId": 1,
            "allThreadsStopped": true,
        }),
    );

    // Service requests until a resume command returns control to the VM.
    let mut stdin = std::io::stdin();
    loop {
        match read_message(&mut stdin) {
            Ok(Some(msg)) => {
                if handle_stopped(&msg, depth) {
                    break;
                }
            }
            _ => {
                // EOF / read error: let the program run to completion.
                DBG.with(|d| d.borrow_mut().mode = Mode::Continue);
                break;
            }
        }
    }
}

/// Handle one request while stopped. Returns true when a resume command
/// (`continue`/`next`/`stepIn`/`stepOut`) was processed and the VM should run on.
fn handle_stopped(msg: &J, depth: usize) -> 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 = DBG.with(|d| d.borrow().program.clone());
            let frames: Vec<J> = crate::host::with_host(|h| h.dbg_stack())
                .into_iter()
                .enumerate()
                .map(|(i, (name, line))| {
                    json!({
                        "id": i,
                        "name": name,
                        "line": line,
                        "column": 1,
                        "source": { "path": program },
                    })
                })
                .collect();
            respond(
                req_seq,
                command,
                json!({ "stackFrames": frames, "totalFrames": frames.len() }),
            );
            false
        }
        "scopes" => {
            respond(
                req_seq,
                command,
                json!({ "scopes": [{ "name": "Locals", "variablesReference": 1, "expensive": false }] }),
            );
            false
        }
        "variables" => {
            let vars: Vec<J> = crate::host::with_host(|h| h.dbg_locals())
                .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
        }
        "setFunctionBreakpoints" => {
            set_function_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 = evaluate_expression(&expr);
            respond(
                req_seq,
                command,
                json!({ "result": result, "variablesReference": 0 }),
            );
            false
        }
        "pause" => {
            // Already stopped at this marker; `pause` is a no-op ack for the
            // single-threaded adapter.
            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" => {
            DBG.with(|d| d.borrow_mut().mode = Mode::StepOver(depth));
            respond(req_seq, command, json!({}));
            true
        }
        "stepIn" => {
            DBG.with(|d| d.borrow_mut().mode = Mode::StepIn);
            respond(req_seq, command, json!({}));
            true
        }
        "stepOut" => {
            DBG.with(|d| d.borrow_mut().mode = Mode::StepOut(depth));
            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
        }
    }
}

/// Read whatever the program has written to its stdout pipe so far (non-blocking)
/// and forward it as an `output` event.
fn drain_output() {
    let fd = DBG.with(|d| d.borrow().pipe_r);
    if fd < 0 {
        return;
    }
    let mut out = Vec::new();
    let mut buf = [0u8; 4096];
    loop {
        let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
        if n > 0 {
            out.extend_from_slice(&buf[..n as usize]);
        } else {
            break;
        }
    }
    if !out.is_empty() {
        let text = String::from_utf8_lossy(&out).to_string();
        event("output", json!({ "category": "stdout", "output": text }));
    }
}

// ---- wire protocol --------------------------------------------------------

/// Read one `Content-Length`-framed JSON message; `None` at EOF.
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}"))
}

/// Write a framed JSON message to the saved protocol fd (never to fd 1, which is
/// the program's redirected stdout during a run).
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);
    // SAFETY: `fd` is a valid duplicated stdout fd owned by this process; wrapped
    // in ManuallyDrop so the File does not close it on drop.
    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 }));
}