-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathbackend.go
More file actions
605 lines (542 loc) · 17.4 KB
/
backend.go
File metadata and controls
605 lines (542 loc) · 17.4 KB
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
package dap
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
)
// waitForReady scans pipe lines for readyString, extracts an address via parseAddr,
// and kills cmd on timeout (10s) or early exit. Caller must have already started cmd.
func waitForReady(cmd *exec.Cmd, pipe io.ReadCloser, readyString string, parseAddr func(line string) string) (string, error) {
scanner := bufio.NewScanner(pipe)
addrCh := make(chan string, 1)
go func() {
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, readyString) {
addrCh <- parseAddr(line)
for scanner.Scan() {
}
return
}
}
close(addrCh)
}()
select {
case addr, ok := <-addrCh:
if !ok || addr == "" {
_ = cmd.Process.Kill()
_ = cmd.Wait()
return "", fmt.Errorf("process exited without reporting listen address")
}
return addr, nil
case <-time.After(10 * time.Second):
_ = cmd.Process.Kill()
_ = cmd.Wait()
return "", fmt.Errorf("process did not start within 10s")
}
}
// normalizePort ensures port has a ":" prefix and returns both forms.
func normalizePort(port string) (withColon, bare string) {
if !strings.HasPrefix(port, ":") {
port = ":" + port
}
return port, strings.TrimPrefix(port, ":")
}
// Backend abstracts the debugger-specific logic for spawning a DAP server
// and building launch/attach argument maps.
type Backend interface {
Spawn(port string) (cmd *exec.Cmd, addr string, err error)
TransportMode() string
AdapterID() string
LaunchArgs(program string, stopOnEntry bool, args []string) (launchArgs map[string]any, cleanup func(), err error)
RemoteAttachArgs(host string, port int) (map[string]any, error)
// StopOnEntryBreakpoint returns a function name to use as a breakpoint
// for stop-on-entry behavior. If empty, native stopOnEntry is used.
StopOnEntryBreakpoint() string
// PIDAttachArgs returns attach arguments for attaching to a local process by PID.
PIDAttachArgs(pid int) (map[string]any, error)
}
// ResolveVenvPython returns the active virtualenv's python binary if $VIRTUAL_ENV
// is set and contains one, otherwise "". Callers pass this into DebugArgs.Python
// so the daemon (which may have a stale env) uses the correct interpreter.
// Returned path is absolute.
func ResolveVenvPython() string {
venv := os.Getenv("VIRTUAL_ENV")
if venv == "" {
return ""
}
// Windows venvs put the interpreter under Scripts\; POSIX venvs use bin/.
var candidates []string
if runtime.GOOS == "windows" {
candidates = []string{
filepath.Join(venv, "Scripts", "python.exe"),
filepath.Join(venv, "Scripts", "python3.exe"),
}
} else {
candidates = []string{
filepath.Join(venv, "bin", "python3"),
filepath.Join(venv, "bin", "python"),
}
}
for _, p := range candidates {
if _, err := os.Stat(p); err == nil {
if abs, err := filepath.Abs(p); err == nil {
return abs
}
return p
}
}
return ""
}
// ResolvePythonFlag turns a user-supplied --python value into an absolute path
// the daemon can exec directly. Bare names go through exec.LookPath (using the
// caller's PATH, not the daemon's); paths are made absolute. Returns an error
// if the binary cannot be found or doesn't exist.
func ResolvePythonFlag(python string) (string, error) {
if strings.ContainsRune(python, filepath.Separator) || (runtime.GOOS == "windows" && strings.ContainsRune(python, '/')) {
abs, err := filepath.Abs(python)
if err != nil {
return "", fmt.Errorf("resolving --python path: %w", err)
}
if _, err := os.Stat(abs); err != nil {
return "", fmt.Errorf("--python %q: %w", python, err)
}
return abs, nil
}
found, err := exec.LookPath(python)
if err != nil {
return "", fmt.Errorf("--python %q not found on PATH: %w", python, err)
}
abs, err := filepath.Abs(found)
if err != nil {
return found, nil
}
return abs, nil
}
// DetectBackend returns the appropriate backend based on file extension.
func DetectBackend(script string) Backend {
switch strings.ToLower(filepath.Ext(script)) {
case ".py":
return &debugpyBackend{}
case ".go":
return &delveBackend{}
case ".js", ".ts", ".mjs", ".cjs":
return &jsDebugBackend{}
case ".rs", ".c", ".cpp", ".cc":
return &lldbBackend{}
default:
return &debugpyBackend{} // default to debugpy
}
}
// GetBackendByName returns a backend by name.
func GetBackendByName(name string) (Backend, error) {
switch name {
case "debugpy":
return &debugpyBackend{}, nil
case "dlv", "delve":
return &delveBackend{}, nil
case "js-debug":
return &jsDebugBackend{}, nil
case "lldb", "lldb-dap":
return &lldbBackend{}, nil
default:
return nil, fmt.Errorf("unknown backend %q — valid options: debugpy, dlv, js-debug, lldb-dap", name)
}
}
// --- debugpy backend (Python) ---
// debugpyBackend spawns debugpy with python. If python is empty, "python3" from PATH is used.
type debugpyBackend struct {
python string
}
func (b *debugpyBackend) Spawn(port string) (*exec.Cmd, string, error) {
_, actualPort := normalizePort(port)
python := b.python
if python == "" {
python = "python3"
}
cmd := exec.Command(python, "-m", "debugpy.adapter", "--host", "127.0.0.1", "--port", actualPort, "--log-stderr")
cmd.Stdout = nil
stderrPipe, err := cmd.StderrPipe()
if err != nil {
return nil, "", fmt.Errorf("creating stderr pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, "", fmt.Errorf("starting debugpy: %w", err)
}
addr, err := waitForReady(cmd, stderrPipe, "Listening", func(string) string {
return "127.0.0.1:" + actualPort
})
if err != nil {
return nil, "", fmt.Errorf("starting debugpy: %w", err)
}
return cmd, addr, nil
}
func (b *debugpyBackend) TransportMode() string { return "tcp" }
func (b *debugpyBackend) AdapterID() string { return "debugpy" }
func (b *debugpyBackend) StopOnEntryBreakpoint() string { return "" }
func (b *debugpyBackend) LaunchArgs(program string, stopOnEntry bool, args []string) (map[string]any, func(), error) {
absProgram, err := filepath.Abs(program)
if err != nil {
return nil, nil, fmt.Errorf("resolving path: %w", err)
}
cwd, _ := os.Getwd()
m := map[string]any{
"request": "launch",
"program": absProgram,
"stopOnEntry": stopOnEntry,
"console": "internalConsole",
"cwd": cwd,
"justMyCode": false,
}
if len(args) > 0 {
m["args"] = args
}
return m, nil, nil
}
func (b *debugpyBackend) RemoteAttachArgs(host string, port int) (map[string]any, error) {
return map[string]any{
"request": "attach",
"justMyCode": false,
}, nil
}
func (b *debugpyBackend) PIDAttachArgs(pid int) (map[string]any, error) {
return map[string]any{
"request": "attach",
"processId": pid,
"justMyCode": false,
}, nil
}
// --- delve backend (Go) ---
type delveBackend struct{}
func (b *delveBackend) Spawn(port string) (*exec.Cmd, string, error) {
if runtime.GOOS == "darwin" {
if err := checkMacOSDevMode(); err != nil {
return nil, "", err
}
}
port, _ = normalizePort(port)
cmd := exec.Command("dlv", "dap", "--listen", port)
cmd.Stderr = nil
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, "", fmt.Errorf("creating stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, "", fmt.Errorf("starting dlv: %w", err)
}
addr, err := waitForReady(cmd, stdoutPipe, "DAP server listening at:", func(line string) string {
idx := strings.Index(line, "DAP server listening at:")
a := strings.TrimSpace(line[idx+len("DAP server listening at:"):])
if strings.HasPrefix(a, "[::]") {
a = "127.0.0.1" + a[4:]
}
return a
})
if err != nil {
return nil, "", fmt.Errorf("starting dlv: %w", err)
}
return cmd, addr, nil
}
func (b *delveBackend) TransportMode() string { return "tcp" }
func (b *delveBackend) AdapterID() string { return "go" }
func (b *delveBackend) StopOnEntryBreakpoint() string { return "main.main" }
func (b *delveBackend) LaunchArgs(program string, stopOnEntry bool, args []string) (map[string]any, func(), error) {
absProgram, err := filepath.Abs(program)
if err != nil {
return nil, nil, fmt.Errorf("resolving path: %w", err)
}
info, err := os.Stat(absProgram)
if err != nil {
return nil, nil, fmt.Errorf("stat: %w", err)
}
isGoSource := info.IsDir() || filepath.Ext(absProgram) == ".go"
var cleanupFn func()
if isGoSource {
// Pre-compile Go source with debug symbols, then use exec mode.
// This avoids module resolution issues in dlv DAP mode.
pkgDir := absProgram
if !info.IsDir() {
pkgDir = filepath.Dir(absProgram)
}
tmpBin, err := os.CreateTemp("", "dap-dlv-*")
if err != nil {
return nil, nil, fmt.Errorf("creating temp file: %w", err)
}
_ = tmpBin.Close()
build := exec.Command("go", "build", "-gcflags=all=-N -l", "-o", tmpBin.Name(), ".")
build.Dir = pkgDir
if out, err := build.CombinedOutput(); err != nil {
_ = os.Remove(tmpBin.Name())
return nil, nil, fmt.Errorf("compiling Go program: %s\n%s", err, out)
}
absProgram = tmpBin.Name()
cleanupFn = func() { _ = os.Remove(absProgram) }
}
m := map[string]any{
"request": "launch",
"mode": "exec",
"program": absProgram,
"stopOnEntry": false, // dlv exec mode can't stop before runtime init; use function breakpoints instead
}
if len(args) > 0 {
m["args"] = args
}
return m, cleanupFn, nil
}
func (b *delveBackend) RemoteAttachArgs(host string, port int) (map[string]any, error) {
return map[string]any{
"request": "attach",
"mode": "remote",
"host": host,
"port": port,
"substitutePath": []any{},
}, nil
}
// PIDAttachArgs for dlv uses "launch" with "local" mode (not "attach"),
// because dlv's DAP API requires this for local process attachment.
func (b *delveBackend) PIDAttachArgs(pid int) (map[string]any, error) {
return map[string]any{
"request": "launch",
"mode": "local",
"processId": pid,
}, nil
}
// checkMacOSDevMode verifies that macOS developer mode is enabled, which is
// required for dlv to debug processes via ptrace.
func checkMacOSDevMode() error {
out, err := exec.Command("DevToolsSecurity", "-status").CombinedOutput()
if err != nil {
// If the command doesn't exist or fails, skip the check
return nil
}
if strings.Contains(string(out), "enabled") {
return nil
}
return fmt.Errorf("macOS developer mode is disabled — dlv cannot debug programs without it.\n" +
"Enable it by running: sudo DevToolsSecurity -enable\n" +
"See: https://github.com/go-delve/delve/blob/master/Documentation/installation/README.md#macos-considerations")
}
// findLLDBDap searches for the lldb-dap binary.
// Returns the path or "" if not found.
func findLLDBDap() string {
// Prefer Homebrew LLVM on macOS (Xcode CLT ships v17 which lacks --connection)
for _, p := range []string{
"/opt/homebrew/opt/llvm/bin/lldb-dap",
"/usr/local/opt/llvm/bin/lldb-dap",
} {
if _, err := os.Stat(p); err == nil {
return p
}
}
// Fall back to PATH (catches Linux installs and custom locations)
if p, err := exec.LookPath("lldb-dap"); err == nil {
return p
}
return ""
}
// FindJSDebugServer searches for the js-debug DAP server script.
// Returns the path or "" if not found.
func FindJSDebugServer() string {
// Check env var first
if p := os.Getenv("DAP_JS_DEBUG_PATH"); p != "" {
if _, err := os.Stat(p); err == nil {
return p
}
}
// Search VS Code and Cursor extension dirs
home, err := os.UserHomeDir()
if err != nil {
return ""
}
// Check ~/.dap-cli standalone install
standalone := filepath.Join(home, ".dap-cli", "js-debug", "js-debug", "src", "dapDebugServer.js")
if _, err := os.Stat(standalone); err == nil {
return standalone
}
// Check VS Code and Cursor extension dirs
for _, dir := range []string{
filepath.Join(home, ".vscode", "extensions"),
filepath.Join(home, ".cursor", "extensions"),
} {
matches, _ := filepath.Glob(filepath.Join(dir, "ms-vscode.js-debug-*/src/dapDebugServer.js"))
if len(matches) > 0 {
return matches[len(matches)-1]
}
}
return ""
}
// --- lldb-dap backend (Rust/C/C++) ---
type lldbBackend struct{}
func (b *lldbBackend) Spawn(port string) (*exec.Cmd, string, error) {
binary := findLLDBDap()
if binary == "" {
return nil, "", fmt.Errorf("lldb-dap not found. Install: brew install llvm (macOS) or apt install lldb (Linux)")
}
_, actualPort := normalizePort(port)
cmd := exec.Command(binary, "--connection", fmt.Sprintf("listen://127.0.0.1:%s", actualPort))
cmd.Stderr = nil
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, "", fmt.Errorf("creating stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, "", fmt.Errorf("starting lldb-dap: %w", err)
}
addr, err := waitForReady(cmd, stdoutPipe, "Listening", func(line string) string {
if idx := strings.Index(line, "connection://"); idx >= 0 {
raw := line[idx+len("connection://"):]
raw = strings.ReplaceAll(raw, "[", "")
raw = strings.ReplaceAll(raw, "]", "")
return raw
}
return "127.0.0.1:" + actualPort
})
if err != nil {
return nil, "", fmt.Errorf("starting lldb-dap: %w", err)
}
return cmd, addr, nil
}
func (b *lldbBackend) TransportMode() string { return "tcp" }
func (b *lldbBackend) AdapterID() string { return "lldb-dap" }
func (b *lldbBackend) StopOnEntryBreakpoint() string { return "" } // native stopOnEntry works
func (b *lldbBackend) LaunchArgs(program string, stopOnEntry bool, args []string) (map[string]any, func(), error) {
absProgram, err := filepath.Abs(program)
if err != nil {
return nil, nil, fmt.Errorf("resolving path: %w", err)
}
var cleanupFn func()
ext := strings.ToLower(filepath.Ext(absProgram))
switch ext {
case ".rs":
// Compile Rust source with debug symbols
tmpBin, err := os.CreateTemp("", "dap-rust-*")
if err != nil {
return nil, nil, fmt.Errorf("creating temp file: %w", err)
}
_ = tmpBin.Close()
build := exec.Command("rustc", "-g", "-o", tmpBin.Name(), absProgram)
if out, err := build.CombinedOutput(); err != nil {
_ = os.Remove(tmpBin.Name())
return nil, nil, fmt.Errorf("compiling Rust program: %s\n%s", err, out)
}
absProgram = tmpBin.Name()
cleanupFn = func() { _ = os.Remove(absProgram) }
case ".c", ".cpp", ".cc":
// Compile C/C++ source with debug symbols
tmpBin, err := os.CreateTemp("", "dap-cc-*")
if err != nil {
return nil, nil, fmt.Errorf("creating temp file: %w", err)
}
_ = tmpBin.Close()
compiler := "cc"
if ext == ".cpp" || ext == ".cc" {
compiler = "c++"
}
build := exec.Command(compiler, "-g", "-o", tmpBin.Name(), absProgram)
if out, err := build.CombinedOutput(); err != nil {
_ = os.Remove(tmpBin.Name())
return nil, nil, fmt.Errorf("compiling C/C++ program: %s\n%s", err, out)
}
absProgram = tmpBin.Name()
cleanupFn = func() { _ = os.Remove(absProgram) }
}
m := map[string]any{
"program": absProgram,
"stopOnEntry": stopOnEntry,
}
if len(args) > 0 {
m["args"] = args
}
return m, cleanupFn, nil
}
func (b *lldbBackend) RemoteAttachArgs(host string, port int) (map[string]any, error) {
return nil, fmt.Errorf("lldb-dap does not support remote attach")
}
func (b *lldbBackend) PIDAttachArgs(pid int) (map[string]any, error) {
return map[string]any{
"request": "attach",
"pid": pid,
}, nil
}
// --- js-debug backend (Node.js/TypeScript) ---
type jsDebugBackend struct{}
func (b *jsDebugBackend) Spawn(port string) (*exec.Cmd, string, error) {
serverPath := FindJSDebugServer()
if serverPath == "" {
return nil, "", fmt.Errorf("js-debug not found. Install VS Code, set DAP_JS_DEBUG_PATH, or download from github.com/microsoft/vscode-js-debug/releases")
}
_, actualPort := normalizePort(port)
cmd := exec.Command("node", serverPath, actualPort)
cmd.Stderr = nil
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, "", fmt.Errorf("creating stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, "", fmt.Errorf("starting js-debug: %w", err)
}
addr, err := waitForReady(cmd, stdoutPipe, "Debug server listening at", func(line string) string {
parts := strings.Fields(line)
if len(parts) == 0 {
return "127.0.0.1:" + actualPort
}
raw := parts[len(parts)-1]
if idx := strings.LastIndex(raw, ":"); idx >= 0 {
p := raw[idx+1:]
host := raw[:idx]
if strings.Contains(host, ":") {
return "[" + host + "]:" + p
} else if host == "" {
return "127.0.0.1:" + p
}
return host + ":" + p
}
return "127.0.0.1:" + actualPort
})
if err != nil {
return nil, "", fmt.Errorf("starting js-debug: %w", err)
}
return cmd, addr, nil
}
func (b *jsDebugBackend) TransportMode() string { return "tcp" }
func (b *jsDebugBackend) AdapterID() string { return "pwa-node" }
func (b *jsDebugBackend) StopOnEntryBreakpoint() string { return "" }
func (b *jsDebugBackend) LaunchArgs(program string, stopOnEntry bool, args []string) (map[string]any, func(), error) {
absProgram, err := filepath.Abs(program)
if err != nil {
return nil, nil, fmt.Errorf("resolving path: %w", err)
}
cwd, _ := os.Getwd()
m := map[string]any{
"type": "pwa-node",
"request": "launch",
"program": absProgram,
"stopOnEntry": stopOnEntry,
"cwd": cwd,
}
if len(args) > 0 {
m["args"] = args
}
return m, nil, nil
}
func (b *jsDebugBackend) RemoteAttachArgs(host string, port int) (map[string]any, error) {
return map[string]any{
"type": "pwa-node",
"request": "attach",
"address": host,
"port": port,
}, nil
}
func (b *jsDebugBackend) PIDAttachArgs(pid int) (map[string]any, error) {
return map[string]any{
"type": "pwa-node",
"request": "attach",
"processId": pid,
}, nil
}