server.go 76.3 KB
Newer Older
1 2 3 4 5 6 7 8
// Package dap implements VSCode's Debug Adaptor Protocol (DAP).
// This allows delve to communicate with frontends using DAP
// without a separate adaptor. The frontend will run the debugger
// (which now doubles as an adaptor) in server mode listening on
// a port and communicating over TCP. This is work in progress,
// so for now Delve in dap mode only supports synchronous
// request-response communication, blocking while processing each request.
// For DAP details see https://microsoft.github.io/debug-adapter-protocol.
9 10 11 12 13 14
package dap

import (
	"bufio"
	"encoding/json"
	"fmt"
15
	"go/constant"
16 17
	"io"
	"net"
18
	"os"
19
	"os/exec"
20
	"path/filepath"
21
	"reflect"
22
	"regexp"
23
	"runtime"
24
	"runtime/debug"
25
	"strings"
26
	"sync"
27

28
	"github.com/go-delve/delve/pkg/gobuild"
29
	"github.com/go-delve/delve/pkg/locspec"
30 31 32 33 34
	"github.com/go-delve/delve/pkg/logflags"
	"github.com/go-delve/delve/pkg/proc"
	"github.com/go-delve/delve/service"
	"github.com/go-delve/delve/service/api"
	"github.com/go-delve/delve/service/debugger"
35
	"github.com/google/go-dap"
36 37 38 39
	"github.com/sirupsen/logrus"
)

// Server implements a DAP server that can accept a single client for
40
// a single debug session (for now). It does not yet support restarting.
41 42 43 44 45 46
// That means that in addition to explicit shutdown requests,
// program termination and failed or closed client connection
// would also result in stopping this single-use server.
//
// The DAP server operates via the following goroutines:
//
47
// (1) Main goroutine where the server is created via NewServer(),
48 49 50 51 52 53 54 55
// started via Run() and stopped via Stop(). Once the server is
// started, this goroutine blocks until it receives a stop-server
// signal that can come from an OS interrupt (such as Ctrl-C) or
// config.DisconnectChan (passed to NewServer()) as a result of
// client connection failure or closure or a DAP disconnect request.
//
// (2) Run goroutine started from Run() that serves as both
// a listener and a client goroutine. It accepts a client connection,
56 57 58 59 60 61 62 63 64 65 66 67
// reads, decodes and dispatches each request from the client.
// For synchronous requests, it issues commands to the
// underlying debugger and sends back events and responses.
// These requests block while the debuggee is running, so,
// where applicable, the handlers need to check if debugging
// state is running, so there is a need for a halt request or
// a dummy/error response to avoid blocking.
//
// This is the only goroutine that sends a stop-server signal
// via config.DisconnecChan when encountering a client connection
// error or responding to a (synchronous) DAP disconnect request.
// Once stop is triggered, the goroutine exits.
68 69
//
// TODO(polina): add another layer of per-client goroutines to support multiple clients
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
//
// (3) Per-request goroutine is started for each asynchronous request
// that resumes execution. We check if target is running already, so
// there should be no more than one pending asynchronous request at
// a time. This goroutine issues commands to the underlying debugger
// and sends back events and responses. It takes a setup-done channel
// as an argument and temporarily blocks the request loop until setup
// for asynchronous execution is complete and targe is running.
// Once done, it unblocks processing of parallel requests unblocks
// (e.g. disconnecting while the program is running).
//
// These per-request goroutines never send a stop-server signal.
// They block on running debugger commands that are interrupted
// when halt is issued while stopping. At that point these goroutines
// wrap-up and exit.
85 86 87 88 89
type Server struct {
	// config is all the information necessary to start the debugger and server.
	config *service.Config
	// listener is used to accept the client connection.
	listener net.Listener
90
	// stopTriggered is closed when the server is Stop()-ed.
91
	stopTriggered chan struct{}
92 93 94 95
	// reader is used to read requests from the connection.
	reader *bufio.Reader
	// log is used for structured logging.
	log *logrus.Entry
96
	// stackFrameHandles maps frames of each goroutine to unique ids across all goroutines.
97
	// Reset at every stop.
98
	stackFrameHandles *handlesMap
99
	// variableHandles maps compound variables to unique references within their stack frame.
100
	// Reset at every stop.
101
	// See also comment for convertVariable.
102
	variableHandles *variablesHandlesMap
103 104
	// args tracks special settings for handling debug session requests.
	args launchAttachArgs
105

106 107
	// mu synchronizes access to objects set on start-up (from run goroutine)
	// and stopped on teardown (from main goroutine)
108
	mu sync.Mutex
109

110 111 112 113
	// conn is the accepted client connection.
	conn net.Conn
	// debugger is the underlying debugger service.
	debugger *debugger.Debugger
114 115
	// binaryToRemove is the temp compiled binary to be removed on disconnect (if any).
	binaryToRemove string
116 117
	// noDebugProcess is set for the noDebug launch process.
	noDebugProcess *exec.Cmd
118 119 120 121

	// sendingMu synchronizes writing to net.Conn
	// to ensure that messages do not get interleaved
	sendingMu sync.Mutex
122 123 124 125 126 127 128 129 130
}

// launchAttachArgs captures arguments from launch/attach request that
// impact handling of subsequent requests.
type launchAttachArgs struct {
	// stopOnEntry is set to automatically stop the debugee after start.
	stopOnEntry bool
	// stackTraceDepth is the maximum length of the returned list of stack frames.
	stackTraceDepth int
131 132
	// showGlobalVariables indicates if global package variables should be loaded.
	showGlobalVariables bool
133 134 135 136 137 138
	// substitutePathClientToServer indicates rules for converting file paths between client and debugger.
	// These must be directory paths.
	substitutePathClientToServer [][2]string
	// substitutePathServerToClient indicates rules for converting file paths between debugger and client.
	// These must be directory paths.
	substitutePathServerToClient [][2]string
139 140 141 142
}

// defaultArgs borrows the defaults for the arguments from the original vscode-go adapter.
var defaultArgs = launchAttachArgs{
143 144 145 146 147
	stopOnEntry:                  false,
	stackTraceDepth:              50,
	showGlobalVariables:          false,
	substitutePathClientToServer: [][2]string{},
	substitutePathServerToClient: [][2]string{},
148 149
}

150 151
// DefaultLoadConfig controls how variables are loaded from the target's memory, borrowing the
// default value from the original vscode-go debug adapter and rpc server.
152
// With dlv-dap, users currently do not have a way to adjust these.
153 154 155 156 157 158 159 160 161
// TODO(polina): Support setting config via launch/attach args or only rely on on-demand loading?
var DefaultLoadConfig = proc.LoadConfig{
	FollowPointers:     true,
	MaxVariableRecurse: 1,
	MaxStringLen:       64,
	MaxArrayValues:     64,
	MaxStructFields:    -1,
}

162
// NewServer creates a new DAP Server. It takes an opened Listener
163 164 165 166
// via config and assumes its ownership. config.DisconnectChan has to be set;
// it will be closed by the server when the client fails to connect,
// disconnects or requests shutdown. Once config.DisconnectChan is closed,
// Server.Stop() must be called to shutdown this single-user server.
167 168 169
func NewServer(config *service.Config) *Server {
	logger := logflags.DAPLogger()
	logflags.WriteDAPListeningMessage(config.Listener.Addr().String())
170
	logger.Debug("DAP server pid = ", os.Getpid())
171
	return &Server{
172 173
		config:            config,
		listener:          config.Listener,
174
		stopTriggered:     make(chan struct{}),
175 176
		log:               logger,
		stackFrameHandles: newHandlesMap(),
177
		variableHandles:   newVariablesHandlesMap(),
178
		args:              defaultArgs,
179 180 181
	}
}

182 183
// If user-specified options are provided via Launch/AttachRequest,
// we override the defaults for optional args.
184
func (s *Server) setLaunchAttachArgs(request dap.LaunchAttachRequest) error {
185 186 187 188 189 190 191 192 193 194 195 196
	stop, ok := request.GetArguments()["stopOnEntry"].(bool)
	if ok {
		s.args.stopOnEntry = stop
	}
	depth, ok := request.GetArguments()["stackTraceDepth"].(float64)
	if ok && depth > 0 {
		s.args.stackTraceDepth = int(depth)
	}
	globals, ok := request.GetArguments()["showGlobalVariables"].(bool)
	if ok {
		s.args.showGlobalVariables = globals
	}
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
	paths, ok := request.GetArguments()["substitutePath"]
	if ok {
		typeMismatchError := fmt.Errorf("'substitutePath' attribute '%v' in debug configuration is not a []{'from': string, 'to': string}", paths)
		pathsParsed, ok := paths.([]interface{})
		if !ok {
			return typeMismatchError
		}
		clientToServer := make([][2]string, 0, len(pathsParsed))
		serverToClient := make([][2]string, 0, len(pathsParsed))
		for _, arg := range pathsParsed {
			pathMapping, ok := arg.(map[string]interface{})
			if !ok {
				return typeMismatchError
			}
			from, ok := pathMapping["from"].(string)
			if !ok {
				return typeMismatchError
			}
			to, ok := pathMapping["to"].(string)
			if !ok {
				return typeMismatchError
			}
			clientToServer = append(clientToServer, [2]string{from, to})
			serverToClient = append(serverToClient, [2]string{to, from})
		}
		s.args.substitutePathClientToServer = clientToServer
		s.args.substitutePathServerToClient = serverToClient
	}
	return nil
226 227
}

228 229
// Stop stops the DAP debugger service, closes the listener and the client
// connection. It shuts down the underlying debugger and kills the target
230 231
// process if it was launched by it or stops the noDebug process.
// This method mustn't be called more than once.
232
func (s *Server) Stop() {
233
	s.log.Debug("DAP server stopping...")
234
	close(s.stopTriggered)
235
	_ = s.listener.Close()
236 237 238

	s.mu.Lock()
	defer s.mu.Unlock()
239 240 241 242 243
	if s.conn != nil {
		// Unless Stop() was called after serveDAPCodec()
		// returned, this will result in closed connection error
		// on next read, breaking out of the read loop and
		// allowing the run goroutine to exit.
244
		_ = s.conn.Close()
245
	}
246

247
	if s.debugger != nil {
248 249
		killProcess := s.config.Debugger.AttachPid == 0
		s.stopDebugSession(killProcess)
250 251
	} else {
		s.stopNoDebugProcess()
252
	}
253 254 255 256 257
	// The binary is no longer in use by the debugger. It is safe to remove it.
	if s.binaryToRemove != "" {
		gobuild.Remove(s.binaryToRemove)
		s.binaryToRemove = ""
	}
258
	s.log.Debug("DAP server stopped")
259 260
}

261 262 263 264 265
// triggerServerStop closes config.DisconnectChan if not nil, which
// signals that client sent a disconnect request or there was connection
// failure or closure. Since the server currently services only one
// client, this is used as a signal to stop the entire server.
// The function safeguards agaist closing the channel more
266 267
// than once and can be called multiple times. It is not thread-safe
// and is currently only called from the run goroutine.
268
func (s *Server) triggerServerStop() {
269 270 271 272
	// Avoid accidentally closing the channel twice and causing a panic, when
	// this function is called more than once. For example, we could have the
	// following sequence of events:
	// -- run goroutine: calls onDisconnectRequest()
273
	// -- run goroutine: calls triggerServerStop()
274
	// -- main goroutine: calls Stop()
275
	// -- main goroutine: Stop() closes client connection (or client closed it)
276
	// -- run goroutine: serveDAPCodec() gets "closed network connection"
277
	// -- run goroutine: serveDAPCodec() returns and calls triggerServerStop()
278 279 280 281
	if s.config.DisconnectChan != nil {
		close(s.config.DisconnectChan)
		s.config.DisconnectChan = nil
	}
282 283 284
	// There should be no logic here after the stop-server
	// signal that might cause everything to shutdown before this
	// logic gets executed.
285 286 287 288 289 290 291 292 293 294 295
}

// Run launches a new goroutine where it accepts a client connection
// and starts processing requests from it. Use Stop() to close connection.
// The server does not support multiple clients, serially or in parallel.
// The server should be restarted for every new debug session.
// The debugger won't be started until launch/attach request is received.
// TODO(polina): allow new client connections for new debug sessions,
// so the editor needs to launch delve only once?
func (s *Server) Run() {
	go func() {
296
		conn, err := s.listener.Accept() // listener is closed in Stop()
297
		if err != nil {
298
			select {
299
			case <-s.stopTriggered:
300 301
			default:
				s.log.Errorf("Error accepting client connection: %s\n", err)
302
				s.triggerServerStop()
303
			}
304 305
			return
		}
306 307 308
		s.mu.Lock()
		s.conn = conn // closed in Stop()
		s.mu.Unlock()
309 310 311 312 313 314
		s.serveDAPCodec()
	}()
}

// serveDAPCodec reads and decodes requests from the client
// until it encounters an error or EOF, when it sends
315
// a disconnect signal and returns.
316 317 318 319 320 321 322 323 324 325 326 327
func (s *Server) serveDAPCodec() {
	s.reader = bufio.NewReader(s.conn)
	for {
		request, err := dap.ReadProtocolMessage(s.reader)
		// TODO(polina): Differentiate between errors and handle them
		// gracefully. For example,
		// -- "Request command 'foo' is not supported" means we
		// potentially got some new DAP request that we do not yet have
		// decoding support for, so we can respond with an ErrorResponse.
		// TODO(polina): to support this add Seq to
		// dap.DecodeProtocolMessageFieldError.
		if err != nil {
328
			select {
329
			case <-s.stopTriggered:
330
			default:
331 332 333 334
				if err != io.EOF {
					s.log.Error("DAP error: ", err)
				}
				s.triggerServerStop()
335 336 337 338 339 340 341
			}
			return
		}
		s.handleRequest(request)
	}
}

342 343 344 345 346 347 348 349 350 351
// In case a handler panics, we catch the panic to avoid crashing both
// the server and the target. We send an error response back, but
// in case its a dup and ignored by the client, we also log the error.
func (s *Server) recoverPanic(request dap.Message) {
	if ierr := recover(); ierr != nil {
		s.log.Errorf("recovered panic: %s\n%s\n", ierr, debug.Stack())
		s.sendInternalErrorResponse(request.GetSeq(), fmt.Sprintf("%v", ierr))
	}
}

352
func (s *Server) handleRequest(request dap.Message) {
353
	defer s.recoverPanic(request)
354

355 356 357
	jsonmsg, _ := json.Marshal(request)
	s.log.Debug("[<- from client]", string(jsonmsg))

358 359 360 361 362 363
	if _, ok := request.(dap.RequestMessage); !ok {
		s.sendInternalErrorResponse(request.GetSeq(), fmt.Sprintf("Unable to process non-request %#v\n", request))
		return
	}

	// These requests, can be handeled regardless of whether the targret is running
364 365
	switch request := request.(type) {
	case *dap.DisconnectRequest:
366
		// Required
367
		s.onDisconnectRequest(request)
368 369 370 371 372 373
		return
	case *dap.PauseRequest:
		// Required
		// TODO: implement this request in V0
		s.onPauseRequest(request)
		return
374
	case *dap.TerminateRequest:
375 376 377
		// Optional (capability ‘supportsTerminateRequest‘)
		// TODO: implement this request in V1
		s.onTerminateRequest(request)
378
		return
379
	case *dap.RestartRequest:
380 381 382
		// Optional (capability ‘supportsRestartRequest’)
		// TODO: implement this request in V1
		s.onRestartRequest(request)
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
		return
	}

	// Most requests cannot be processed while the debuggee is running.
	// We have a couple of options for handling these without blocking
	// the request loop indefinitely when we are in running state.
	// --1-- Return a dummy response or an error right away.
	// --2-- Halt execution, process the request, resume execution.
	// TODO(polina): do this for setting breakpoints
	// --3-- Handle such requests asynchronously and let them block until
	// the process stops or terminates (e.g. using a channel and a single
	// goroutine to preserve the order). This might not be appropriate
	// for requests such as continue or step because they would skip
	// the stop, resuming execution right away. Other requests
	// might not be relevant anymore when the stop is finally reached, and
	// state changed from the previous snapshot. The user might want to
	// resume execution before the backlog of buffered requests is cleared,
	// so we would have to either cancel them or delay processing until
	// the next stop. In addition, the editor itself might block waiting
	// for these requests to return. We are not aware of any requests
	// that would benefit from this approach at this time.
	if s.debugger != nil && s.debugger.IsRunning() {
		switch request := request.(type) {
		case *dap.ThreadsRequest:
			// On start-up, the client requests the baseline of currently existing threads
			// right away as there are a number of DAP requests that require a thread id
			// (pause, continue, stacktrace, etc). This can happen after the program
			// continues on entry, preventing the client from handling any pause requests
			// from the user. We remedy this by sending back a placeholder thread id
			// for the current goroutine.
			response := &dap.ThreadsResponse{
				Response: *newResponse(request.Request),
				Body:     dap.ThreadsResponseBody{Threads: []dap.Thread{{Id: -1, Name: "Current"}}},
			}
			s.send(response)
		default:
			r := request.(dap.RequestMessage).GetRequest()
			s.sendErrorResponse(*r, DebuggeeIsRunning, fmt.Sprintf("Unable to process `%s`", r.Command), "debuggee is running")
		}
		return
	}

	// Requests below can only be handled while target is stopped.
	// Some of them are blocking and will be handled synchronously
	// on this goroutine while non-blocking requests will be dispatched
	// to another goroutine. Please note that because of the running
	// check above, there should be no more than one pending asynchronous
	// request at a time.

	// Non-blocking request handlers will signal when they are ready
	// setting up for async execution, so more requests can be processed.
	resumeRequestLoop := make(chan struct{})

	switch request := request.(type) {
	//--- Asynchronous requests ---
438
	case *dap.ConfigurationDoneRequest:
439
		// Optional (capability ‘supportsConfigurationDoneRequest’)
440 441 442 443 444
		go func() {
			defer s.recoverPanic(request)
			s.onConfigurationDoneRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
445
	case *dap.ContinueRequest:
446
		// Required
447 448 449 450 451
		go func() {
			defer s.recoverPanic(request)
			s.onContinueRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
452
	case *dap.NextRequest:
453
		// Required
454 455 456 457 458
		go func() {
			defer s.recoverPanic(request)
			s.onNextRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
459
	case *dap.StepInRequest:
460
		// Required
461 462 463 464 465
		go func() {
			defer s.recoverPanic(request)
			s.onStepInRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
466
	case *dap.StepOutRequest:
467
		// Required
468 469 470 471 472
		go func() {
			defer s.recoverPanic(request)
			s.onStepOutRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
473
	case *dap.StepBackRequest:
474 475 476
		// Optional (capability ‘supportsStepBack’)
		// TODO: implement this request in V1
		s.onStepBackRequest(request)
477
	case *dap.ReverseContinueRequest:
478 479 480
		// Optional (capability ‘supportsStepBack’)
		// TODO: implement this request in V1
		s.onReverseContinueRequest(request)
481 482
	//--- Synchronous requests ---
	case *dap.InitializeRequest:
483
		// Required
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
		s.onInitializeRequest(request)
	case *dap.LaunchRequest:
		// Required
		s.onLaunchRequest(request)
	case *dap.AttachRequest:
		// Required
		s.onAttachRequest(request)
	case *dap.SetBreakpointsRequest:
		// Required
		s.onSetBreakpointsRequest(request)
	case *dap.SetFunctionBreakpointsRequest:
		// Optional (capability ‘supportsFunctionBreakpoints’)
		// TODO: implement this request in V1
		s.onSetFunctionBreakpointsRequest(request)
	case *dap.SetExceptionBreakpointsRequest:
		// Optional (capability ‘exceptionBreakpointFilters’)
		s.onSetExceptionBreakpointsRequest(request)
	case *dap.ThreadsRequest:
		// Required
		s.onThreadsRequest(request)
504
	case *dap.StackTraceRequest:
505 506
		// Required
		s.onStackTraceRequest(request)
507
	case *dap.ScopesRequest:
508 509
		// Required
		s.onScopesRequest(request)
510
	case *dap.VariablesRequest:
511 512
		// Required
		s.onVariablesRequest(request)
513 514 515
	case *dap.EvaluateRequest:
		// Required
		s.onEvaluateRequest(request)
516
	case *dap.SetVariableRequest:
517 518 519 520
		// Optional (capability ‘supportsSetVariable’)
		// Supported by vscode-go
		// TODO: implement this request in V0
		s.onSetVariableRequest(request)
521
	case *dap.SetExpressionRequest:
522 523 524
		// Optional (capability ‘supportsSetExpression’)
		// TODO: implement this request in V1
		s.onSetExpressionRequest(request)
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
	case *dap.LoadedSourcesRequest:
		// Optional (capability ‘supportsLoadedSourcesRequest’)
		// TODO: implement this request in V1
		s.onLoadedSourcesRequest(request)
	case *dap.ReadMemoryRequest:
		// Optional (capability ‘supportsReadMemoryRequest‘)
		// TODO: implement this request in V1
		s.onReadMemoryRequest(request)
	case *dap.DisassembleRequest:
		// Optional (capability ‘supportsDisassembleRequest’)
		// TODO: implement this request in V1
		s.onDisassembleRequest(request)
	case *dap.CancelRequest:
		// Optional (capability ‘supportsCancelRequest’)
		// TODO: does this request make sense for delve?
		s.onCancelRequest(request)
	//--- Requests that we do not plan to support ---
	case *dap.RestartFrameRequest:
		// Optional (capability ’supportsRestartFrame’)
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.GotoRequest:
		// Optional (capability ‘supportsGotoTargetsRequest’)
		s.sendUnsupportedErrorResponse(request.Request)
548
	case *dap.SourceRequest:
549 550 551
		// Required
		// This does not make sense in the context of Go as
		// the source cannot be a string eval'ed at runtime.
552 553
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.TerminateThreadsRequest:
554
		// Optional (capability ‘supportsTerminateThreadsRequest’)
555 556
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.StepInTargetsRequest:
557
		// Optional (capability ‘supportsStepInTargetsRequest’)
558 559
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.GotoTargetsRequest:
560
		// Optional (capability ‘supportsGotoTargetsRequest’)
561 562
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.CompletionsRequest:
563
		// Optional (capability ‘supportsCompletionsRequest’)
564 565
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.ExceptionInfoRequest:
566 567
		// Optional (capability ‘supportsExceptionInfoRequest’)
		// TODO: does this request make sense for delve?
568 569
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.DataBreakpointInfoRequest:
570
		// Optional (capability ‘supportsDataBreakpoints’)
571 572
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.SetDataBreakpointsRequest:
573
		// Optional (capability ‘supportsDataBreakpoints’)
574 575
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.BreakpointLocationsRequest:
576 577 578 579 580
		// Optional (capability ‘supportsBreakpointLocationsRequest’)
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.ModulesRequest:
		// Optional (capability ‘supportsModulesRequest’)
		// TODO: does this request make sense for delve?
581 582 583 584
		s.sendUnsupportedErrorResponse(request.Request)
	default:
		// This is a DAP message that go-dap has a struct for, so
		// decoding succeeded, but this function does not know how
585 586
		// to handle.
		s.sendInternalErrorResponse(request.GetSeq(), fmt.Sprintf("Unable to process %#v\n", request))
587 588 589 590 591 592
	}
}

func (s *Server) send(message dap.Message) {
	jsonmsg, _ := json.Marshal(message)
	s.log.Debug("[-> to client]", string(jsonmsg))
593 594 595 596 597
	// TODO(polina): consider using a channel for all the sends and to have a dedicated
	// goroutine that reads from that channel and sends over the connection.
	// This will avoid blocking on slow network sends.
	s.sendingMu.Lock()
	defer s.sendingMu.Unlock()
598
	_ = dap.WriteProtocolMessage(s.conn, message)
599 600
}

601 602 603 604 605 606 607 608 609
func (s *Server) logToConsole(msg string) {
	s.send(&dap.OutputEvent{
		Event: *newEvent("output"),
		Body: dap.OutputEventBody{
			Output:   msg + "\n",
			Category: "console",
		}})
}

610
func (s *Server) onInitializeRequest(request *dap.InitializeRequest) {
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
	if request.Arguments.PathFormat != "path" {
		s.sendErrorResponse(request.Request, FailedToInitialize, "Failed to initialize",
			fmt.Sprintf("Unsupported 'pathFormat' value '%s'.", request.Arguments.PathFormat))
		return
	}
	if !request.Arguments.LinesStartAt1 {
		s.sendErrorResponse(request.Request, FailedToInitialize, "Failed to initialize",
			"Only 1-based line numbers are supported.")
		return
	}
	if !request.Arguments.ColumnsStartAt1 {
		s.sendErrorResponse(request.Request, FailedToInitialize, "Failed to initialize",
			"Only 1-based column numbers are supported.")
		return
	}

627 628 629
	// TODO(polina): Respond with an error if debug session is in progress?
	response := &dap.InitializeResponse{Response: *newResponse(request.Request)}
	response.Body.SupportsConfigurationDoneRequest = true
630
	response.Body.SupportsConditionalBreakpoints = true
631
	response.Body.SupportsDelayedStackTraceLoading = true
632
	response.Body.SupportTerminateDebuggee = true
633 634
	// TODO(polina): support this to match vscode-go functionality
	response.Body.SupportsSetVariable = false
635 636 637 638 639 640 641 642 643 644
	// TODO(polina): support these requests in addition to vscode-go feature parity
	response.Body.SupportsTerminateRequest = false
	response.Body.SupportsRestartRequest = false
	response.Body.SupportsFunctionBreakpoints = false
	response.Body.SupportsStepBack = false
	response.Body.SupportsSetExpression = false
	response.Body.SupportsLoadedSourcesRequest = false
	response.Body.SupportsReadMemoryRequest = false
	response.Body.SupportsDisassembleRequest = false
	response.Body.SupportsCancelRequest = false
645 646 647
	s.send(response)
}

648 649 650
// Default output file pathname for the compiled binary in debug or test modes,
// relative to the current working directory of the server.
const defaultDebugBinary string = "./__debug_bin"
651

652 653 654 655 656 657 658
func cleanExeName(name string) string {
	if runtime.GOOS == "windows" && filepath.Ext(name) != ".exe" {
		return name + ".exe"
	}
	return name
}

659
func (s *Server) onLaunchRequest(request *dap.LaunchRequest) {
660 661 662 663 664 665 666 667 668 669 670
	// Validate launch request mode
	mode, ok := request.Arguments["mode"]
	if !ok || mode == "" {
		mode = "debug"
	}
	if !isValidLaunchMode(mode) {
		s.sendErrorResponse(request.Request,
			FailedToLaunch, "Failed to launch",
			fmt.Sprintf("Unsupported 'mode' value %q in debug configuration.", mode))
		return
	}
671

672
	// TODO(polina): Respond with an error if debug session is in progress?
673
	program, ok := request.Arguments["program"].(string)
674 675
	if !ok || program == "" {
		s.sendErrorResponse(request.Request,
676
			FailedToLaunch, "Failed to launch",
677 678 679 680
			"The program attribute is missing in debug configuration.")
		return
	}

681 682 683
	if mode == "debug" || mode == "test" {
		output, ok := request.Arguments["output"].(string)
		if !ok || output == "" {
684
			output = cleanExeName(defaultDebugBinary)
685
		}
686
		debugbinary, err := filepath.Abs(output)
687 688 689 690 691
		if err != nil {
			s.sendInternalErrorResponse(request.Seq, err.Error())
			return
		}

692 693 694 695 696 697
		buildFlags := ""
		buildFlagsArg, ok := request.Arguments["buildFlags"]
		if ok {
			buildFlags, ok = buildFlagsArg.(string)
			if !ok {
				s.sendErrorResponse(request.Request,
698
					FailedToLaunch, "Failed to launch",
699 700 701
					fmt.Sprintf("'buildFlags' attribute '%v' in debug configuration is not a string.", buildFlagsArg))
				return
			}
702 703
		}

704
		s.log.Debugf("building binary at %s", debugbinary)
705
		var out []byte
706 707
		switch mode {
		case "debug":
708
			out, err = gobuild.GoBuildCombinedOutput(debugbinary, []string{program}, buildFlags)
709
		case "test":
710
			out, err = gobuild.GoTestBuildCombinedOutput(debugbinary, []string{program}, buildFlags)
711 712 713
		}
		if err != nil {
			s.sendErrorResponse(request.Request,
714
				FailedToLaunch, "Failed to launch",
715
				fmt.Sprintf("Build error: %s (%s)", strings.TrimSpace(string(out)), err.Error()))
716 717
			return
		}
718
		program = debugbinary
719
		s.mu.Lock()
720
		s.binaryToRemove = debugbinary
721
		s.mu.Unlock()
722 723
	}

724 725 726 727 728 729 730
	err := s.setLaunchAttachArgs(request)
	if err != nil {
		s.sendErrorResponse(request.Request,
			FailedToLaunch, "Failed to launch",
			err.Error())
		return
	}
731

732 733 734 735 736 737
	var targetArgs []string
	args, ok := request.Arguments["args"]
	if ok {
		argsParsed, ok := args.([]interface{})
		if !ok {
			s.sendErrorResponse(request.Request,
738
				FailedToLaunch, "Failed to launch",
739 740 741 742 743 744 745
				fmt.Sprintf("'args' attribute '%v' in debug configuration is not an array.", args))
			return
		}
		for _, arg := range argsParsed {
			argParsed, ok := arg.(string)
			if !ok {
				s.sendErrorResponse(request.Request,
746
					FailedToLaunch, "Failed to launch",
747 748 749 750 751 752 753 754
					fmt.Sprintf("value '%v' in 'args' attribute in debug configuration is not a string.", arg))
				return
			}
			targetArgs = append(targetArgs, argParsed)
		}
	}

	s.config.ProcessArgs = append([]string{program}, targetArgs...)
755
	s.config.Debugger.WorkingDir = filepath.Dir(program)
756

757
	// Set the WorkingDir for this program to the one specified in the request arguments.
758
	wd, ok := request.Arguments["cwd"]
759 760 761 762 763
	if ok {
		wdParsed, ok := wd.(string)
		if !ok {
			s.sendErrorResponse(request.Request,
				FailedToLaunch, "Failed to launch",
764
				fmt.Sprintf("'cwd' attribute '%v' in debug configuration is not a string.", wd))
765 766 767 768 769
			return
		}
		s.config.Debugger.WorkingDir = wdParsed
	}

770
	s.log.Debugf("running program in %s\n", s.config.Debugger.WorkingDir)
771
	if noDebug, ok := request.Arguments["noDebug"].(bool); ok && noDebug {
772
		s.mu.Lock()
773
		cmd, err := s.startNoDebugProcess(program, targetArgs, s.config.Debugger.WorkingDir)
774
		s.mu.Unlock()
775 776
		if err != nil {
			s.sendErrorResponse(request.Request, FailedToLaunch, "Failed to launch", err.Error())
777 778
			return
		}
779 780 781 782 783 784
		// Skip 'initialized' event, which will prevent the client from sending
		// debug-related requests.
		s.send(&dap.LaunchResponse{Response: *newResponse(request.Request)})

		// Then, block until the program terminates or is stopped.
		if err := cmd.Wait(); err != nil {
785
			s.log.Debugf("program exited with error: %v", err)
786 787 788 789 790 791 792 793
		}
		stopped := false
		s.mu.Lock()
		stopped = s.noDebugProcess == nil // if it was stopped, this should be nil.
		s.noDebugProcess = nil
		s.mu.Unlock()

		if !stopped {
794
			s.logToConsole(proc.ErrProcessExited{Pid: cmd.ProcessState.Pid(), Status: cmd.ProcessState.ExitCode()}.Error())
795 796 797
			s.send(&dap.TerminatedEvent{Event: *newEvent("terminated")})
		}
		return
798
	}
799

800 801 802 803 804 805
	func() {
		s.mu.Lock()
		defer s.mu.Unlock() // Make sure to unlock in case of panic that will become internal error
		s.debugger, err = debugger.New(&s.config.Debugger, s.config.ProcessArgs)
	}()
	if err != nil {
806
		s.sendErrorResponse(request.Request, FailedToLaunch, "Failed to launch", err.Error())
807 808
		return
	}
809 810 811 812

	// Notify the client that the debugger is ready to start accepting
	// configuration requests for setting breakpoints, etc. The client
	// will end the configuration sequence with 'configurationDone'.
813 814 815 816
	s.send(&dap.InitializedEvent{Event: *newEvent("initialized")})
	s.send(&dap.LaunchResponse{Response: *newResponse(request.Request)})
}

817 818
// startNoDebugProcess is called from onLaunchRequest (run goroutine) and
// requires holding mu lock.
819
func (s *Server) startNoDebugProcess(program string, targetArgs []string, wd string) (*exec.Cmd, error) {
820
	if s.noDebugProcess != nil {
821
		return nil, fmt.Errorf("another launch request is in progress")
822
	}
823 824
	cmd := exec.Command(program, targetArgs...)
	cmd.Stdout, cmd.Stderr, cmd.Stdin, cmd.Dir = os.Stdout, os.Stderr, os.Stdin, wd
825
	if err := cmd.Start(); err != nil {
826
		return nil, err
827 828
	}
	s.noDebugProcess = cmd
829
	return cmd, nil
830 831
}

832 833
// stopNoDebugProcess is called from Stop (main goroutine) and
// onDisconnectRequest (run goroutine) and requires holding mu lock.
834
func (s *Server) stopNoDebugProcess() {
835
	if s.noDebugProcess == nil {
836 837 838
		// We already handled termination or there was never a process
		return
	}
839 840
	if s.noDebugProcess.ProcessState.Exited() {
		s.logToConsole(proc.ErrProcessExited{Pid: s.noDebugProcess.ProcessState.Pid(), Status: s.noDebugProcess.ProcessState.ExitCode()}.Error())
841 842
	} else {
		// TODO(hyangah): gracefully terminate the process and its children processes.
843 844
		s.logToConsole(fmt.Sprintf("Terminating process %d", s.noDebugProcess.Process.Pid))
		s.noDebugProcess.Process.Kill() // Don't check error. Process killing and self-termination may race.
845
	}
846
	s.noDebugProcess = nil
847 848
}

849 850 851 852 853 854 855 856 857 858
// TODO(polina): support "remote" mode
func isValidLaunchMode(launchMode interface{}) bool {
	switch launchMode {
	case "exec", "debug", "test":
		return true
	}

	return false
}

859 860 861 862
// onDisconnectRequest handles the DisconnectRequest. Per the DAP spec,
// it disconnects the debuggee and signals that the debug adaptor
// (in our case this TCP server) can be terminated.
func (s *Server) onDisconnectRequest(request *dap.DisconnectRequest) {
863 864 865 866
	defer s.triggerServerStop()
	s.mu.Lock()
	defer s.mu.Unlock()

867
	var err error
868
	if s.debugger != nil {
869
		// We always kill launched programs.
870
		// In case of attach, we leave the program
871
		// running by default, which can be
872
		// overridden by an explicit request to terminate.
873 874
		killProcess := s.config.Debugger.AttachPid == 0 || request.Arguments.TerminateDebuggee
		err = s.stopDebugSession(killProcess)
875 876
	} else {
		s.stopNoDebugProcess()
877
	}
878
	if err != nil {
879 880 881 882
		s.sendErrorResponse(request.Request, DisconnectError, "Error while disconnecting", err.Error())
	} else {
		s.send(&dap.DisconnectResponse{Response: *newResponse(request.Request)})
	}
883
}
884

885 886 887 888 889 890 891 892 893
// stopDebugSession is called from Stop (main goroutine) and
// onDisconnectRequest (run goroutine) and requires holding mu lock.
// Returns any detach error other than proc.ErrProcessExited.
func (s *Server) stopDebugSession(killProcess bool) error {
	if s.debugger == nil {
		return nil
	}
	var err error
	var exited error
894 895 896 897 898 899
	// Halting will stop any debugger command that's pending on another
	// per-request goroutine, hence unblocking that goroutine to wrap-up and exit.
	// TODO(polina): Per-request goroutine could still not be done when this one is.
	// To avoid goroutine leaks, we can use a wait group or have the goroutine listen
	// for a stop signal on a dedicated quit channel at suitable points (use context?).
	// Additional clean-up might be especially critical when we support multiple clients.
900 901
	state, err := s.debugger.Command(&api.DebuggerCommand{Name: api.Halt}, nil)
	if err == proc.ErrProcessDetached {
902
		s.log.Debug("halt returned error:", err)
903 904 905 906 907 908 909
		return nil
	}
	if err != nil {
		switch err.(type) {
		case proc.ErrProcessExited:
			exited = err
		default:
910
			s.log.Error("halt returned error:", err)
911 912 913
		}
	} else if state.Exited {
		exited = proc.ErrProcessExited{Pid: s.debugger.ProcessPid(), Status: state.ExitStatus}
914
		s.log.Debug("halt returned state:", exited)
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
	}
	if exited != nil {
		s.logToConsole(exited.Error())
		s.logToConsole("Detaching")
	} else if killProcess {
		s.logToConsole("Detaching and terminating target process")
	} else {
		s.logToConsole("Detaching without terminating target processs")
	}
	err = s.debugger.Detach(killProcess)
	s.debugger = nil
	if err != nil {
		switch err.(type) {
		case proc.ErrProcessExited:
			s.log.Debug(err)
			s.logToConsole(exited.Error())
			err = nil
		default:
			s.log.Error(err)
		}
	}
	return err
937 938
}

939 940 941 942 943 944
func (s *Server) isNoDebug() bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.noDebugProcess != nil
}

945
func (s *Server) onSetBreakpointsRequest(request *dap.SetBreakpointsRequest) {
946
	if s.isNoDebug() {
947 948 949
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", "running in noDebug mode")
		return
	}
950

951
	if request.Arguments.Source.Path == "" {
952 953 954 955
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", "empty file path")
		return
	}

956 957 958
	clientPath := request.Arguments.Source.Path
	serverPath := s.toServerPath(clientPath)

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
	// According to the spec we should "set multiple breakpoints for a single source
	// and clear all previous breakpoints in that source." The simplest way is
	// to clear all and then set all.
	//
	// TODO(polina): should we optimize this as follows?
	// See https://github.com/golang/vscode-go/issues/163 for details.
	// If a breakpoint:
	// -- exists and not in request => ClearBreakpoint
	// -- exists and in request => AmendBreakpoint
	// -- doesn't exist and in request => SetBreakpoint

	// Clear all existing breakpoints in the file.
	existing := s.debugger.Breakpoints()
	for _, bp := range existing {
		// Skip special breakpoints such as for panic.
		if bp.ID < 0 {
			continue
		}
		// Skip other source files.
		// TODO(polina): should this be normalized because of different OSes?
979
		if bp.File != serverPath {
980 981 982 983 984 985 986
			continue
		}
		_, err := s.debugger.ClearBreakpoint(bp)
		if err != nil {
			s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", err.Error())
			return
		}
987
	}
988 989

	// Set all requested breakpoints.
990 991
	response := &dap.SetBreakpointsResponse{Response: *newResponse(request.Request)}
	response.Body.Breakpoints = make([]dap.Breakpoint, len(request.Arguments.Breakpoints))
992 993
	for i, want := range request.Arguments.Breakpoints {
		got, err := s.debugger.CreateBreakpoint(
994
			&api.Breakpoint{File: serverPath, Line: want.Line, Cond: want.Condition})
995
		response.Body.Breakpoints[i].Verified = (err == nil)
996
		if err != nil {
997 998 999
			response.Body.Breakpoints[i].Line = want.Line
			response.Body.Breakpoints[i].Message = err.Error()
		} else {
1000
			response.Body.Breakpoints[i].Id = got.ID
1001
			response.Body.Breakpoints[i].Line = got.Line
1002
			response.Body.Breakpoints[i].Source = dap.Source{Name: request.Arguments.Source.Name, Path: clientPath}
1003 1004 1005 1006 1007 1008 1009
		}
	}
	s.send(response)
}

func (s *Server) onSetExceptionBreakpointsRequest(request *dap.SetExceptionBreakpointsRequest) {
	// Unlike what DAP documentation claims, this request is always sent
1010
	// even though we specified no filters at initialization. Handle as no-op.
1011 1012 1013
	s.send(&dap.SetExceptionBreakpointsResponse{Response: *newResponse(request.Request)})
}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
func (s *Server) asyncCommandDone(asyncSetupDone chan struct{}) {
	if asyncSetupDone != nil {
		select {
		case <-asyncSetupDone:
			// already closed
		default:
			close(asyncSetupDone)
		}
	}
}

// onConfigurationDoneRequest handles 'configurationDone' request.
// This is an optional request enabled by capability ‘supportsConfigurationDoneRequest’.
// It gets triggered after all the debug requests that followinitalized event,
// so the s.debugger is guaranteed to be set.
func (s *Server) onConfigurationDoneRequest(request *dap.ConfigurationDoneRequest, asyncSetupDone chan struct{}) {
	defer s.asyncCommandDone(asyncSetupDone)
	if s.args.stopOnEntry {
1032 1033
		e := &dap.StoppedEvent{
			Event: *newEvent("stopped"),
1034
			Body:  dap.StoppedEventBody{Reason: "entry", ThreadId: 1, AllThreadsStopped: true},
1035 1036 1037 1038
		}
		s.send(e)
	}
	s.send(&dap.ConfigurationDoneResponse{Response: *newResponse(request.Request)})
1039 1040
	if !s.args.stopOnEntry {
		s.doCommand(api.Continue, asyncSetupDone)
1041 1042 1043
	}
}

1044 1045 1046
// onContinueRequest handles 'continue' request.
// This is a mandatory request to support.
func (s *Server) onContinueRequest(request *dap.ContinueRequest, asyncSetupDone chan struct{}) {
1047 1048 1049
	s.send(&dap.ContinueResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ContinueResponseBody{AllThreadsContinued: true}})
1050
	s.doCommand(api.Continue, asyncSetupDone)
1051 1052
}

1053 1054 1055 1056 1057 1058 1059
func fnName(loc *proc.Location) string {
	if loc.Fn == nil {
		return "???"
	}
	return loc.Fn.Name
}

1060 1061 1062
// onThreadsRequest handles 'threads' request.
// This is a mandatory request to support.
// It is sent in response to configurationDone response and stopped events.
1063 1064 1065 1066 1067
func (s *Server) onThreadsRequest(request *dap.ThreadsRequest) {
	if s.debugger == nil {
		s.sendErrorResponse(request.Request, UnableToDisplayThreads, "Unable to display threads", "debugger is nil")
		return
	}
1068

1069 1070 1071
	gs, _, err := s.debugger.Goroutines(0, 0)
	if err != nil {
		switch err.(type) {
1072
		case proc.ErrProcessExited:
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
			// If the program exits very quickly, the initial threads request will complete after it has exited.
			// A TerminatedEvent has already been sent. Ignore the err returned in this case.
			s.send(&dap.ThreadsResponse{Response: *newResponse(request.Request)})
		default:
			s.sendErrorResponse(request.Request, UnableToDisplayThreads, "Unable to display threads", err.Error())
		}
		return
	}

	threads := make([]dap.Thread, len(gs))
	if len(threads) == 0 {
		// Depending on the debug session stage, goroutines information
		// might not be available. However, the DAP spec states that
		// "even if a debug adapter does not support multiple threads,
		// it must implement the threads request and return a single
		// (dummy) thread".
		threads = []dap.Thread{{Id: 1, Name: "Dummy"}}
	} else {
1091 1092 1093 1094 1095 1096 1097 1098
		state, err := s.debugger.State( /*nowait*/ true)
		if err != nil {
			s.sendErrorResponse(request.Request, UnableToDisplayThreads, "Unable to display threads", err.Error())
			return
		}
		s.debugger.LockTarget()
		defer s.debugger.UnlockTarget()

1099
		for i, g := range gs {
1100 1101 1102 1103 1104 1105 1106
			selected := ""
			if state.SelectedGoroutine != nil && g.ID == state.SelectedGoroutine.ID {
				selected = "* "
			}
			thread := ""
			if g.Thread != nil && g.Thread.ThreadID() != 0 {
				thread = fmt.Sprintf(" (Thread %d)", g.Thread.ThreadID())
1107
			}
1108 1109 1110 1111 1112
			// File name and line number are communicated via `stackTrace`
			// so no need to include them here.
			loc := g.UserCurrent()
			threads[i].Name = fmt.Sprintf("%s[Go %d] %s%s", selected, g.ID, fnName(&loc), thread)
			threads[i].Id = g.ID
1113 1114 1115 1116 1117 1118 1119 1120 1121
		}
	}
	response := &dap.ThreadsResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ThreadsResponseBody{Threads: threads},
	}
	s.send(response)
}

1122
// onAttachRequest handles 'attach' request.
1123
// This is a mandatory request to support.
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
func (s *Server) onAttachRequest(request *dap.AttachRequest) {
	mode, ok := request.Arguments["mode"]
	if !ok || mode == "" {
		mode = "local"
	}
	if mode == "local" {
		pid, ok := request.Arguments["processId"].(float64)
		if !ok || pid == 0 {
			s.sendErrorResponse(request.Request,
				FailedToAttach, "Failed to attach",
				"The 'processId' attribute is missing in debug configuration")
			return
		}
		s.config.Debugger.AttachPid = int(pid)
1138 1139
		err := s.setLaunchAttachArgs(request)
		if err != nil {
1140
			s.sendErrorResponse(request.Request, FailedToAttach, "Failed to attach", err.Error())
1141 1142
			return
		}
1143 1144 1145 1146 1147 1148 1149
		func() {
			s.mu.Lock()
			defer s.mu.Unlock() // Make sure to unlock in case of panic that will become internal error
			s.debugger, err = debugger.New(&s.config.Debugger, nil)
		}()
		if err != nil {
			s.sendErrorResponse(request.Request, FailedToAttach, "Failed to attach", err.Error())
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
			return
		}
	} else {
		// TODO(polina): support 'remote' mode with 'host' and 'port'
		s.sendErrorResponse(request.Request,
			FailedToAttach, "Failed to attach",
			fmt.Sprintf("Unsupported 'mode' value %q in debug configuration", mode))
		return
	}
	// Notify the client that the debugger is ready to start accepting
	// configuration requests for setting breakpoints, etc. The client
	// will end the configuration sequence with 'configurationDone'.
	s.send(&dap.InitializedEvent{Event: *newEvent("initialized")})
	s.send(&dap.AttachResponse{Response: *newResponse(request.Request)})
1164 1165
}

1166
// onNextRequest handles 'next' request.
1167
// This is a mandatory request to support.
1168
func (s *Server) onNextRequest(request *dap.NextRequest, asyncSetupDone chan struct{}) {
1169
	s.send(&dap.NextResponse{Response: *newResponse(request.Request)})
1170
	s.doStepCommand(api.Next, request.Arguments.ThreadId, asyncSetupDone)
1171 1172
}

1173
// onStepInRequest handles 'stepIn' request
1174
// This is a mandatory request to support.
1175
func (s *Server) onStepInRequest(request *dap.StepInRequest, asyncSetupDone chan struct{}) {
1176
	s.send(&dap.StepInResponse{Response: *newResponse(request.Request)})
1177
	s.doStepCommand(api.Step, request.Arguments.ThreadId, asyncSetupDone)
1178 1179
}

1180
// onStepOutRequest handles 'stepOut' request
1181
// This is a mandatory request to support.
1182
func (s *Server) onStepOutRequest(request *dap.StepOutRequest, asyncSetupDone chan struct{}) {
1183
	s.send(&dap.StepOutResponse{Response: *newResponse(request.Request)})
1184
	s.doStepCommand(api.StepOut, request.Arguments.ThreadId, asyncSetupDone)
1185 1186
}

1187 1188 1189 1190 1191 1192 1193 1194 1195
func stoppedGoroutineID(state *api.DebuggerState) (id int) {
	if state.SelectedGoroutine != nil {
		id = state.SelectedGoroutine.ID
	} else if state.CurrentThread != nil {
		id = state.CurrentThread.GoroutineID
	}
	return id
}

1196 1197 1198 1199 1200 1201 1202
// doStepCommand is a wrapper around doCommand that
// first switches selected goroutine. asyncSetupDone is
// a channel that will be closed to signal that an
// asynchornous command has completed setup or was interrupted
// due to an error, so the server is ready to receive new requests.
func (s *Server) doStepCommand(command string, threadId int, asyncSetupDone chan struct{}) {
	defer s.asyncCommandDone(asyncSetupDone)
1203
	_, err := s.debugger.Command(&api.DebuggerCommand{Name: api.SwitchGoroutine, GoroutineID: threadId}, nil)
1204
	if err != nil {
1205
		s.log.Errorf("Error switching goroutines while stepping: %v", err)
1206 1207 1208 1209
		// If we encounter an error, we will have to send a stopped event
		// since we already sent the step response.
		stopped := &dap.StoppedEvent{Event: *newEvent("stopped")}
		stopped.Body.AllThreadsStopped = true
1210 1211 1212
		if state, err := s.debugger.State(false); err != nil {
			s.log.Errorf("Error retrieving state: %e", err)
		} else {
1213
			stopped.Body.ThreadId = stoppedGoroutineID(state)
1214 1215 1216 1217 1218 1219
		}
		stopped.Body.Reason = "error"
		stopped.Body.Text = err.Error()
		s.send(stopped)
		return
	}
1220
	s.doCommand(command, asyncSetupDone)
1221 1222 1223 1224 1225 1226 1227 1228
}

// onPauseRequest sends a not-yet-implemented error response.
// This is a mandatory request to support.
func (s *Server) onPauseRequest(request *dap.PauseRequest) { // TODO V0
	s.sendNotYetImplementedErrorResponse(request.Request)
}

1229 1230 1231 1232 1233 1234 1235 1236
// stackFrame represents the index of a frame within
// the context of a stack of a specific goroutine.
type stackFrame struct {
	goroutineID int
	frameIndex  int
}

// onStackTraceRequest handles ‘stackTrace’ requests.
1237
// This is a mandatory request to support.
1238 1239
// As per DAP spec, this request only gets triggered as a follow-up
// to a successful threads request as part of the "request waterfall".
1240 1241
func (s *Server) onStackTraceRequest(request *dap.StackTraceRequest) {
	goroutineID := request.Arguments.ThreadId
1242
	frames, err := s.debugger.Stacktrace(goroutineID, s.args.stackTraceDepth, 0)
1243 1244 1245 1246 1247
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToProduceStackTrace, "Unable to produce stack trace", err.Error())
		return
	}

1248 1249 1250
	stackFrames := make([]dap.StackFrame, len(frames))
	for i, frame := range frames {
		loc := &frame.Call
1251
		uniqueStackFrameID := s.stackFrameHandles.create(stackFrame{goroutineID, i})
1252
		stackFrames[i] = dap.StackFrame{Id: uniqueStackFrameID, Line: loc.Line, Name: fnName(loc)}
1253
		if loc.File != "<autogenerated>" {
1254 1255
			clientPath := s.toClientPath(loc.File)
			stackFrames[i].Source = dap.Source{Name: filepath.Base(clientPath), Path: clientPath}
1256 1257 1258
		}
		stackFrames[i].Column = 0
	}
1259 1260 1261 1262 1263
	// Since the backend doesn't support paging, we load all frames up to
	// pre-configured depth every time and then slice them here per
	// `supportsDelayedStackTraceLoading` capability.
	// TODO(polina): consider optimizing this, so subsequent stack requests
	// slice already loaded frames and handles instead of reloading every time.
1264 1265 1266 1267 1268 1269 1270 1271
	if request.Arguments.StartFrame > 0 {
		stackFrames = stackFrames[min(request.Arguments.StartFrame, len(stackFrames)):]
	}
	if request.Arguments.Levels > 0 {
		stackFrames = stackFrames[:min(request.Arguments.Levels, len(stackFrames))]
	}
	response := &dap.StackTraceResponse{
		Response: *newResponse(request.Request),
1272
		Body:     dap.StackTraceResponseBody{StackFrames: stackFrames, TotalFrames: len(frames)},
1273 1274
	}
	s.send(response)
1275 1276
}

1277
// onScopesRequest handles 'scopes' requests.
1278
// This is a mandatory request to support.
1279 1280 1281
// It is automatically sent as part of the threads > stacktrace > scopes > variables
// "waterfall" to highlight the topmost frame at stops, after an evaluate request
// for the selected scope or when a user selects different scopes in the UI.
1282 1283 1284 1285 1286 1287 1288
func (s *Server) onScopesRequest(request *dap.ScopesRequest) {
	sf, ok := s.stackFrameHandles.get(request.Arguments.FrameId)
	if !ok {
		s.sendErrorResponse(request.Request, UnableToListLocals, "Unable to list locals", fmt.Sprintf("unknown frame id %d", request.Arguments.FrameId))
		return
	}

1289 1290
	goid := sf.(stackFrame).goroutineID
	frame := sf.(stackFrame).frameIndex
1291 1292

	// Retrieve arguments
1293
	args, err := s.debugger.FunctionArguments(goid, frame, 0, DefaultLoadConfig)
1294 1295 1296 1297
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToListArgs, "Unable to list args", err.Error())
		return
	}
1298
	argScope := &fullyQualifiedVariable{&proc.Variable{Name: "Arguments", Children: slicePtrVarToSliceVar(args)}, "", true}
1299 1300

	// Retrieve local variables
1301
	locals, err := s.debugger.LocalVariables(goid, frame, 0, DefaultLoadConfig)
1302
	if err != nil {
1303
		s.sendErrorResponse(request.Request, UnableToListLocals, "Unable to list locals", err.Error())
1304 1305
		return
	}
1306
	locScope := &fullyQualifiedVariable{&proc.Variable{Name: "Locals", Children: slicePtrVarToSliceVar(locals)}, "", true}
1307 1308 1309 1310 1311

	scopeArgs := dap.Scope{Name: argScope.Name, VariablesReference: s.variableHandles.create(argScope)}
	scopeLocals := dap.Scope{Name: locScope.Name, VariablesReference: s.variableHandles.create(locScope)}
	scopes := []dap.Scope{scopeArgs, scopeLocals}

1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
	if s.args.showGlobalVariables {
		// Limit what global variables we will return to the current package only.
		// TODO(polina): This is how vscode-go currently does it to make
		// the amount of the returned data manageable. In fact, this is
		// considered so expensive even with the package filter, that
		// the default for showGlobalVariables was recently flipped to
		// not showing. If we delay loading of the globals until the corresponding
		// scope is expanded, generating an explicit variable request,
		// should we consider making all globals accessible with a scope per package?
		// Or users can just rely on watch variables.
		currPkg, err := s.debugger.CurrentPackage()
		if err != nil {
			s.sendErrorResponse(request.Request, UnableToListGlobals, "Unable to list globals", err.Error())
			return
		}
		currPkgFilter := fmt.Sprintf("^%s\\.", currPkg)
1328
		globals, err := s.debugger.PackageVariables(currPkgFilter, DefaultLoadConfig)
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
		if err != nil {
			s.sendErrorResponse(request.Request, UnableToListGlobals, "Unable to list globals", err.Error())
			return
		}
		// Remove package prefix from the fully-qualified variable names.
		// We will include the package info once in the name of the scope instead.
		for i, g := range globals {
			globals[i].Name = strings.TrimPrefix(g.Name, currPkg+".")
		}

1339
		globScope := &fullyQualifiedVariable{&proc.Variable{
1340 1341
			Name:     fmt.Sprintf("Globals (package %s)", currPkg),
			Children: slicePtrVarToSliceVar(globals),
1342
		}, currPkg, true}
1343 1344 1345
		scopeGlobals := dap.Scope{Name: globScope.Name, VariablesReference: s.variableHandles.create(globScope)}
		scopes = append(scopes, scopeGlobals)
	}
1346 1347 1348 1349 1350
	response := &dap.ScopesResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ScopesResponseBody{Scopes: scopes},
	}
	s.send(response)
1351 1352
}

1353 1354 1355 1356 1357 1358 1359 1360
func slicePtrVarToSliceVar(vars []*proc.Variable) []proc.Variable {
	r := make([]proc.Variable, len(vars))
	for i := range vars {
		r[i] = *vars[i]
	}
	return r
}

1361
// onVariablesRequest handles 'variables' requests.
1362
// This is a mandatory request to support.
1363
func (s *Server) onVariablesRequest(request *dap.VariablesRequest) {
1364
	v, ok := s.variableHandles.get(request.Arguments.VariablesReference)
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
	if !ok {
		s.sendErrorResponse(request.Request, UnableToLookupVariable, "Unable to lookup variable", fmt.Sprintf("unknown reference %d", request.Arguments.VariablesReference))
		return
	}
	children := make([]dap.Variable, 0)

	switch v.Kind {
	case reflect.Map:
		for i := 0; i < len(v.Children); i += 2 {
			// A map will have twice as many children as there are key-value elements.
			kvIndex := i / 2
			// Process children in pairs: even indices are map keys, odd indices are values.
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
			keyv, valv := &v.Children[i], &v.Children[i+1]
			keyexpr := fmt.Sprintf("(*(*%q)(%#x))", keyv.TypeString(), keyv.Addr)
			valexpr := fmt.Sprintf("%s[%s]", v.fullyQualifiedNameOrExpr, keyexpr)
			switch keyv.Kind {
			// For value expression, use the key value, not the corresponding expression if the key is a scalar.
			case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128,
				reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
				reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				valexpr = fmt.Sprintf("%s[%s]", v.fullyQualifiedNameOrExpr, api.VariableValueAsString(keyv))
			case reflect.String:
				if key := constant.StringVal(keyv.Value); keyv.Len == int64(len(key)) { // fully loaded
					valexpr = fmt.Sprintf("%s[%q]", v.fullyQualifiedNameOrExpr, key)
				}
			}
			key, keyref := s.convertVariable(keyv, keyexpr)
			val, valref := s.convertVariable(valv, valexpr)
1393 1394 1395 1396 1397 1398
			// If key or value or both are scalars, we can use
			// a single variable to represet key:value format.
			// Otherwise, we must return separate variables for both.
			if keyref > 0 && valref > 0 { // Both are not scalars
				keyvar := dap.Variable{
					Name:               fmt.Sprintf("[key %d]", kvIndex),
1399
					EvaluateName:       keyexpr,
1400 1401 1402 1403 1404
					Value:              key,
					VariablesReference: keyref,
				}
				valvar := dap.Variable{
					Name:               fmt.Sprintf("[val %d]", kvIndex),
1405
					EvaluateName:       valexpr,
1406 1407 1408 1409 1410 1411
					Value:              val,
					VariablesReference: valref,
				}
				children = append(children, keyvar, valvar)
			} else { // At least one is a scalar
				kvvar := dap.Variable{
1412 1413 1414
					Name:         key,
					EvaluateName: valexpr,
					Value:        val,
1415 1416
				}
				if keyref != 0 { // key is a type to be expanded
1417 1418 1419 1420
					if len(key) > DefaultLoadConfig.MaxStringLen {
						// Truncate and make unique
						kvvar.Name = fmt.Sprintf("%s... @ %#x", key[0:DefaultLoadConfig.MaxStringLen], keyv.Addr)
					}
1421 1422 1423 1424 1425 1426 1427 1428 1429
					kvvar.VariablesReference = keyref
				} else if valref != 0 { // val is a type to be expanded
					kvvar.VariablesReference = valref
				}
				children = append(children, kvvar)
			}
		}
	case reflect.Slice, reflect.Array:
		children = make([]dap.Variable, len(v.Children))
1430
		for i := range v.Children {
1431 1432
			cfqname := fmt.Sprintf("%s[%d]", v.fullyQualifiedNameOrExpr, i)
			cvalue, cvarref := s.convertVariable(&v.Children[i], cfqname)
1433 1434
			children[i] = dap.Variable{
				Name:               fmt.Sprintf("[%d]", i),
1435 1436 1437
				EvaluateName:       cfqname,
				Value:              cvalue,
				VariablesReference: cvarref,
1438 1439 1440 1441
			}
		}
	default:
		children = make([]dap.Variable, len(v.Children))
1442 1443
		for i := range v.Children {
			c := &v.Children[i]
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
			cfqname := fmt.Sprintf("%s.%s", v.fullyQualifiedNameOrExpr, c.Name)

			if strings.HasPrefix(c.Name, "~") || strings.HasPrefix(c.Name, ".") {
				cfqname = ""
			} else if v.isScope && v.fullyQualifiedNameOrExpr == "" {
				cfqname = c.Name
			} else if v.fullyQualifiedNameOrExpr == "" {
				cfqname = ""
			} else if v.Kind == reflect.Interface {
				cfqname = fmt.Sprintf("%s.(%s)", v.fullyQualifiedNameOrExpr, c.Name) // c is data
			} else if v.Kind == reflect.Ptr {
				cfqname = fmt.Sprintf("(*%v)", v.fullyQualifiedNameOrExpr) // c is the nameless pointer value
			} else if v.Kind == reflect.Complex64 || v.Kind == reflect.Complex128 {
				cfqname = "" // complex children are not struct fields and can't be accessed directly
			}
			cvalue, cvarref := s.convertVariable(c, cfqname)
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

			// Annotate any shadowed variables to "(name)" in order
			// to distinguish from non-shadowed variables.
			// TODO(suzmue): should we support a special evaluateName syntax that
			// can access shadowed variables?
			name := c.Name
			if c.Flags&proc.VariableShadowed == proc.VariableShadowed {
				name = fmt.Sprintf("(%s)", name)
			}

1470
			children[i] = dap.Variable{
1471
				Name:               name,
1472 1473 1474
				EvaluateName:       cfqname,
				Value:              cvalue,
				VariablesReference: cvarref,
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
			}
		}
	}
	response := &dap.VariablesResponse{
		Response: *newResponse(request.Request),
		Body:     dap.VariablesResponseBody{Variables: children},
	}
	s.send(response)
}

1485 1486
// convertVariable converts proc.Variable to dap.Variable value and reference
// while keeping track of the full qualified name or load expression.
1487
// Variable reference is used to keep track of the children associated with each
1488 1489 1490 1491 1492 1493
// variable. It is shared with the host via scopes or evaluate response and is an index
// into the s.variableHandles map, used to look up variables and their children on
// subsequent variables requests. A positive reference signals the host that another
// variables request can be issued to get the elements of the compound variable. As a
// custom, a zero reference, reminiscent of a zero pointer, is used to indicate that
// a scalar variable cannot be "dereferenced" to get its elements (as there are none).
1494 1495
func (s *Server) convertVariable(v *proc.Variable, qualifiedNameOrExpr string) (value string, variablesReference int) {
	return s.convertVariableWithOpts(v, qualifiedNameOrExpr, false)
1496 1497 1498
}

func (s *Server) convertVariableToString(v *proc.Variable) string {
1499
	val, _ := s.convertVariableWithOpts(v, "", true)
1500 1501 1502
	return val
}

1503
// convertVariableWithOpts allows to skip reference generation in case all we need is
1504
// a string representation of the variable.
1505
func (s *Server) convertVariableWithOpts(v *proc.Variable, qualifiedNameOrExpr string, skipRef bool) (value string, variablesReference int) {
1506 1507 1508 1509
	maybeCreateVariableHandle := func(v *proc.Variable) int {
		if skipRef {
			return 0
		}
1510
		return s.variableHandles.create(&fullyQualifiedVariable{v, qualifiedNameOrExpr, false /*not a scope*/})
1511
	}
1512
	value = api.ConvertVar(v).SinglelineString()
1513
	if v.Unreadable != nil {
1514 1515
		return
	}
1516

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
	// Some of the types might be fully or partially not loaded based on LoadConfig.
	// Those that are fully missing (e.g. due to hitting MaxVariableRecurse), can be reloaded in place.
	// Those that are partially missing (e.g. MaxArrayValues from a large array), need a more creative solution
	// that is still to be determined. For now, clearly communicate when that happens with additional value labels.
	// TODO(polina): look into layered/paged loading for truncated strings, arrays, maps and structs.
	var reloadVariable = func(v *proc.Variable, qualifiedNameOrExpr string) (value string) {
		// We might be loading variables from the frame that's not topmost, so use
		// frame-independent address-based expression, not fully-qualified name as per
		// https://github.com/go-delve/delve/blob/master/Documentation/api/ClientHowto.md#looking-into-variables.
		// TODO(polina): Get *proc.Variable object from debugger instead. Export and set v.loaded to false
		// and call v.loadValue gain. It's more efficient, and it's guaranteed to keep working with generics.
		value = api.ConvertVar(v).SinglelineString()
		typeName := api.PrettyTypeName(v.DwarfType)
		loadExpr := fmt.Sprintf("*(*%q)(%#x)", typeName, v.Addr)
		s.log.Debugf("loading %s (type %s) with %s", qualifiedNameOrExpr, typeName, loadExpr)
		// Make sure we can load the pointers directly, not by updating just the child
		// This is not really necessary now because users have no way of setting FollowPointers to false.
		config := DefaultLoadConfig
		config.FollowPointers = true
		vLoaded, err := s.debugger.EvalVariableInScope(-1, 0, 0, loadExpr, config)
		if err != nil {
			value += fmt.Sprintf(" - FAILED TO LOAD: %s", err)
		} else {
			v.Children = vLoaded.Children
			value = api.ConvertVar(v).SinglelineString()
		}
		return value
	}
1545

1546 1547
	switch v.Kind {
	case reflect.UnsafePointer:
1548
		// Skip child reference
1549
	case reflect.Ptr:
1550
		if v.DwarfType != nil && len(v.Children) > 0 && v.Children[0].Addr != 0 && v.Children[0].Kind != reflect.Invalid {
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
			if v.Children[0].OnlyAddr { // Not loaded
				if v.Addr == 0 {
					// This is equvalent to the following with the cli:
					//    (dlv) p &a7
					//    (**main.FooBar)(0xc0000a3918)
					//
					// TODO(polina): what is more appropriate?
					// Option 1: leave it unloaded because it is a special case
					// Option 2: load it, but then we have to load the child, not the parent, unlike all others
					// TODO(polina): see if reloadVariable can be reused here
					cTypeName := api.PrettyTypeName(v.Children[0].DwarfType)
					cLoadExpr := fmt.Sprintf("*(*%q)(%#x)", cTypeName, v.Children[0].Addr)
					s.log.Debugf("loading *(%s) (type %s) with %s", qualifiedNameOrExpr, cTypeName, cLoadExpr)
					cLoaded, err := s.debugger.EvalVariableInScope(-1, 0, 0, cLoadExpr, DefaultLoadConfig)
					if err != nil {
						value += fmt.Sprintf(" - FAILED TO LOAD: %s", err)
					} else {
						cLoaded.Name = v.Children[0].Name // otherwise, this will be the pointer expression
						v.Children = []proc.Variable{*cLoaded}
						value = api.ConvertVar(v).SinglelineString()
					}
				} else {
					value = reloadVariable(v, qualifiedNameOrExpr)
				}
			}
			if !v.Children[0].OnlyAddr {
1577 1578
				variablesReference = maybeCreateVariableHandle(v)
			}
1579
		}
1580
	case reflect.Slice, reflect.Array:
1581
		if v.Len > int64(len(v.Children)) { // Not fully loaded
1582 1583 1584 1585 1586
			if v.Base != 0 && len(v.Children) == 0 { // Fully missing
				value = reloadVariable(v, qualifiedNameOrExpr)
			} else { // Partially missing (TODO)
				value = fmt.Sprintf("(loaded %d/%d) ", len(v.Children), v.Len) + value
			}
1587
		}
1588
		if v.Base != 0 && len(v.Children) > 0 {
1589
			variablesReference = maybeCreateVariableHandle(v)
1590 1591
		}
	case reflect.Map:
1592
		if v.Len > int64(len(v.Children)/2) { // Not fully loaded
1593 1594 1595 1596 1597
			if len(v.Children) == 0 { // Fully missing
				value = reloadVariable(v, qualifiedNameOrExpr)
			} else { // Partially missing (TODO)
				value = fmt.Sprintf("(loaded %d/%d) ", len(v.Children)/2, v.Len) + value
			}
1598
		}
1599
		if v.Base != 0 && len(v.Children) > 0 {
1600
			variablesReference = maybeCreateVariableHandle(v)
1601
		}
1602 1603
	case reflect.String:
		// TODO(polina): implement auto-loading here
1604
	case reflect.Interface:
1605
		if v.Addr != 0 && len(v.Children) > 0 && v.Children[0].Kind != reflect.Invalid && v.Children[0].Addr != 0 {
1606 1607
			if v.Children[0].OnlyAddr { // Not loaded
				value = reloadVariable(v, qualifiedNameOrExpr)
1608 1609
			}
			if !v.Children[0].OnlyAddr {
1610 1611 1612 1613 1614
				variablesReference = maybeCreateVariableHandle(v)
			}
		}
	case reflect.Struct:
		if v.Len > int64(len(v.Children)) { // Not fully loaded
1615 1616 1617 1618 1619
			if len(v.Children) == 0 { // Fully missing
				value = reloadVariable(v, qualifiedNameOrExpr)
			} else { // Partially missing (TODO)
				value = fmt.Sprintf("(loaded %d/%d) ", len(v.Children), v.Len) + value
			}
1620 1621
		}
		if len(v.Children) > 0 {
1622
			variablesReference = maybeCreateVariableHandle(v)
1623
		}
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
	case reflect.Complex64, reflect.Complex128:
		v.Children = make([]proc.Variable, 2)
		v.Children[0].Name = "real"
		v.Children[0].Value = constant.Real(v.Value)
		v.Children[1].Name = "imaginary"
		v.Children[1].Value = constant.Imag(v.Value)
		if v.Kind == reflect.Complex64 {
			v.Children[0].Kind = reflect.Float32
			v.Children[1].Kind = reflect.Float32
		} else {
			v.Children[0].Kind = reflect.Float64
			v.Children[1].Kind = reflect.Float64
		}
		fallthrough
1638
	default: // Complex, Scalar, Chan, Func
1639
		if len(v.Children) > 0 {
1640
			variablesReference = maybeCreateVariableHandle(v)
1641 1642 1643
		}
	}
	return
1644 1645
}

1646
// onEvaluateRequest handles 'evalute' requests.
1647
// This is a mandatory request to support.
1648 1649 1650 1651 1652 1653 1654
// Support the following expressions:
// -- {expression} - evaluates the expression and returns the result as a variable
// -- call {function} - injects a function call and returns the result as a variable
// TODO(polina): users have complained about having to click to expand multi-level
// variables, so consider also adding the following:
// -- print {expression} - return the result as a string like from dlv cli
func (s *Server) onEvaluateRequest(request *dap.EvaluateRequest) {
1655
	showErrorToUser := request.Arguments.Context != "watch" && request.Arguments.Context != "repl"
1656 1657 1658 1659
	if s.debugger == nil {
		s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", "debugger is nil", showErrorToUser)
		return
	}
1660

1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
	// Default to the topmost stack frame of the current goroutine in case
	// no frame is specified (e.g. when stopped on entry or no call stack frame is expanded)
	goid, frame := -1, 0
	if sf, ok := s.stackFrameHandles.get(request.Arguments.FrameId); ok {
		goid = sf.(stackFrame).goroutineID
		frame = sf.(stackFrame).frameIndex
	}

	response := &dap.EvaluateResponse{Response: *newResponse(request.Request)}
	isCall, err := regexp.MatchString(`^\s*call\s+\S+`, request.Arguments.Expression)
	if err == nil && isCall { // call {expression}
		// This call might be evaluated in the context of the frame that is not topmost
		// if the editor is set to view the variables for one of the parent frames.
		// If the call expression refers to any of these variables, unlike regular
		// expressions, it will evaluate them in the context of the topmost frame,
		// and the user will get an unexpected result or an unexpected symbol error.
		// We prevent this but disallowing any frames other than topmost.
		if frame > 0 {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", "call is only supported with topmost stack frame", showErrorToUser)
			return
		}
		stateBeforeCall, err := s.debugger.State( /*nowait*/ true)
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
			return
		}
1687 1688 1689
		// TODO(polina): since call will resume execution of all goroutines,
		// we should do this asynchronously and send a continued event to the
		// editor, followed by a stop event when the call completes.
1690 1691
		state, err := s.debugger.Command(&api.DebuggerCommand{
			Name:                 api.Call,
1692
			ReturnInfoLoadConfig: api.LoadConfigFromProc(&DefaultLoadConfig),
1693 1694 1695
			Expr:                 strings.Replace(request.Arguments.Expression, "call ", "", 1),
			UnsafeCall:           false,
			GoroutineID:          goid,
1696
		}, nil)
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
		if _, isexited := err.(proc.ErrProcessExited); isexited || err == nil && state.Exited {
			e := &dap.TerminatedEvent{Event: *newEvent("terminated")}
			s.send(e)
			return
		}
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
			return
		}
		// After the call is done, the goroutine where we injected the call should
		// return to the original stopped line with return values. However,
		// it is not guaranteed to be selected due to the possibility of the
		// of simultaenous breakpoints. Therefore, we check all threads.
		var retVars []*proc.Variable
		for _, t := range state.Threads {
			if t.GoroutineID == stateBeforeCall.SelectedGoroutine.ID &&
1713
				t.Line == stateBeforeCall.SelectedGoroutine.CurrentLoc.Line && t.CallReturn {
1714
				// The call completed. Get the return values.
1715
				retVars, err = s.debugger.FindThreadReturnValues(t.ID, DefaultLoadConfig)
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
				if err != nil {
					s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
					return
				}
				break
			}
		}
		if retVars == nil {
			// The call got interrupted by a stop (e.g. breakpoint in injected
			// function call or in another goroutine)
1726
			s.resetHandlesForStoppedEvent()
1727 1728
			stopped := &dap.StoppedEvent{Event: *newEvent("stopped")}
			stopped.Body.AllThreadsStopped = true
1729
			stopped.Body.ThreadId = stoppedGoroutineID(state)
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
			stopped.Body.Reason = s.debugger.StopReason().String()
			s.send(stopped)
			// TODO(polina): once this is asynchronous, we could wait to reply until the user
			// continues, call ends, original stop point is hit and return values are available.
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", "call stopped", showErrorToUser)
			return
		}
		// The call completed and we can reply with its return values (if any)
		if len(retVars) > 0 {
			// Package one or more return values in a single scope-like nameless variable
			// that preserves their names.
			retVarsAsVar := &proc.Variable{Children: slicePtrVarToSliceVar(retVars)}
			// As a shortcut also express the return values as a single string.
			retVarsAsStr := ""
			for _, v := range retVars {
				retVarsAsStr += s.convertVariableToString(v) + ", "
			}
			response.Body = dap.EvaluateResponseBody{
				Result:             strings.TrimRight(retVarsAsStr, ", "),
1749
				VariablesReference: s.variableHandles.create(&fullyQualifiedVariable{retVarsAsVar, "", false /*not a scope*/}),
1750 1751 1752
			}
		}
	} else { // {expression}
1753
		exprVar, err := s.debugger.EvalVariableInScope(goid, frame, 0, request.Arguments.Expression, DefaultLoadConfig)
1754 1755 1756 1757
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
			return
		}
1758 1759 1760
		// TODO(polina): as far as I can tell, evaluateName is ignored by vscode for expression variables.
		// Should it be skipped alltogether for all levels?
		exprVal, exprRef := s.convertVariable(exprVar, fmt.Sprintf("(%s)", request.Arguments.Expression))
1761 1762 1763
		response.Body = dap.EvaluateResponseBody{Result: exprVal, VariablesReference: exprRef}
	}
	s.send(response)
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
}

// onTerminateRequest sends a not-yet-implemented error response.
// Capability 'supportsTerminateRequest' is not set in 'initialize' response.
func (s *Server) onTerminateRequest(request *dap.TerminateRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onRestartRequest sends a not-yet-implemented error response
// Capability 'supportsRestartRequest' is not set in 'initialize' response.
func (s *Server) onRestartRequest(request *dap.RestartRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onSetFunctionBreakpointsRequest sends a not-yet-implemented error response.
// Capability 'supportsFunctionBreakpoints' is not set 'initialize' response.
func (s *Server) onSetFunctionBreakpointsRequest(request *dap.SetFunctionBreakpointsRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onStepBackRequest sends a not-yet-implemented error response.
// Capability 'supportsStepBack' is not set 'initialize' response.
func (s *Server) onStepBackRequest(request *dap.StepBackRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onReverseContinueRequest sends a not-yet-implemented error response.
// Capability 'supportsStepBack' is not set 'initialize' response.
func (s *Server) onReverseContinueRequest(request *dap.ReverseContinueRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onSetVariableRequest sends a not-yet-implemented error response.
// Capability 'supportsSetVariable' is not set 'initialize' response.
func (s *Server) onSetVariableRequest(request *dap.SetVariableRequest) { // TODO V0
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onSetExpression sends a not-yet-implemented error response.
// Capability 'supportsSetExpression' is not set 'initialize' response.
func (s *Server) onSetExpressionRequest(request *dap.SetExpressionRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onLoadedSourcesRequest sends a not-yet-implemented error response.
// Capability 'supportsLoadedSourcesRequest' is not set 'initialize' response.
func (s *Server) onLoadedSourcesRequest(request *dap.LoadedSourcesRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onReadMemoryRequest sends a not-yet-implemented error response.
// Capability 'supportsReadMemoryRequest' is not set 'initialize' response.
func (s *Server) onReadMemoryRequest(request *dap.ReadMemoryRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onDisassembleRequest sends a not-yet-implemented error response.
// Capability 'supportsDisassembleRequest' is not set 'initialize' response.
func (s *Server) onDisassembleRequest(request *dap.DisassembleRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

// onCancelRequest sends a not-yet-implemented error response.
// Capability 'supportsCancelRequest' is not set 'initialize' response.
func (s *Server) onCancelRequest(request *dap.CancelRequest) {
	s.sendNotYetImplementedErrorResponse(request.Request)
}

1832
// sendErrorResponseWithOpts offers configuration options.
1833 1834
//   showUser - if true, the error will be shown to the user (e.g. via a visible pop-up)
func (s *Server) sendErrorResponseWithOpts(request dap.Request, id int, summary, details string, showUser bool) {
1835 1836 1837 1838 1839 1840 1841 1842
	er := &dap.ErrorResponse{}
	er.Type = "response"
	er.Command = request.Command
	er.RequestSeq = request.Seq
	er.Success = false
	er.Message = summary
	er.Body.Error.Id = id
	er.Body.Error.Format = fmt.Sprintf("%s: %s", summary, details)
1843
	er.Body.Error.ShowUser = showUser
1844
	s.log.Debug(er.Body.Error.Format)
1845 1846 1847
	s.send(er)
}

1848 1849 1850 1851 1852
// sendErrorResponse sends an error response with default visibility settings.
func (s *Server) sendErrorResponse(request dap.Request, id int, summary, details string) {
	s.sendErrorResponseWithOpts(request, id, summary, details, false /*showUser*/)
}

1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
// sendInternalErrorResponse sends an "internal error" response back to the client.
// We only take a seq here because we don't want to make assumptions about the
// kind of message received by the server that this error is a reply to.
func (s *Server) sendInternalErrorResponse(seq int, details string) {
	er := &dap.ErrorResponse{}
	er.Type = "response"
	er.RequestSeq = seq
	er.Success = false
	er.Message = "Internal Error"
	er.Body.Error.Id = InternalError
	er.Body.Error.Format = fmt.Sprintf("%s: %s", er.Message, details)
1864
	s.log.Debug(er.Body.Error.Format)
1865 1866 1867
	s.send(er)
}

1868 1869
func (s *Server) sendUnsupportedErrorResponse(request dap.Request) {
	s.sendErrorResponse(request, UnsupportedCommand, "Unsupported command",
1870
		fmt.Sprintf("cannot process %q request", request.Command))
1871 1872
}

1873 1874
func (s *Server) sendNotYetImplementedErrorResponse(request dap.Request) {
	s.sendErrorResponse(request, NotYetImplemented, "Not yet implemented",
1875
		fmt.Sprintf("cannot process %q request", request.Command))
1876 1877
}

1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
func newResponse(request dap.Request) *dap.Response {
	return &dap.Response{
		ProtocolMessage: dap.ProtocolMessage{
			Seq:  0,
			Type: "response",
		},
		Command:    request.Command,
		RequestSeq: request.Seq,
		Success:    true,
	}
}

func newEvent(event string) *dap.Event {
	return &dap.Event{
		ProtocolMessage: dap.ProtocolMessage{
			Seq:  0,
			Type: "event",
		},
		Event: event,
	}
}

1900
const BetterBadAccessError = `invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation]
1901
Unable to propagate EXC_BAD_ACCESS signal to target process and panic (see https://github.com/go-delve/delve/issues/852)`
1902

1903
func (s *Server) resetHandlesForStoppedEvent() {
1904 1905 1906 1907
	s.stackFrameHandles.reset()
	s.variableHandles.reset()
}

1908 1909
// doCommand runs a debugger command until it stops on
// termination, error, breakpoint, etc, when an appropriate
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
// event needs to be sent to the client. asyncSetupDone is
// a channel that will be closed to signal that an
// asynchornous command has completed setup or was interrupted
// due to an error, so the server is ready to receive new requests.
func (s *Server) doCommand(command string, asyncSetupDone chan struct{}) {
	// TODO(polina): it appears that debugger.Command doesn't close
	// asyncSetupDone (e.g. when having an error next while nexting).
	// So we should always close it ourselves just in case.
	defer s.asyncCommandDone(asyncSetupDone)
	state, err := s.debugger.Command(&api.DebuggerCommand{Name: command}, asyncSetupDone)
1920
	if _, isexited := err.(proc.ErrProcessExited); isexited || err == nil && state.Exited {
1921
		s.send(&dap.TerminatedEvent{Event: *newEvent("terminated")})
1922 1923
		return
	}
1924

1925
	s.resetHandlesForStoppedEvent()
1926 1927 1928 1929
	stopped := &dap.StoppedEvent{Event: *newEvent("stopped")}
	stopped.Body.AllThreadsStopped = true

	if err == nil {
1930
		stopped.Body.ThreadId = stoppedGoroutineID(state)
1931

1932 1933 1934
		sr := s.debugger.StopReason()
		s.log.Debugf("%q command stopped - reason %q", command, sr)
		switch sr {
1935
		case proc.StopNextFinished:
1936
			stopped.Body.Reason = "step"
1937 1938 1939 1940
		case proc.StopManual: // triggered by halt
			stopped.Body.Reason = "pause"
		case proc.StopUnknown: // can happen while stopping
			stopped.Body.Reason = "unknown"
1941 1942 1943
		default:
			stopped.Body.Reason = "breakpoint"
		}
1944
		if state.CurrentThread != nil && state.CurrentThread.Breakpoint != nil {
1945 1946 1947 1948 1949 1950 1951
			switch state.CurrentThread.Breakpoint.Name {
			case proc.FatalThrow:
				stopped.Body.Reason = "fatal error"
			case proc.UnrecoveredPanic:
				stopped.Body.Reason = "panic"
			}
		}
1952
	} else {
1953 1954 1955 1956 1957 1958 1959 1960 1961
		s.log.Error("runtime error: ", err)
		stopped.Body.Reason = "runtime error"
		stopped.Body.Text = err.Error()
		// Special case in the spirit of https://github.com/microsoft/vscode-go/issues/1903
		if stopped.Body.Text == "bad access" {
			stopped.Body.Text = BetterBadAccessError
		}
		state, err := s.debugger.State( /*nowait*/ true)
		if err == nil {
1962
			stopped.Body.ThreadId = stoppedGoroutineID(state)
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
		}

		// TODO(polina): according to the spec, the extra 'text' is supposed to show up in the UI (e.g. on hover),
		// but so far I am unable to get this to work in vscode - see https://github.com/microsoft/vscode/issues/104475.
		// Options to explore:
		//   - supporting ExceptionInfo request
		//   - virtual variable scope for Exception that shows the message (details here: https://github.com/microsoft/vscode/issues/3101)
		// In the meantime, provide the extra details by outputing an error message.
		s.send(&dap.OutputEvent{
			Event: *newEvent("output"),
			Body: dap.OutputEventBody{
				Output:   fmt.Sprintf("ERROR: %s\n", stopped.Body.Text),
				Category: "stderr",
			}})
1977
	}
1978 1979 1980 1981 1982

	// NOTE: If we happen to be responding to another request with an is-running
	// error while this one completes, it is possible that the error response
	// will arrive after this stopped event.
	s.send(stopped)
1983
}
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005

func (s *Server) toClientPath(path string) string {
	if len(s.args.substitutePathServerToClient) == 0 {
		return path
	}
	clientPath := locspec.SubstitutePath(path, s.args.substitutePathServerToClient)
	if clientPath != path {
		s.log.Debugf("server path=%s converted to client path=%s\n", path, clientPath)
	}
	return clientPath
}

func (s *Server) toServerPath(path string) string {
	if len(s.args.substitutePathClientToServer) == 0 {
		return path
	}
	serverPath := locspec.SubstitutePath(path, s.args.substitutePathClientToServer)
	if serverPath != path {
		s.log.Debugf("client path=%s converted to server path=%s\n", path, serverPath)
	}
	return serverPath
}