-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdaemon.go
More file actions
1633 lines (1457 loc) · 44.9 KB
/
Copy pathdaemon.go
File metadata and controls
1633 lines (1457 loc) · 44.9 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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dap
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
godap "github.com/google/go-dap"
)
// defaultSocketDir returns the directory for the daemon socket.
func defaultSocketDir() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".dap-cli")
}
// SessionSocketPath returns the socket path for a named session.
func SessionSocketPath(name string) string {
return filepath.Join(defaultSocketDir(), name+".sock")
}
// DefaultSocketPath returns the default socket path (session "default").
func DefaultSocketPath() string {
return SessionSocketPath("default")
}
// Daemon holds the stateful debug session.
type Daemon struct {
clientMu sync.Mutex // guards d.client pointer; never held during I/O
client *DAPClient
backend Backend
adapterCmd *exec.Cmd
// Async event dispatch
expectCh chan godap.Message
// Output buffer (bounded at write time)
mu sync.Mutex
outputLines []string // complete lines, capped at maxOutputLines
outputPartial strings.Builder // last incomplete line (no \n yet)
// Session state
threadID int
frameID int
frameIDs []int // DAP frame IDs for the current stop, indexed by stack position
captureOutput bool // only capture output after first stop
// Unverified breakpoint warnings, drained on next response
breakWarnings []string
// Requested breakpoint lines per file, for detecting line adjustments
requestedBreakLines map[string]map[int]bool
// Cleanup function for temp binaries (e.g. Go, Rust compilation)
cleanupFn func()
// Last debug args for restart
lastDebugArgs json.RawMessage
// Adapter address and config for child session creation (js-debug multi-session)
adapterAddr string
// sessionBreaks and sessionExceptionFilters are accessed from handler methods
// serialized by cmdMu. Interrupt commands (pause, stop) don't modify them.
// d.client is guarded by clientMu for pointer swaps (readLoop↔handlers).
sessionBreaks []Breakpoint // stored breakpoints for child session re-init
sessionExceptionFilters []string // stored exception filter IDs for child session re-init
// Command serialization: most commands hold cmdMu for their duration.
// Interrupt commands (pause, stop) skip it so they can run while a
// blocking command (continue/step/debug) is in progress.
cmdMu sync.Mutex
// Socket
listener net.Listener
socketPath string
// Idle timeout
idleTimer *time.Timer
}
const maxOutputLines = 200
const defaultIdleTimeout = 10 * time.Minute
const errNoSession = "no active debug session (program may have terminated) — run 'dap debug' to start a new session"
func errResponse(msg string) *Response {
return &Response{Status: "error", Error: msg}
}
func errResponsef(format string, args ...any) *Response {
return &Response{Status: "error", Error: fmt.Sprintf(format, args...)}
}
func (d *Daemon) requireSession() *Response {
if d.getClient() == nil {
return errResponse(errNoSession)
}
return nil
}
func (d *Daemon) getClient() *DAPClient {
d.clientMu.Lock()
defer d.clientMu.Unlock()
return d.client
}
func (d *Daemon) setClient(c *DAPClient) {
d.clientMu.Lock()
d.client = c
d.clientMu.Unlock()
}
func idleTimeout() time.Duration {
if v := os.Getenv("DAP_IDLE_TIMEOUT"); v != "" {
if d, err := time.ParseDuration(v); err == nil {
return d
}
}
return defaultIdleTimeout
}
// appendOutput appends text to the bounded output buffer. Called under mu.
func (d *Daemon) appendOutput(text string) {
if d.outputPartial.Len() > 0 {
text = d.outputPartial.String() + text
d.outputPartial.Reset()
}
lines := strings.Split(text, "\n")
d.outputLines = append(d.outputLines, lines[:len(lines)-1]...)
if len(d.outputLines) > maxOutputLines {
trimmed := make([]string, maxOutputLines)
copy(trimmed, d.outputLines[len(d.outputLines)-maxOutputLines:])
d.outputLines = trimmed
}
d.outputPartial.WriteString(lines[len(lines)-1])
}
// outputString returns buffered output as a string and clears the buffer. Called under mu.
func (d *Daemon) outputString() string {
lines := d.outputLines
if d.outputPartial.Len() > 0 {
lines = append(lines, d.outputPartial.String())
}
d.outputLines = nil
d.outputPartial.Reset()
return strings.Join(lines, "\n")
}
// addBreakWarning appends a warning about an unverified breakpoint.
func (d *Daemon) addBreakWarning(w string) {
d.mu.Lock()
d.breakWarnings = append(d.breakWarnings, w)
d.mu.Unlock()
}
// drainBreakWarnings returns accumulated warnings and clears them.
func (d *Daemon) drainBreakWarnings() []string {
d.mu.Lock()
defer d.mu.Unlock()
if len(d.breakWarnings) == 0 {
return nil
}
w := d.breakWarnings
d.breakWarnings = nil
return w
}
// attachWarnings drains any pending break warnings into a response.
func (d *Daemon) attachWarnings(resp *Response) {
warnings := d.drainBreakWarnings()
if len(warnings) == 0 {
return
}
if resp.Data == nil {
resp.Data = &ContextResult{}
}
resp.Data.Warnings = warnings
}
// recordRequestedBreaks stores the requested line numbers for a file,
// so we can detect line adjustments in SetBreakpointsResponse.
func (d *Daemon) recordRequestedBreaks(file string, breaks []Breakpoint) {
d.mu.Lock()
defer d.mu.Unlock()
if d.requestedBreakLines == nil {
d.requestedBreakLines = make(map[string]map[int]bool)
}
lines := make(map[int]bool, len(breaks))
for _, b := range breaks {
lines[b.Line] = true
}
d.requestedBreakLines[file] = lines
}
// checkBreakpointWarnings inspects a SetBreakpointsResponse for unverified
// or line-adjusted breakpoints and records warnings.
func (d *Daemon) checkBreakpointWarnings(m *godap.SetBreakpointsResponse) {
d.mu.Lock()
requested := d.requestedBreakLines
d.mu.Unlock()
for _, bp := range m.Body.Breakpoints {
if !bp.Verified {
w := fmt.Sprintf("breakpoint at line %d not verified", bp.Line)
if bp.Message != "" {
w = fmt.Sprintf("breakpoint at line %d not verified: %s", bp.Line, bp.Message)
}
d.addBreakWarning(w)
continue
}
// Check for line adjustment: adapter moved the breakpoint to a different line
if bp.Source != nil && requested != nil {
file := bp.Source.Path
if lines, ok := requested[file]; ok && !lines[bp.Line] {
// Find which requested line was adjusted
for reqLine := range lines {
// Heuristic: report adjusted if this response line wasn't requested
d.addBreakWarning(fmt.Sprintf("breakpoint at %s:%d was adjusted to line %d", filepath.Base(file), reqLine, bp.Line))
delete(lines, reqLine)
break
}
}
}
}
}
// readExpected reads the next expected message from the reader goroutine.
func (d *Daemon) readExpected() (godap.Message, error) {
msg, ok := <-d.expectCh
if !ok {
return nil, io.EOF
}
return msg, nil
}
// readLoop continuously reads DAP messages and dispatches them.
//
// Event dispatch (whitelist):
//
// ReadMessage()
// ├─ OutputEvent ──► buffer stdout/stderr (cap at maxOutputLines)
// ├─ StoppedEvent ──────┐
// ├─ TerminatedEvent ───┤
// ├─ InitializedEvent ──┼──► expectCh (consumed by waitForStopped, handleEval, etc.)
// ├─ ExitedEvent ───────┤
// ├─ ResponseMessage ───┘
// └─ default ──► DROP (ProcessEvent, ThreadEvent, ModuleEvent, etc.)
func (d *Daemon) readLoop() {
defer close(d.expectCh)
// Pin the client for this loop's lifetime: stopSession() sets d.client = nil,
// which would race with d.client.ReadMessage() here and panic. The client's
// Close() will unblock ReadMessage() with an error and the loop returns.
client := d.getClient()
if client == nil {
return
}
for {
msg, err := client.ReadMessage()
if err != nil {
return
}
switch m := msg.(type) {
case *godap.OutputEvent:
if d.captureOutput {
cat := m.Body.Category
if cat == "stdout" || cat == "stderr" {
d.mu.Lock()
d.appendOutput(m.Body.Output)
d.mu.Unlock()
}
}
case *godap.StoppedEvent, *godap.TerminatedEvent, *godap.InitializedEvent, *godap.ExitedEvent:
d.expectCh <- msg
case *godap.SetBreakpointsResponse:
d.checkBreakpointWarnings(m)
d.expectCh <- msg
case godap.ResponseMessage:
d.expectCh <- msg
case *godap.StartDebuggingRequest:
// Reverse request from js-debug to create a child debug session.
// js-debug uses multi-session: parent = session manager, child = actual debuggee.
// We respond with success, create a new connection for the child session,
// do full init (initialize → launch → breakpoints → configDone),
// and swap d.client so readLoop continues on the child.
resp := &godap.StartDebuggingResponse{}
resp.Type = "response"
resp.Command = m.Command
resp.RequestSeq = m.Seq
resp.Seq = 0
resp.Success = true
_ = d.client.send(resp)
if d.adapterAddr == "" {
log.Printf("startDebugging: no adapter address for child session")
continue
}
if err := d.setupChildSession(m.Arguments.Configuration); err != nil {
log.Printf("startDebugging: %v", err)
continue
}
default:
// Silently drop: ProcessEvent, ThreadEvent, ModuleEvent, ContinuedEvent, etc.
}
}
}
// waitForStopped waits for a StoppedEvent or TerminatedEvent, skipping responses and other events.
// ExitedEvent → captures exit code, continues waiting for TerminatedEvent.
// contextLines overrides the default source context window; 0 means use default.
func (d *Daemon) waitForStopped(contextLines int) (*ContextResult, error) {
var exitCode *int
for {
msg, err := d.readExpected()
if err != nil {
return nil, fmt.Errorf("debug adapter disconnected unexpectedly: %w", err)
}
switch m := msg.(type) {
case *godap.StoppedEvent:
d.threadID = resolveThreadID(m.Body.ThreadId)
ctx, err := getFullContext(d, d.threadID, 0, contextLines)
if err != nil {
return nil, fmt.Errorf("getting context: %w", err)
}
ctx.Reason = m.Body.Reason
// Fetch exception info when stopped on an exception
if m.Body.Reason == "exception" {
if err := d.client.ExceptionInfoRequest(d.threadID); err == nil {
if emsg, eerr := d.readExpected(); eerr == nil {
if eresp, ok := emsg.(*godap.ExceptionInfoResponse); ok && eresp.Success {
ctx.ExceptionInfo = &ExceptionInfo{
ExceptionID: eresp.Body.ExceptionId,
Description: eresp.Body.Description,
}
if eresp.Body.Details != nil {
ctx.ExceptionInfo.Details = eresp.Body.Details.Message
}
}
}
}
}
return ctx, nil
case *godap.ExitedEvent:
ec := m.Body.ExitCode
exitCode = &ec
case *godap.TerminatedEvent:
d.mu.Lock()
output := d.outputString()
d.mu.Unlock()
d.stopSession()
return &ContextResult{Output: output, ExitCode: exitCode}, nil
case godap.ResponseMessage:
if !m.GetResponse().Success {
return nil, fmt.Errorf("debugger error: %s", m.GetResponse().Message)
}
}
}
}
// Serve starts the daemon's Unix socket server.
func (d *Daemon) Serve(socketPath string) error {
d.socketPath = socketPath
// Ensure directory exists
if err := os.MkdirAll(filepath.Dir(socketPath), 0700); err != nil {
return fmt.Errorf("creating socket dir: %w", err)
}
// Remove stale socket
_ = os.Remove(socketPath)
listener, err := net.Listen("unix", socketPath)
if err != nil {
return fmt.Errorf("listening on %s: %w", socketPath, err)
}
d.listener = listener
// Write PID file
pidPath := socketPath + ".pid"
_ = os.WriteFile(pidPath, []byte(strconv.Itoa(os.Getpid())), 0600)
defer func() { _ = os.Remove(pidPath) }()
// Cleanup on signals
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
go func() {
<-sigCh
d.cleanup()
os.Exit(0)
}()
// Idle timeout: exit if no commands received within timeout
d.idleTimer = time.AfterFunc(idleTimeout(), func() {
log.Printf("daemon idle timeout, exiting")
d.cleanup()
os.Exit(0)
})
log.Printf("daemon listening on %s (pid %d)", socketPath, os.Getpid())
for {
conn, err := listener.Accept()
if err != nil {
if d.listener == nil {
return nil // shut down
}
// Closed listener during cleanup — exit silently
if strings.Contains(err.Error(), "use of closed") {
return nil
}
log.Printf("accept error: %v", err)
continue
}
go d.handleConnection(conn)
}
}
func (d *Daemon) handleConnection(conn net.Conn) {
defer func() { _ = conn.Close() }()
var req Request
if err := ReadIPC(conn, &req); err != nil {
log.Printf("read request: %v", err)
return
}
resp := d.dispatch(req)
if err := WriteIPC(conn, resp); err != nil {
log.Printf("write response: %v", err)
}
}
func (d *Daemon) dispatch(req Request) *Response {
if d.idleTimer != nil {
d.idleTimer.Reset(idleTimeout())
}
// Interrupt commands (pause, stop) run without holding cmdMu so they
// can execute while a blocking command (continue/step/debug) is in progress.
switch req.Command {
case "pause", "stop":
// no lock
default:
d.cmdMu.Lock()
defer d.cmdMu.Unlock()
}
resp := d.dispatchCommand(req)
if resp.Status != "error" {
d.attachWarnings(resp)
}
return resp
}
func (d *Daemon) dispatchCommand(req Request) *Response {
switch req.Command {
case "debug":
return d.handleDebug(req.Args)
case "step":
return d.handleStep(req.Args)
case "continue":
return d.handleContinue(req.Args)
case "context":
return d.handleContext(req.Args)
case "eval":
return d.handleEval(req.Args)
case "inspect":
return d.handleInspect(req.Args)
case "output":
return d.handleOutput(req.Args)
case "break_list":
return d.handleBreakList()
case "break_add":
return d.handleBreakAdd(req.Args)
case "break_remove":
return d.handleBreakRemove(req.Args)
case "break_clear":
return d.handleBreakClear()
case "pause":
return d.handlePause(req.Args)
case "threads":
return d.handleThreads()
case "thread":
return d.handleThread(req.Args)
case "restart":
return d.handleRestart()
case "stop":
return d.handleStop()
case "ping":
return &Response{Status: "ok"}
default:
return errResponsef("unknown command: %s", req.Command)
}
}
func (d *Daemon) handleDebug(rawArgs json.RawMessage) *Response {
var args DebugArgs
if err := json.Unmarshal(rawArgs, &args); err != nil {
return errResponsef("invalid args: %v", err)
}
// Store raw args and initialize session breaks for restart
d.lastDebugArgs = rawArgs
d.sessionBreaks = args.Breaks
d.sessionExceptionFilters = args.ExceptionFilters
// Select backend
var backend Backend
if args.Backend != "" {
var err error
backend, err = GetBackendByName(args.Backend)
if err != nil {
return errResponse(err.Error())
}
} else if args.Script != "" {
backend = DetectBackend(args.Script)
} else if args.Attach != "" {
return errResponse("backend required for remote attach (e.g. --backend debugpy)")
} else if args.PID > 0 {
return errResponse("backend required for PID attach (e.g. --backend debugpy)")
} else {
return errResponse("script path, --attach, or --pid required")
}
if b, ok := backend.(*debugpyBackend); ok && args.Python != "" {
b.python = args.Python
}
d.backend = backend
d.stopSession() // clean up any previous session
isRemote := args.Attach != ""
isPID := args.PID > 0
if isPID {
// PID attach: spawn local adapter, connect, initialize, then attach with PID args
if err := d.startAdapter(backend); err != nil {
return errResponse(err.Error())
}
if err := d.initializeDAP(backend); err != nil {
return errResponse(err.Error())
}
pidArgs, err := backend.PIDAttachArgs(args.PID)
if err != nil {
d.stopSession()
return errResponsef("preparing PID attach: %v", err)
}
if err := d.client.AttachRequestWithArgs(pidArgs); err != nil {
d.stopSession()
return errResponsef("PID attach: %v", err)
}
} else if isRemote {
// Connect directly to the remote DAP server
client, err := newDAPClient(args.Attach)
if err != nil {
return errResponsef("connecting to %s: %v", args.Attach, err)
}
d.setClient(client)
d.expectCh = make(chan godap.Message, 64)
go d.readLoop()
if err := d.initializeDAP(backend); err != nil {
return errResponse(err.Error())
}
host, portStr, splitErr := net.SplitHostPort(args.Attach)
if splitErr != nil {
d.stopSession()
return errResponsef("invalid attach address %q: %v", args.Attach, splitErr)
}
remotePort, _ := strconv.Atoi(portStr)
attachArgs, err := backend.RemoteAttachArgs(host, remotePort)
if err != nil {
d.stopSession()
return errResponsef("preparing attach: %v", err)
}
if err := d.client.AttachRequestWithArgs(attachArgs); err != nil {
d.stopSession()
return errResponsef("attach: %v", err)
}
} else {
// Local launch
if err := d.startAdapter(backend); err != nil {
return errResponse(err.Error())
}
if err := d.initializeDAP(backend); err != nil {
return errResponse(err.Error())
}
launchArgs, cleanupFn, err := backend.LaunchArgs(args.Script, args.StopOnEntry || len(args.Breaks) == 0, args.ProgramArgs)
if err != nil {
d.stopSession()
return errResponsef("preparing launch: %v", err)
}
d.cleanupFn = cleanupFn
if err := d.client.LaunchRequestWithArgs(launchArgs); err != nil {
d.stopSession()
return errResponsef("launch: %v", err)
}
}
// Wait for initialized event. The launch/attach response may arrive before or after
// initialized (adapter-dependent), so we consume both but only block on initialized.
initializedReceived := false
for !initializedReceived {
msg, err := d.readExpected()
if err != nil {
d.stopSession()
return errResponsef("waiting for initialized: %v", err)
}
switch m := msg.(type) {
case *godap.ErrorResponse:
errMsg := m.Message
if m.Body.Error != nil {
errMsg = m.Body.Error.Format
}
d.stopSession()
return errResponsef("request failed: %s", errMsg)
case *godap.ExitedEvent, *godap.TerminatedEvent:
d.stopSession()
return errResponse("debug adapter exited during initialization — check that the program path is valid and the debugger is installed")
case godap.ResponseMessage:
if !m.GetResponse().Success {
d.stopSession()
return errResponsef("request failed: %s", m.GetResponse().Message)
}
case *godap.InitializedEvent:
initializedReceived = true
}
}
// Send all config requests without waiting for individual responses.
// DAP is async — responses will be consumed by waitForStopped below.
stopOnEntry := !isRemote && !isPID && (args.StopOnEntry || len(args.Breaks) == 0)
entryBP := backend.StopOnEntryBreakpoint()
if stopOnEntry && entryBP != "" {
if err := d.client.SetFunctionBreakpointsRequest([]string{entryBP}); err != nil {
d.stopSession()
return errResponsef("set entry breakpoint: %v", err)
}
}
breaksByFile := groupBreakpoints(args.Breaks)
for file, bps := range breaksByFile {
d.recordRequestedBreaks(file, bps)
if err := d.client.SetBreakpointsRequest(file, bps); err != nil {
d.stopSession()
return errResponsef("set breakpoints: %v", err)
}
}
exceptionFilters := args.ExceptionFilters
if exceptionFilters == nil {
exceptionFilters = []string{}
}
if err := d.client.SetExceptionBreakpointsRequest(exceptionFilters); err != nil {
d.stopSession()
return errResponsef("set exception breakpoints: %v", err)
}
if err := d.client.ConfigurationDoneRequest(); err != nil {
d.stopSession()
return errResponsef("finalizing debug setup: %v", err)
}
// Wait for first stop. If we get an "entry" stop and have breakpoints, continue past it.
for {
ctx, err := d.waitForStopped(args.ContextLines)
if err != nil {
d.stopSession()
return errResponse(err.Error())
}
if ctx.Location == nil {
// terminated
return &Response{Status: "terminated", Data: ctx}
}
if len(args.Breaks) > 0 && !args.StopOnEntry && ctx.Reason == "entry" {
d.mu.Lock()
d.outputLines = nil
d.outputPartial.Reset()
d.mu.Unlock()
if err := d.client.ContinueRequest(d.threadID); err != nil {
d.stopSession()
return errResponsef("continue past entry: %v", err)
}
continue
}
ctx.Output = "" // discard launch noise
d.captureOutput = true
return &Response{Status: "stopped", Data: ctx}
}
}
// applyBreakpointUpdates processes breakpoint add/remove/exception filter changes.
// Returns nil on success, error *Response on failure.
func (d *Daemon) applyBreakpointUpdates(bu BreakpointUpdates) *Response {
if len(bu.Breaks) > 0 || len(bu.RemoveBreaks) > 0 {
if err := d.updateBreakpoints(bu.Breaks, bu.RemoveBreaks); err != nil {
return errResponsef("set breakpoints: %v", err)
}
}
if len(bu.ExceptionFilters) > 0 {
existing := make(map[string]bool)
for _, f := range d.sessionExceptionFilters {
existing[f] = true
}
for _, f := range bu.ExceptionFilters {
if !existing[f] {
d.sessionExceptionFilters = append(d.sessionExceptionFilters, f)
}
}
if err := d.client.SetExceptionBreakpointsRequest(d.sessionExceptionFilters); err != nil {
return errResponsef("set exception breakpoints: %v", err)
}
}
return nil
}
func (d *Daemon) handleStep(rawArgs json.RawMessage) *Response {
if resp := d.requireSession(); resp != nil {
return resp
}
var args StepArgs
if rawArgs != nil {
if err := json.Unmarshal(rawArgs, &args); err != nil {
return errResponsef("invalid args: %v", err)
}
}
if args.Mode == "" {
args.Mode = "over"
}
if errResp := d.applyBreakpointUpdates(args.BreakpointUpdates); errResp != nil {
return errResp
}
threadID := resolveThreadID(d.threadID)
switch args.Mode {
case "over":
if err := d.client.NextRequest(threadID); err != nil {
return errResponsef("step over: %v", err)
}
case "in":
if err := d.client.StepInRequest(threadID); err != nil {
return errResponsef("step in: %v", err)
}
case "out":
if err := d.client.StepOutRequest(threadID); err != nil {
return errResponsef("step out: %v", err)
}
default:
return errResponsef("invalid step mode %q — use: in, out, over", args.Mode)
}
return d.awaitStopResult(args.ContextLines)
}
func (d *Daemon) handleContinue(rawArgs json.RawMessage) *Response {
if resp := d.requireSession(); resp != nil {
return resp
}
var args ContinueArgs
if rawArgs != nil {
if err := json.Unmarshal(rawArgs, &args); err != nil {
return errResponsef("invalid args: %v", err)
}
}
if errResp := d.applyBreakpointUpdates(args.BreakpointUpdates); errResp != nil {
return errResp
}
// --to: add temp breakpoint before continuing
if args.ContinueTo != nil {
if err := d.updateBreakpoints([]Breakpoint{*args.ContinueTo}, nil); err != nil {
return errResponsef("set temp breakpoint: %v", err)
}
}
threadID := resolveThreadID(d.threadID)
if err := d.client.ContinueRequest(threadID); err != nil {
return errResponsef("continue: %v", err)
}
resp := d.awaitStopResult(args.ContextLines)
// --to: remove temp breakpoint after stop (whether stopped or terminated)
if args.ContinueTo != nil {
if d.getClient() != nil {
_ = d.updateBreakpoints(nil, []Breakpoint{*args.ContinueTo})
} else {
// Session ended — just clean sessionBreaks directly
d.sessionBreaks = mergeBreakpoints(d.sessionBreaks, nil, []Breakpoint{*args.ContinueTo})
}
}
return resp
}
func (d *Daemon) handlePause(rawArgs json.RawMessage) *Response {
if resp := d.requireSession(); resp != nil {
return resp
}
var args PauseArgs
if rawArgs != nil {
if err := json.Unmarshal(rawArgs, &args); err != nil {
return errResponsef("invalid args: %v", err)
}
}
if errResp := d.applyBreakpointUpdates(args.BreakpointUpdates); errResp != nil {
return errResp
}
threadID := resolveThreadID(d.threadID)
if err := d.client.PauseRequest(threadID); err != nil {
return errResponsef("pause: %v", err)
}
// Don't call awaitStopResult here — the already-blocking command
// (continue/step/debug) will consume the StoppedEvent and return
// the auto-context to its caller.
return &Response{Status: "ok"}
}
func (d *Daemon) handleContext(rawArgs json.RawMessage) *Response {
if resp := d.requireSession(); resp != nil {
return resp
}
var args ContextArgs
if rawArgs != nil {
if err := json.Unmarshal(rawArgs, &args); err != nil {
return errResponsef("invalid args: %v", err)
}
}
if errResp := d.applyBreakpointUpdates(args.BreakpointUpdates); errResp != nil {
return errResp
}
threadID := resolveThreadID(d.threadID)
ctx, err := getFullContext(d, threadID, args.Frame, args.ContextLines)
if err != nil {
return errResponse(err.Error())
}
return &Response{Status: "stopped", Data: ctx}
}
func (d *Daemon) handleInspect(rawArgs json.RawMessage) *Response {
if resp := d.requireSession(); resp != nil {
return resp
}
var args InspectArgs
if err := json.Unmarshal(rawArgs, &args); err != nil {
return errResponsef("invalid args: %v", err)
}
if args.Variable == "" {
return errResponse("variable name required")
}
if args.Depth <= 0 {
args.Depth = 1
}
if args.Depth > 5 {
args.Depth = 5
}
// Resolve target frame
frameID := d.frameID
if args.Frame > 0 {
if args.Frame >= len(d.frameIDs) {
return errResponsef("frame %d out of range (stack has %d frames)", args.Frame, len(d.frameIDs))
}
frameID = d.frameIDs[args.Frame]
}
// Get scopes
if err := d.client.ScopesRequest(frameID); err != nil {
return errResponsef("scopes request: %v", err)
}
var scopes []godap.Scope
for {
msg, err := d.readExpected()
if err != nil {
return errResponsef("reading scopes: %v", err)
}
if resp, ok := msg.(*godap.ScopesResponse); ok {
scopes = resp.Body.Scopes
break
}
if _, ok := msg.(*godap.ErrorResponse); ok {
break
}
}
// Search for variable: first in locals/arguments, then fall back to all scopes
isLocalScope := func(name string) bool {
name = strings.ToLower(name)
return strings.Contains(name, "local") || strings.Contains(name, "argument") ||
name == "locals" || name == "arguments"
}
searchScopes := func(filter func(string) bool) *Response {
for _, scope := range scopes {
if scope.VariablesReference == 0 {
continue
}
if filter != nil && !filter(scope.Name) {
continue
}
if err := d.client.VariablesRequest(scope.VariablesReference); err != nil {
continue
}
for {
msg, err := d.readExpected()
if err != nil {
break
}
if _, ok := msg.(*godap.ErrorResponse); ok {
break
}
resp, ok := msg.(*godap.VariablesResponse)
if !ok {
continue
}
if !resp.Success {
break
}
for _, v := range resp.Body.Variables {
if v.Name == args.Variable {
nodeCount := 1
result := InspectResult{
Name: v.Name,
Type: v.Type,
Value: truncateString(v.Value, maxStringLen),
}
if v.VariablesReference > 0 {
result.Children = expandVariable(d, v.VariablesReference, 0, args.Depth, &nodeCount, 100)
}
return &Response{
Status: "ok",
Data: &ContextResult{InspectResult: &result},
}
}
}
break
}
}
return nil
}
// First pass: locals/arguments only
if resp := searchScopes(isLocalScope); resp != nil {
return resp
}
// Second pass: all remaining scopes (globals, module, etc.)
if resp := searchScopes(func(name string) bool { return !isLocalScope(name) }); resp != nil {
return resp
}
return errResponsef("variable %q not found in current scope", args.Variable)
}
func (d *Daemon) handleEval(rawArgs json.RawMessage) *Response {
if resp := d.requireSession(); resp != nil {
return resp
}
var args EvalArgs
if err := json.Unmarshal(rawArgs, &args); err != nil {
return errResponsef("invalid args: %v", err)
}
if errResp := d.applyBreakpointUpdates(args.BreakpointUpdates); errResp != nil {
return errResp
}