Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 49 additions & 23 deletions daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,12 +258,17 @@ func (d *Daemon) readExpected() (godap.Message, error) {
// ├─ 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()
//
// The loop owns ch until it hands off to a child session (js-debug multi-session,
// see the startDebugging case); the client is pinned for the loop's lifetime
// because stopSession() sets d.client = nil, and Close() unblocks ReadMessage().
func (d *Daemon) readLoop(client *DAPClient, ch chan godap.Message) {
handedOff := false
defer func() {
if !handedOff {
close(ch)
}
}()
if client == nil {
return
}
Expand All @@ -272,6 +277,17 @@ func (d *Daemon) readLoop() {
if err != nil {
return
}
if handedOff {
// The child session owns the conversation and receives program output;
// the parent only mirrors the child's terminated event from here on.
// Keep draining so the adapter never blocks on a full send buffer, and
// decline further startDebugging requests rather than leave them unanswered.
if req, ok := msg.(*godap.StartDebuggingRequest); ok {
log.Printf("startDebugging: declined, a child session is already active")
_ = client.send(startDebuggingResponse(req, false))
}
continue
}
switch m := msg.(type) {
case *godap.OutputEvent:
if d.captureOutput {
Expand All @@ -283,40 +299,48 @@ func (d *Daemon) readLoop() {
}
}
case *godap.StoppedEvent, *godap.TerminatedEvent, *godap.InitializedEvent, *godap.ExitedEvent:
d.expectCh <- msg
ch <- msg
case *godap.SetBreakpointsResponse:
d.checkBreakpointWarnings(m)
d.expectCh <- msg
ch <- msg
case godap.ResponseMessage:
d.expectCh <- msg
ch <- 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)
// and hand d.client and ch to a read loop on the child connection.
_ = client.send(startDebuggingResponse(m, true))

if d.adapterAddr == "" {
log.Printf("startDebugging: no adapter address for child session")
continue
}
if err := d.setupChildSession(m.Arguments.Configuration); err != nil {
if err := d.setupChildSession(m.Arguments.Configuration, ch); err != nil {
log.Printf("startDebugging: %v", err)
continue
}
handedOff = true
default:
// Silently drop: ProcessEvent, ThreadEvent, ModuleEvent, ContinuedEvent, etc.
}
}
}

// startDebuggingResponse acknowledges (or declines) js-debug's startDebugging reverse request.
func startDebuggingResponse(req *godap.StartDebuggingRequest, ok bool) *godap.StartDebuggingResponse {
resp := &godap.StartDebuggingResponse{}
resp.Type = "response"
resp.Command = req.Command
resp.RequestSeq = req.Seq
resp.Success = ok
if !ok {
resp.Message = "a child session is already active"
}
return resp
}

// 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.
Expand Down Expand Up @@ -571,7 +595,7 @@ func (d *Daemon) handleDebug(rawArgs json.RawMessage) *Response {
}
d.setClient(client)
d.expectCh = make(chan godap.Message, 64)
go d.readLoop()
go d.readLoop(client, d.expectCh)

if err := d.initializeDAP(backend); err != nil {
return errResponse(err.Error())
Expand Down Expand Up @@ -1326,7 +1350,7 @@ func (d *Daemon) startAdapter(backend Backend) error {
}
d.setClient(client)
d.expectCh = make(chan godap.Message, 64)
go d.readLoop()
go d.readLoop(client, d.expectCh)
return nil
}

Expand Down Expand Up @@ -1358,8 +1382,8 @@ func (d *Daemon) initializeDAP(backend Backend) error {

// setupChildSession creates a child debug session for js-debug's multi-session architecture.
// It connects a new DAP client, initializes it, sends launch + breakpoints + configDone,
// and swaps d.client so readLoop continues reading from the child session.
func (d *Daemon) setupChildSession(config map[string]any) error {
// then swaps d.client to the child and starts a read loop on it that takes over ch.
func (d *Daemon) setupChildSession(config map[string]any, ch chan godap.Message) error {
childClient, err := newDAPClient(d.adapterAddr)
if err != nil {
return fmt.Errorf("connecting child session: %w", err)
Expand Down Expand Up @@ -1418,8 +1442,10 @@ func (d *Daemon) setupChildSession(config map[string]any) error {
log.Printf("child configuration done: %v", err)
}

// Swap to child session — readLoop continues reading from child
// Without a loop of its own, the child's StoppedEvent/TerminatedEvent would
// never reach ch and every execution command would block forever.
d.setClient(childClient)
go d.readLoop(childClient, ch)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Child failure can crash the daemon 📘 Rule violation ☼ Reliability

setupChildSession starts a child readLoop before the parent loop sets handedOff, while both
loops defer closing the same ch. If the child reaches EOF or fails during that window, it closes
ch; a subsequent parent event reaches ch <- msg and panics.
Agent Prompt
Issue description
The child reader starts before the parent reader marks the handoff complete, so both readers can close the shared channel. A fast child failure can close the channel first, after which the parent may send an event to the closed channel and panic.

Fix Focus Areas
- daemon.go[266-270]
- daemon.go[320-324]
- daemon.go[1445-1448]

Recommended Fix
Transfer channel-closure ownership atomically before starting the child reader, or centralize closure behind a synchronization primitive such as sync.Once. Ensure a child initialization failure leaves the parent as the sole channel owner and that no reader can send after closure.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

return nil
}

Expand Down
141 changes: 141 additions & 0 deletions daemon_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package dap

import (
"bufio"
"encoding/json"
"fmt"
"net"
"os/exec"
"strings"
"testing"
"time"

godap "github.com/google/go-dap"
)

func TestOutputBufferBoundedAtWrite(t *testing.T) {
Expand Down Expand Up @@ -492,3 +496,140 @@ func TestMergeBreakpoints(t *testing.T) {
})
}
}

// serveChildSession plays the child side of a js-debug style adapter: it answers
// the daemon's handshake on conn and emits a StoppedEvent once configurationDone
// arrives. It returns when the connection closes.
func serveChildSession(conn net.Conn) {
r := bufio.NewReader(conn)
seq := 100
next := func() int { seq++; return seq }
for {
msg, err := godap.ReadProtocolMessage(r)
if err != nil {
return
}
req, ok := msg.(godap.RequestMessage)
if !ok {
continue
}
cmd := req.GetRequest().Command
if cmd == "launch" {
_ = godap.WriteProtocolMessage(conn, &godap.InitializedEvent{
Event: godap.Event{ProtocolMessage: godap.ProtocolMessage{Seq: next(), Type: "event"}, Event: "initialized"},
})
}
_ = godap.WriteProtocolMessage(conn, &godap.Response{
ProtocolMessage: godap.ProtocolMessage{Seq: next(), Type: "response"},
RequestSeq: req.GetRequest().Seq,
Success: true,
Command: cmd,
})
if cmd == "configurationDone" {
_ = godap.WriteProtocolMessage(conn, &godap.StoppedEvent{
Event: godap.Event{ProtocolMessage: godap.ProtocolMessage{Seq: next(), Type: "event"}, Event: "stopped"},
Body: godap.StoppedEventBody{Reason: "breakpoint", ThreadId: 1},
})
}
}
}

// TestReadLoop_ChildSessionHandoff mirrors js-debug's multi-session protocol with
// a fake adapter: the parent connection only asks for a child session through the
// startDebugging reverse request, and the debuggee's events arrive on a second
// connection. Without a reader on that child connection the StoppedEvent below
// never reaches the channel and every execution command hangs. Needs no js-debug.
func TestReadLoop_ChildSessionHandoff(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()

d := &Daemon{backend: &jsDebugBackend{}, adapterAddr: ln.Addr().String()}

parentAck := make(chan godap.Message, 1)
go func() {
parent, err := ln.Accept()
if err != nil {
return
}
defer func() { _ = parent.Close() }()
_ = godap.WriteProtocolMessage(parent, &godap.StartDebuggingRequest{
Request: godap.Request{ProtocolMessage: godap.ProtocolMessage{Seq: 1, Type: "request"}, Command: "startDebugging"},
Arguments: godap.StartDebuggingRequestArguments{
Configuration: map[string]any{"type": "pwa-node", "name": "child"},
Request: "launch",
},
})
// The acknowledgement must come back on the parent connection.
ack, err := godap.ReadProtocolMessage(bufio.NewReader(parent))
if err != nil {
return
}
parentAck <- ack

child, err := ln.Accept()
if err != nil {
return
}
defer func() { _ = child.Close() }()
serveChildSession(child)
}()

parentClient, err := newDAPClient(ln.Addr().String())
if err != nil {
t.Fatal(err)
}
defer parentClient.Close()
d.setClient(parentClient)
ch := make(chan godap.Message, 64)
go d.readLoop(parentClient, ch)
Comment on lines +580 to +587

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

2. Handoff has no isolated client test 📘 Rule violation ⚙ Maintainability

TestReadLoop_ChildSessionHandoff drives a concrete DAPClient over TCP instead of mocking the DAP
client through an interface. The test therefore exercises the fake network adapter and reader
together, so client-level failures are not isolated at the unit-test boundary required for this
handoff.
Agent Prompt
Issue description
The new child-session handoff test constructs a real network-backed `DAPClient` and fake TCP adapter rather than testing the reader against an interface-backed mock. This does not provide the isolated DAP-client unit coverage required for the new behavior.

Fix Focus Areas
- daemon_test.go[542-587]
- daemon.go[265-324]

Recommended Fix
Introduce or use a narrow DAP client interface for the reader's required operations, provide a mock implementation in the unit test, and keep the TCP fake as an integration test. Assert the parent acknowledgement, child event delivery, and single channel closure through the isolated mock test.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


deadline := time.After(5 * time.Second)
var stopped *godap.StoppedEvent
for stopped == nil {
select {
case msg, ok := <-ch:
if !ok {
t.Fatal("channel closed before the child's StoppedEvent arrived")
}
stopped, _ = msg.(*godap.StoppedEvent)
case <-deadline:
t.Fatal("the child session's StoppedEvent never reached the channel")
}
}
if stopped.Body.Reason != "breakpoint" {
t.Errorf("stopped reason = %q, want breakpoint", stopped.Body.Reason)
}

select {
case ack := <-parentAck:
if _, ok := ack.(*godap.StartDebuggingResponse); !ok {
t.Errorf("parent connection received %T, want *godap.StartDebuggingResponse", ack)
}
case <-time.After(5 * time.Second):
t.Fatal("startDebugging was never acknowledged on the parent connection")
}

child := d.getClient()
if child == parentClient {
t.Fatal("d.client still points at the parent session")
}

// Ending both connections ends both loops; the channel must close exactly
// once (a second close would panic).
child.Close()
parentClient.Close()
deadline = time.After(5 * time.Second)
for {
select {
case _, ok := <-ch:
if !ok {
return
}
case <-deadline:
t.Fatal("channel was not closed after both connections ended")
}
}
}
60 changes: 60 additions & 0 deletions e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1135,6 +1135,66 @@ func TestE2E_DebugNode(t *testing.T) {
}
}

// TestE2E_DebugTypeScript debugs compiled JavaScript and breaks on a line of the
// original .ts source, covering the common TypeScript workflow end to end. Like
// TestE2E_DebugNode, it depends on the daemon reading js-debug's child session.
//
// The breakpoint is added after --stop-on-entry because a sub-second script can
// finish before a launch-time .ts breakpoint binds.
//
// testdata/node/ts/greet.js(.map) is committed so the test needs no compiler.
// Regenerate with: esbuild greet.ts --outfile=greet.js --format=cjs --platform=node --sourcemap
func TestE2E_DebugTypeScript(t *testing.T) {
if FindJSDebugServer() == "" {
t.Skip("js-debug not found")
}

env := newE2EEnv(t)
dir := filepath.Join(projectRoot(t), "testdata", "node", "ts")
program := filepath.Join(dir, "greet.js")
source := filepath.Join(dir, "greet.ts")

out, err := env.run("debug", program, "--stop-on-entry")
if err != nil {
t.Fatalf("debug failed: %v\n%s", err, out)
}
if !strings.Contains(out, "greet.ts") {
t.Errorf("expected entry location mapped to greet.ts, got:\n%s", out)
}

// greet.ts:8 is the return statement inside greet(); it compiles to greet.js:3.
if out, err = env.run("break", "add", source+":8"); err != nil {
t.Fatalf("break add failed: %v\n%s", err, out)
}

out, err = env.run("continue")
if err != nil {
t.Fatalf("continue failed: %v\n%s", err, out)
}
if !strings.Contains(out, "Stopped: breakpoint") || !strings.Contains(out, "greet.ts:8") {
t.Fatalf("expected to stop at greet.ts:8, got:\n%s", out)
}
if !strings.Contains(out, "adult") {
t.Errorf("expected local label=adult, got:\n%s", out)
}

out, err = env.run("continue")
if err != nil {
t.Fatalf("continue failed: %v\n%s", err, out)
}
if !strings.Contains(out, "terminated") {
t.Errorf("expected terminated, got:\n%s", out)
}

out, err = env.run("stop")
if err != nil {
t.Fatalf("stop failed: %v\n%s", err, out)
}
if !strings.Contains(out, "OK") {
t.Errorf("expected OK, got:\n%s", out)
}
}

// --- Remote attach tests ---

// TestE2E_RemoteAttach_Python tests attaching to a remote debugpy instance.
Expand Down
7 changes: 7 additions & 0 deletions testdata/node/ts/greet.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions testdata/node/ts/greet.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions testdata/node/ts/greet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
interface Person {
name: string;
age: number;
}

function greet(p: Person): string {
const label: string = p.age >= 18 ? "adult" : "minor";
return `Hello ${p.name} (${label})`;
}

const message: string = greet({ name: "Ada", age: 36 });
console.log(message);