server.go 94.0 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
package dap

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

31
	"github.com/go-delve/delve/pkg/gobuild"
32
	"github.com/go-delve/delve/pkg/locspec"
33 34
	"github.com/go-delve/delve/pkg/logflags"
	"github.com/go-delve/delve/pkg/proc"
35
	"github.com/go-delve/delve/pkg/terminal"
36 37 38
	"github.com/go-delve/delve/service"
	"github.com/go-delve/delve/service/api"
	"github.com/go-delve/delve/service/debugger"
39
	"github.com/go-delve/delve/service/internal/sameuser"
40
	"github.com/google/go-dap"
41 42 43 44
	"github.com/sirupsen/logrus"
)

// Server implements a DAP server that can accept a single client for
45
// a single debug session (for now). It does not yet support restarting.
46 47 48 49 50 51
// 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:
//
52
// (1) Main goroutine where the server is created via NewServer(),
53 54 55 56 57 58 59 60
// 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,
61 62 63 64 65 66 67 68 69 70 71 72
// 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.
73 74
//
// TODO(polina): add another layer of per-client goroutines to support multiple clients
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
//
// (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.
90 91 92 93 94
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
95
	// stopTriggered is closed when the server is Stop()-ed.
96
	stopTriggered chan struct{}
97 98 99 100
	// reader is used to read requests from the connection.
	reader *bufio.Reader
	// log is used for structured logging.
	log *logrus.Entry
101
	// stackFrameHandles maps frames of each goroutine to unique ids across all goroutines.
102
	// Reset at every stop.
103
	stackFrameHandles *handlesMap
104
	// variableHandles maps compound variables to unique references within their stack frame.
105
	// Reset at every stop.
106
	// See also comment for convertVariable.
107
	variableHandles *variablesHandlesMap
108 109
	// args tracks special settings for handling debug session requests.
	args launchAttachArgs
110 111
	// exceptionErr tracks the runtime error that last occurred.
	exceptionErr error
112 113
	// clientCapabilities tracks special settings for handling debug session requests.
	clientCapabilities dapClientCapabilites
114

115 116
	// mu synchronizes access to objects set on start-up (from run goroutine)
	// and stopped on teardown (from main goroutine)
117
	mu sync.Mutex
118

119 120 121 122
	// conn is the accepted client connection.
	conn net.Conn
	// debugger is the underlying debugger service.
	debugger *debugger.Debugger
123 124
	// binaryToRemove is the temp compiled binary to be removed on disconnect (if any).
	binaryToRemove string
125 126
	// noDebugProcess is set for the noDebug launch process.
	noDebugProcess *exec.Cmd
127 128 129 130

	// sendingMu synchronizes writing to net.Conn
	// to ensure that messages do not get interleaved
	sendingMu sync.Mutex
131 132 133 134 135 136 137 138 139
}

// 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
140 141
	// showGlobalVariables indicates if global package variables should be loaded.
	showGlobalVariables bool
142 143 144 145 146 147
	// 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
148 149 150 151
}

// defaultArgs borrows the defaults for the arguments from the original vscode-go adapter.
var defaultArgs = launchAttachArgs{
152 153 154 155 156
	stopOnEntry:                  false,
	stackTraceDepth:              50,
	showGlobalVariables:          false,
	substitutePathClientToServer: [][2]string{},
	substitutePathServerToClient: [][2]string{},
157 158
}

159 160 161 162 163 164 165 166 167 168
// dapClientCapabilites captures arguments from intitialize request that
// impact handling of subsequent requests.
type dapClientCapabilites struct {
	supportsVariableType         bool
	supportsVariablePaging       bool
	supportsRunInTerminalRequest bool
	supportsMemoryReferences     bool
	supportsProgressReporting    bool
}

169 170
// 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.
171
// With dlv-dap, users currently do not have a way to adjust these.
172 173 174 175 176 177 178 179 180
// 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,
}

181
// NewServer creates a new DAP Server. It takes an opened Listener
182 183 184 185
// 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.
186 187 188
func NewServer(config *service.Config) *Server {
	logger := logflags.DAPLogger()
	logflags.WriteDAPListeningMessage(config.Listener.Addr().String())
189
	logger.Debug("DAP server pid = ", os.Getpid())
190
	return &Server{
191 192
		config:            config,
		listener:          config.Listener,
193
		stopTriggered:     make(chan struct{}),
194 195
		log:               logger,
		stackFrameHandles: newHandlesMap(),
196
		variableHandles:   newVariablesHandlesMap(),
197
		args:              defaultArgs,
198
		exceptionErr:      nil,
199 200 201
	}
}

202 203
// If user-specified options are provided via Launch/AttachRequest,
// we override the defaults for optional args.
204
func (s *Server) setLaunchAttachArgs(request dap.LaunchAttachRequest) error {
205 206 207 208 209 210 211 212 213 214 215 216
	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
	}
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
	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
246 247
}

248 249
// Stop stops the DAP debugger service, closes the listener and the client
// connection. It shuts down the underlying debugger and kills the target
250 251
// process if it was launched by it or stops the noDebug process.
// This method mustn't be called more than once.
252
func (s *Server) Stop() {
253
	s.log.Debug("DAP server stopping...")
254
	close(s.stopTriggered)
255
	_ = s.listener.Close()
256 257 258

	s.mu.Lock()
	defer s.mu.Unlock()
259 260 261 262 263
	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.
264
		_ = s.conn.Close()
265
	}
266

267
	if s.debugger != nil {
268 269
		killProcess := s.config.Debugger.AttachPid == 0
		s.stopDebugSession(killProcess)
270 271
	} else {
		s.stopNoDebugProcess()
272
	}
273 274 275 276 277
	// 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 = ""
	}
278
	s.log.Debug("DAP server stopped")
279 280
}

281 282 283 284 285
// 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
286 287
// than once and can be called multiple times. It is not thread-safe
// and is currently only called from the run goroutine.
288
func (s *Server) triggerServerStop() {
289 290 291 292
	// 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()
293
	// -- run goroutine: calls triggerServerStop()
294
	// -- main goroutine: calls Stop()
295
	// -- main goroutine: Stop() closes client connection (or client closed it)
296
	// -- run goroutine: serveDAPCodec() gets "closed network connection"
297
	// -- run goroutine: serveDAPCodec() returns and calls triggerServerStop()
298 299 300 301
	if s.config.DisconnectChan != nil {
		close(s.config.DisconnectChan)
		s.config.DisconnectChan = nil
	}
302 303 304
	// There should be no logic here after the stop-server
	// signal that might cause everything to shutdown before this
	// logic gets executed.
305 306 307 308 309 310 311 312 313 314 315
}

// 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() {
316
		conn, err := s.listener.Accept() // listener is closed in Stop()
317
		if err != nil {
318
			select {
319
			case <-s.stopTriggered:
320 321
			default:
				s.log.Errorf("Error accepting client connection: %s\n", err)
322
				s.triggerServerStop()
323
			}
324 325
			return
		}
326 327 328 329 330 331 332
		if s.config.CheckLocalConnUser {
			if !sameuser.CanAccept(s.listener.Addr(), conn.RemoteAddr()) {
				s.log.Error("Error accepting client connection: Only connections from the same user that started this instance of Delve are allowed to connect. See --only-same-user.")
				s.triggerServerStop()
				return
			}
		}
333 334 335
		s.mu.Lock()
		s.conn = conn // closed in Stop()
		s.mu.Unlock()
336 337 338 339 340 341
		s.serveDAPCodec()
	}()
}

// serveDAPCodec reads and decodes requests from the client
// until it encounters an error or EOF, when it sends
342
// a disconnect signal and returns.
343 344 345 346 347 348 349 350 351 352 353 354
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 {
355
			select {
356
			case <-s.stopTriggered:
357
			default:
358 359 360 361
				if err != io.EOF {
					s.log.Error("DAP error: ", err)
				}
				s.triggerServerStop()
362 363 364 365 366 367 368
			}
			return
		}
		s.handleRequest(request)
	}
}

369 370 371 372 373 374 375 376 377 378
// 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))
	}
}

379
func (s *Server) handleRequest(request dap.Message) {
380
	defer s.recoverPanic(request)
381

382 383 384
	jsonmsg, _ := json.Marshal(request)
	s.log.Debug("[<- from client]", string(jsonmsg))

385 386 387 388 389
	if _, ok := request.(dap.RequestMessage); !ok {
		s.sendInternalErrorResponse(request.GetSeq(), fmt.Sprintf("Unable to process non-request %#v\n", request))
		return
	}

390
	// These requests, can be handled regardless of whether the targret is running
391 392
	switch request := request.(type) {
	case *dap.DisconnectRequest:
393
		// Required
394
		s.onDisconnectRequest(request)
395 396 397 398 399
		return
	case *dap.PauseRequest:
		// Required
		s.onPauseRequest(request)
		return
400
	case *dap.TerminateRequest:
401 402 403
		// Optional (capability ‘supportsTerminateRequest‘)
		// TODO: implement this request in V1
		s.onTerminateRequest(request)
404
		return
405
	case *dap.RestartRequest:
406 407 408
		// Optional (capability ‘supportsRestartRequest’)
		// TODO: implement this request in V1
		s.onRestartRequest(request)
409 410 411 412 413 414 415
		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.
416
	// --2-- Halt execution, process the request, maybe resume execution.
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	// --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)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
		case *dap.SetBreakpointsRequest:
			s.log.Debug("halting execution to set breakpoints")
			_, err := s.debugger.Command(&api.DebuggerCommand{Name: api.Halt}, nil)
			if err != nil {
				s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", err.Error())
				return
			}
			s.onSetBreakpointsRequest(request)
			// TODO(polina): consider resuming execution here automatically after suppressing
			// a stop event when an operation in doRunCommand returns. In case that operation
			// was already stopping for a different reason, we would need to examine the state
			// that is returned to determine if this halt was the cause of the stop or not.
			// We should stop with an event and not resume if one of the following is true:
			// - StopReason is anything but manual
			// - Any thread has a breakpoint or CallReturn set
			// - NextInProgress is false and the last command sent by the user was: next,
			//   step, stepOut, reverseNext, reverseStep or reverseStepOut
			// Otherwise, we can skip the stop event and resume the temporarily
			// interrupted process execution with api.DirectionCongruentContinue.
			// For this to apply in cases other than api.Continue, we would also need to
			// introduce a new version of halt that skips ClearInternalBreakpoints
			// in proc.(*Target).Continue, leaving NextInProgress as true.
465 466 467 468 469 470 471 472
		case *dap.SetFunctionBreakpointsRequest:
			s.log.Debug("halting execution to set breakpoints")
			_, err := s.debugger.Command(&api.DebuggerCommand{Name: api.Halt}, nil)
			if err != nil {
				s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", err.Error())
				return
			}
			s.onSetFunctionBreakpointsRequest(request)
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
		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 ---
493
	case *dap.ConfigurationDoneRequest:
494
		// Optional (capability ‘supportsConfigurationDoneRequest’)
495 496 497 498 499
		go func() {
			defer s.recoverPanic(request)
			s.onConfigurationDoneRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
500
	case *dap.ContinueRequest:
501
		// Required
502 503 504 505 506
		go func() {
			defer s.recoverPanic(request)
			s.onContinueRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
507
	case *dap.NextRequest:
508
		// Required
509 510 511 512 513
		go func() {
			defer s.recoverPanic(request)
			s.onNextRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
514
	case *dap.StepInRequest:
515
		// Required
516 517 518 519 520
		go func() {
			defer s.recoverPanic(request)
			s.onStepInRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
521
	case *dap.StepOutRequest:
522
		// Required
523 524 525 526 527
		go func() {
			defer s.recoverPanic(request)
			s.onStepOutRequest(request, resumeRequestLoop)
		}()
		<-resumeRequestLoop
528
	case *dap.StepBackRequest:
529 530 531
		// Optional (capability ‘supportsStepBack’)
		// TODO: implement this request in V1
		s.onStepBackRequest(request)
532
	case *dap.ReverseContinueRequest:
533 534 535
		// Optional (capability ‘supportsStepBack’)
		// TODO: implement this request in V1
		s.onReverseContinueRequest(request)
536 537
	//--- Synchronous requests ---
	case *dap.InitializeRequest:
538
		// Required
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
		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)
559
	case *dap.StackTraceRequest:
560 561
		// Required
		s.onStackTraceRequest(request)
562
	case *dap.ScopesRequest:
563 564
		// Required
		s.onScopesRequest(request)
565
	case *dap.VariablesRequest:
566 567
		// Required
		s.onVariablesRequest(request)
568 569 570
	case *dap.EvaluateRequest:
		// Required
		s.onEvaluateRequest(request)
571
	case *dap.SetVariableRequest:
572 573 574 575
		// Optional (capability ‘supportsSetVariable’)
		// Supported by vscode-go
		// TODO: implement this request in V0
		s.onSetVariableRequest(request)
576
	case *dap.SetExpressionRequest:
577 578 579
		// Optional (capability ‘supportsSetExpression’)
		// TODO: implement this request in V1
		s.onSetExpressionRequest(request)
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
	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)
596 597 598
	case *dap.ExceptionInfoRequest:
		// Optional (capability ‘supportsExceptionInfoRequest’)
		s.onExceptionInfoRequest(request)
599 600 601 602 603 604 605
	//--- 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)
606
	case *dap.SourceRequest:
607 608 609
		// Required
		// This does not make sense in the context of Go as
		// the source cannot be a string eval'ed at runtime.
610 611
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.TerminateThreadsRequest:
612
		// Optional (capability ‘supportsTerminateThreadsRequest’)
613 614
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.StepInTargetsRequest:
615
		// Optional (capability ‘supportsStepInTargetsRequest’)
616 617
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.GotoTargetsRequest:
618
		// Optional (capability ‘supportsGotoTargetsRequest’)
619 620
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.CompletionsRequest:
621
		// Optional (capability ‘supportsCompletionsRequest’)
622 623
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.DataBreakpointInfoRequest:
624
		// Optional (capability ‘supportsDataBreakpoints’)
625 626
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.SetDataBreakpointsRequest:
627
		// Optional (capability ‘supportsDataBreakpoints’)
628 629
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.BreakpointLocationsRequest:
630 631 632 633 634
		// Optional (capability ‘supportsBreakpointLocationsRequest’)
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.ModulesRequest:
		// Optional (capability ‘supportsModulesRequest’)
		// TODO: does this request make sense for delve?
635 636 637 638
		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
639 640
		// to handle.
		s.sendInternalErrorResponse(request.GetSeq(), fmt.Sprintf("Unable to process %#v\n", request))
641 642 643 644 645 646
	}
}

func (s *Server) send(message dap.Message) {
	jsonmsg, _ := json.Marshal(message)
	s.log.Debug("[-> to client]", string(jsonmsg))
647 648 649 650 651
	// 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()
652
	_ = dap.WriteProtocolMessage(s.conn, message)
653 654
}

655 656 657 658 659 660 661 662 663
func (s *Server) logToConsole(msg string) {
	s.send(&dap.OutputEvent{
		Event: *newEvent("output"),
		Body: dap.OutputEventBody{
			Output:   msg + "\n",
			Category: "console",
		}})
}

664
func (s *Server) onInitializeRequest(request *dap.InitializeRequest) {
665
	s.setClientCapabilities(request.Arguments)
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
	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
	}

682 683 684
	// TODO(polina): Respond with an error if debug session is in progress?
	response := &dap.InitializeResponse{Response: *newResponse(request.Request)}
	response.Body.SupportsConfigurationDoneRequest = true
685
	response.Body.SupportsConditionalBreakpoints = true
686
	response.Body.SupportsDelayedStackTraceLoading = true
687
	response.Body.SupportTerminateDebuggee = true
688
	response.Body.SupportsFunctionBreakpoints = true
689
	response.Body.SupportsExceptionInfoRequest = true
690
	response.Body.SupportsSetVariable = true
691
	response.Body.SupportsEvaluateForHovers = true
692 693 694 695 696 697 698 699 700
	// TODO(polina): support these requests in addition to vscode-go feature parity
	response.Body.SupportsTerminateRequest = false
	response.Body.SupportsRestartRequest = 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
701 702 703
	s.send(response)
}

704 705 706 707 708 709 710 711
func (s *Server) setClientCapabilities(args dap.InitializeRequestArguments) {
	s.clientCapabilities.supportsMemoryReferences = args.SupportsMemoryReferences
	s.clientCapabilities.supportsProgressReporting = args.SupportsProgressReporting
	s.clientCapabilities.supportsRunInTerminalRequest = args.SupportsRunInTerminalRequest
	s.clientCapabilities.supportsVariablePaging = args.SupportsVariablePaging
	s.clientCapabilities.supportsVariableType = args.SupportsVariableType
}

712 713 714
// 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"
715

716 717 718 719 720 721 722
func cleanExeName(name string) string {
	if runtime.GOOS == "windows" && filepath.Ext(name) != ".exe" {
		return name + ".exe"
	}
	return name
}

723
func (s *Server) onLaunchRequest(request *dap.LaunchRequest) {
724 725 726 727 728 729 730 731 732 733 734
	// 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
	}
735

736
	// TODO(polina): Respond with an error if debug session is in progress?
737
	program, ok := request.Arguments["program"].(string)
738 739
	if !ok || program == "" {
		s.sendErrorResponse(request.Request,
740
			FailedToLaunch, "Failed to launch",
741 742 743 744
			"The program attribute is missing in debug configuration.")
		return
	}

745 746 747
	if mode == "debug" || mode == "test" {
		output, ok := request.Arguments["output"].(string)
		if !ok || output == "" {
748
			output = cleanExeName(defaultDebugBinary)
749
		}
750
		debugbinary, err := filepath.Abs(output)
751 752 753 754 755
		if err != nil {
			s.sendInternalErrorResponse(request.Seq, err.Error())
			return
		}

756 757 758 759 760 761
		buildFlags := ""
		buildFlagsArg, ok := request.Arguments["buildFlags"]
		if ok {
			buildFlags, ok = buildFlagsArg.(string)
			if !ok {
				s.sendErrorResponse(request.Request,
762
					FailedToLaunch, "Failed to launch",
763 764 765
					fmt.Sprintf("'buildFlags' attribute '%v' in debug configuration is not a string.", buildFlagsArg))
				return
			}
766 767
		}

768
		s.log.Debugf("building binary at %s", debugbinary)
769
		var cmd string
770
		var out []byte
771 772
		switch mode {
		case "debug":
773
			cmd, out, err = gobuild.GoBuildCombinedOutput(debugbinary, []string{program}, buildFlags)
774
		case "test":
775
			cmd, out, err = gobuild.GoTestBuildCombinedOutput(debugbinary, []string{program}, buildFlags)
776 777
		}
		if err != nil {
778 779 780 781 782 783
			s.send(&dap.OutputEvent{
				Event: *newEvent("output"),
				Body: dap.OutputEventBody{
					Output:   fmt.Sprintf("Build Error: %s\n%s (%s)\n", cmd, strings.TrimSpace(string(out)), err.Error()),
					Category: "stderr",
				}})
784
			s.sendErrorResponse(request.Request,
785
				FailedToLaunch, "Failed to launch",
786
				"Build error: Check the debug console for details.")
787 788
			return
		}
789
		program = debugbinary
790
		s.mu.Lock()
791
		s.binaryToRemove = debugbinary
792
		s.mu.Unlock()
793 794
	}

795 796 797 798 799 800 801
	err := s.setLaunchAttachArgs(request)
	if err != nil {
		s.sendErrorResponse(request.Request,
			FailedToLaunch, "Failed to launch",
			err.Error())
		return
	}
802

803 804 805 806 807 808
	var targetArgs []string
	args, ok := request.Arguments["args"]
	if ok {
		argsParsed, ok := args.([]interface{})
		if !ok {
			s.sendErrorResponse(request.Request,
809
				FailedToLaunch, "Failed to launch",
810 811 812 813 814 815 816
				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,
817
					FailedToLaunch, "Failed to launch",
818 819 820 821 822 823 824 825
					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...)
826
	s.config.Debugger.WorkingDir = filepath.Dir(program)
827

828
	// Set the WorkingDir for this program to the one specified in the request arguments.
829
	wd, ok := request.Arguments["cwd"]
830 831 832 833 834
	if ok {
		wdParsed, ok := wd.(string)
		if !ok {
			s.sendErrorResponse(request.Request,
				FailedToLaunch, "Failed to launch",
835
				fmt.Sprintf("'cwd' attribute '%v' in debug configuration is not a string.", wd))
836 837 838 839 840
			return
		}
		s.config.Debugger.WorkingDir = wdParsed
	}

841
	s.log.Debugf("running program in %s\n", s.config.Debugger.WorkingDir)
842
	if noDebug, ok := request.Arguments["noDebug"].(bool); ok && noDebug {
843
		s.mu.Lock()
844
		cmd, err := s.startNoDebugProcess(program, targetArgs, s.config.Debugger.WorkingDir)
845
		s.mu.Unlock()
846 847
		if err != nil {
			s.sendErrorResponse(request.Request, FailedToLaunch, "Failed to launch", err.Error())
848 849
			return
		}
850 851 852 853 854 855
		// 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 {
856
			s.log.Debugf("program exited with error: %v", err)
857 858 859 860 861 862 863 864
		}
		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 {
865
			s.logToConsole(proc.ErrProcessExited{Pid: cmd.ProcessState.Pid(), Status: cmd.ProcessState.ExitCode()}.Error())
866 867 868
			s.send(&dap.TerminatedEvent{Event: *newEvent("terminated")})
		}
		return
869
	}
870

871 872 873 874 875 876
	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 {
877
		s.sendErrorResponse(request.Request, FailedToLaunch, "Failed to launch", err.Error())
878 879
		return
	}
880 881 882 883

	// 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'.
884 885 886 887
	s.send(&dap.InitializedEvent{Event: *newEvent("initialized")})
	s.send(&dap.LaunchResponse{Response: *newResponse(request.Request)})
}

888 889
// startNoDebugProcess is called from onLaunchRequest (run goroutine) and
// requires holding mu lock.
890
func (s *Server) startNoDebugProcess(program string, targetArgs []string, wd string) (*exec.Cmd, error) {
891
	if s.noDebugProcess != nil {
892
		return nil, fmt.Errorf("another launch request is in progress")
893
	}
894 895
	cmd := exec.Command(program, targetArgs...)
	cmd.Stdout, cmd.Stderr, cmd.Stdin, cmd.Dir = os.Stdout, os.Stderr, os.Stdin, wd
896
	if err := cmd.Start(); err != nil {
897
		return nil, err
898 899
	}
	s.noDebugProcess = cmd
900
	return cmd, nil
901 902
}

903 904
// stopNoDebugProcess is called from Stop (main goroutine) and
// onDisconnectRequest (run goroutine) and requires holding mu lock.
905
func (s *Server) stopNoDebugProcess() {
906
	if s.noDebugProcess == nil {
907 908 909
		// We already handled termination or there was never a process
		return
	}
910 911
	if s.noDebugProcess.ProcessState.Exited() {
		s.logToConsole(proc.ErrProcessExited{Pid: s.noDebugProcess.ProcessState.Pid(), Status: s.noDebugProcess.ProcessState.ExitCode()}.Error())
912 913
	} else {
		// TODO(hyangah): gracefully terminate the process and its children processes.
914 915
		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.
916
	}
917
	s.noDebugProcess = nil
918 919
}

920 921 922 923 924 925 926 927 928 929
// TODO(polina): support "remote" mode
func isValidLaunchMode(launchMode interface{}) bool {
	switch launchMode {
	case "exec", "debug", "test":
		return true
	}

	return false
}

930 931 932 933
// 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) {
934 935 936 937
	defer s.triggerServerStop()
	s.mu.Lock()
	defer s.mu.Unlock()

938
	var err error
939
	if s.debugger != nil {
940
		// We always kill launched programs.
941
		// In case of attach, we leave the program
942
		// running by default, which can be
943
		// overridden by an explicit request to terminate.
944 945
		killProcess := s.config.Debugger.AttachPid == 0 || request.Arguments.TerminateDebuggee
		err = s.stopDebugSession(killProcess)
946 947
	} else {
		s.stopNoDebugProcess()
948
	}
949
	if err != nil {
950 951 952 953
		s.sendErrorResponse(request.Request, DisconnectError, "Error while disconnecting", err.Error())
	} else {
		s.send(&dap.DisconnectResponse{Response: *newResponse(request.Request)})
	}
954
}
955

956 957 958 959 960 961 962 963 964
// 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
965 966 967 968 969 970
	// 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.
971 972
	state, err := s.debugger.Command(&api.DebuggerCommand{Name: api.Halt}, nil)
	if err == proc.ErrProcessDetached {
973
		s.log.Debug("halt returned error:", err)
974 975 976 977 978 979 980
		return nil
	}
	if err != nil {
		switch err.(type) {
		case proc.ErrProcessExited:
			exited = err
		default:
981
			s.log.Error("halt returned error:", err)
982 983 984
		}
	} else if state.Exited {
		exited = proc.ErrProcessExited{Pid: s.debugger.ProcessPid(), Status: state.ExitStatus}
985
		s.log.Debug("halt returned state:", exited)
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	}
	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
1008 1009
}

1010 1011 1012 1013 1014 1015
func (s *Server) isNoDebug() bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.noDebugProcess != nil
}

1016
func (s *Server) onSetBreakpointsRequest(request *dap.SetBreakpointsRequest) {
1017
	if s.isNoDebug() {
1018 1019 1020
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", "running in noDebug mode")
		return
	}
1021

1022
	if request.Arguments.Source.Path == "" {
1023 1024 1025 1026
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", "empty file path")
		return
	}

1027 1028 1029
	clientPath := request.Arguments.Source.Path
	serverPath := s.toServerPath(clientPath)

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
	// 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

1041 1042 1043 1044
	// Clear all existing breakpoints in the file that are not function breakpoints.
	if err := s.clearMatchingBreakpoints(func(bp *api.Breakpoint) bool { return bp.File == serverPath && bp.Name == "" }); err != nil {
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", err.Error())
		return
1045
	}
1046 1047

	// Set all requested breakpoints.
1048 1049
	response := &dap.SetBreakpointsResponse{Response: *newResponse(request.Request)}
	response.Body.Breakpoints = make([]dap.Breakpoint, len(request.Arguments.Breakpoints))
1050 1051
	for i, want := range request.Arguments.Breakpoints {
		got, err := s.debugger.CreateBreakpoint(
1052
			&api.Breakpoint{File: serverPath, Line: want.Line, Cond: want.Condition})
1053
		response.Body.Breakpoints[i].Verified = (err == nil)
1054
		if err != nil {
1055 1056 1057
			response.Body.Breakpoints[i].Line = want.Line
			response.Body.Breakpoints[i].Message = err.Error()
		} else {
1058
			response.Body.Breakpoints[i].Id = got.ID
1059
			response.Body.Breakpoints[i].Line = got.Line
1060
			response.Body.Breakpoints[i].Source = dap.Source{Name: request.Arguments.Source.Name, Path: clientPath}
1061 1062 1063 1064 1065 1066 1067
		}
	}
	s.send(response)
}

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

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
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 {
1090 1091
		e := &dap.StoppedEvent{
			Event: *newEvent("stopped"),
1092
			Body:  dap.StoppedEventBody{Reason: "entry", ThreadId: 1, AllThreadsStopped: true},
1093 1094 1095 1096
		}
		s.send(e)
	}
	s.send(&dap.ConfigurationDoneResponse{Response: *newResponse(request.Request)})
1097
	if !s.args.stopOnEntry {
1098
		s.doRunCommand(api.Continue, asyncSetupDone)
1099 1100 1101
	}
}

1102 1103 1104
// onContinueRequest handles 'continue' request.
// This is a mandatory request to support.
func (s *Server) onContinueRequest(request *dap.ContinueRequest, asyncSetupDone chan struct{}) {
1105 1106 1107
	s.send(&dap.ContinueResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ContinueResponseBody{AllThreadsContinued: true}})
1108
	s.doRunCommand(api.Continue, asyncSetupDone)
1109 1110
}

1111 1112 1113 1114 1115 1116 1117
func fnName(loc *proc.Location) string {
	if loc.Fn == nil {
		return "???"
	}
	return loc.Fn.Name
}

1118 1119 1120
// onThreadsRequest handles 'threads' request.
// This is a mandatory request to support.
// It is sent in response to configurationDone response and stopped events.
1121 1122 1123 1124 1125
func (s *Server) onThreadsRequest(request *dap.ThreadsRequest) {
	if s.debugger == nil {
		s.sendErrorResponse(request.Request, UnableToDisplayThreads, "Unable to display threads", "debugger is nil")
		return
	}
1126

1127 1128 1129
	gs, _, err := s.debugger.Goroutines(0, 0)
	if err != nil {
		switch err.(type) {
1130
		case proc.ErrProcessExited:
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
			// 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 {
1149 1150 1151 1152 1153 1154 1155 1156
		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()

1157
		for i, g := range gs {
1158 1159 1160 1161 1162 1163 1164
			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())
1165
			}
1166 1167 1168 1169 1170
			// 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
1171 1172
		}
	}
1173

1174 1175 1176 1177 1178 1179 1180
	response := &dap.ThreadsResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ThreadsResponseBody{Threads: threads},
	}
	s.send(response)
}

1181
// onAttachRequest handles 'attach' request.
1182
// This is a mandatory request to support.
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
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)
1197 1198
		err := s.setLaunchAttachArgs(request)
		if err != nil {
1199
			s.sendErrorResponse(request.Request, FailedToAttach, "Failed to attach", err.Error())
1200 1201
			return
		}
1202 1203 1204 1205 1206 1207 1208
		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())
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
			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)})
1223 1224
}

1225
// onNextRequest handles 'next' request.
1226
// This is a mandatory request to support.
1227
func (s *Server) onNextRequest(request *dap.NextRequest, asyncSetupDone chan struct{}) {
1228
	s.send(&dap.NextResponse{Response: *newResponse(request.Request)})
1229
	s.doStepCommand(api.Next, request.Arguments.ThreadId, asyncSetupDone)
1230 1231
}

1232
// onStepInRequest handles 'stepIn' request
1233
// This is a mandatory request to support.
1234
func (s *Server) onStepInRequest(request *dap.StepInRequest, asyncSetupDone chan struct{}) {
1235
	s.send(&dap.StepInResponse{Response: *newResponse(request.Request)})
1236
	s.doStepCommand(api.Step, request.Arguments.ThreadId, asyncSetupDone)
1237 1238
}

1239
// onStepOutRequest handles 'stepOut' request
1240
// This is a mandatory request to support.
1241
func (s *Server) onStepOutRequest(request *dap.StepOutRequest, asyncSetupDone chan struct{}) {
1242
	s.send(&dap.StepOutResponse{Response: *newResponse(request.Request)})
1243
	s.doStepCommand(api.StepOut, request.Arguments.ThreadId, asyncSetupDone)
1244 1245
}

1246 1247 1248 1249 1250 1251 1252 1253 1254
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
}

1255
// doStepCommand is a wrapper around doRunCommand that
1256 1257 1258 1259 1260 1261
// 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)
1262 1263 1264 1265 1266 1267 1268 1269 1270
	// All of the threads will be continued by this request, so we need to send
	// a continued event so the UI can properly reflect the current state.
	s.send(&dap.ContinuedEvent{
		Event: *newEvent("continued"),
		Body: dap.ContinuedEventBody{
			ThreadId:            threadId,
			AllThreadsContinued: true,
		},
	})
1271
	_, err := s.debugger.Command(&api.DebuggerCommand{Name: api.SwitchGoroutine, GoroutineID: threadId}, nil)
1272
	if err != nil {
1273
		s.log.Errorf("Error switching goroutines while stepping: %v", err)
1274 1275 1276 1277
		// 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
1278 1279 1280
		if state, err := s.debugger.State(false); err != nil {
			s.log.Errorf("Error retrieving state: %e", err)
		} else {
1281
			stopped.Body.ThreadId = stoppedGoroutineID(state)
1282 1283 1284 1285 1286 1287
		}
		stopped.Body.Reason = "error"
		stopped.Body.Text = err.Error()
		s.send(stopped)
		return
	}
1288
	s.doRunCommand(command, asyncSetupDone)
1289 1290
}

1291
// onPauseRequest handles 'pause' request.
1292
// This is a mandatory request to support.
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
func (s *Server) onPauseRequest(request *dap.PauseRequest) {
	_, err := s.debugger.Command(&api.DebuggerCommand{Name: api.Halt}, nil)
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToHalt, "Unable to halt execution", err.Error())
		return
	}
	s.send(&dap.PauseResponse{Response: *newResponse(request.Request)})
	// No need to send any event here.
	// If we received this request while stopped, there already was an event for the stop.
	// If we received this while running, then doCommand will unblock and trigger the right
	// event, using debugger.StopReason because manual stop reason always wins even if we
	// simultaneously receive a manual stop request and hit a breakpoint.
1305 1306
}

1307 1308 1309 1310 1311 1312 1313 1314
// 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.
1315
// This is a mandatory request to support.
1316 1317
// As per DAP spec, this request only gets triggered as a follow-up
// to a successful threads request as part of the "request waterfall".
1318 1319
func (s *Server) onStackTraceRequest(request *dap.StackTraceRequest) {
	goroutineID := request.Arguments.ThreadId
1320
	frames, err := s.debugger.Stacktrace(goroutineID, s.args.stackTraceDepth, 0)
1321 1322 1323 1324 1325
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToProduceStackTrace, "Unable to produce stack trace", err.Error())
		return
	}

1326 1327 1328
	stackFrames := make([]dap.StackFrame, len(frames))
	for i, frame := range frames {
		loc := &frame.Call
1329
		uniqueStackFrameID := s.stackFrameHandles.create(stackFrame{goroutineID, i})
1330
		stackFrames[i] = dap.StackFrame{Id: uniqueStackFrameID, Line: loc.Line, Name: fnName(loc)}
1331
		if loc.File != "<autogenerated>" {
1332 1333
			clientPath := s.toClientPath(loc.File)
			stackFrames[i].Source = dap.Source{Name: filepath.Base(clientPath), Path: clientPath}
1334 1335 1336
		}
		stackFrames[i].Column = 0
	}
1337 1338 1339 1340 1341
	// 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.
1342 1343 1344 1345 1346 1347 1348 1349
	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),
1350
		Body:     dap.StackTraceResponseBody{StackFrames: stackFrames, TotalFrames: len(frames)},
1351 1352
	}
	s.send(response)
1353 1354
}

1355
// onScopesRequest handles 'scopes' requests.
1356
// This is a mandatory request to support.
1357 1358 1359
// 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.
1360 1361 1362 1363 1364 1365 1366
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
	}

1367 1368
	goid := sf.(stackFrame).goroutineID
	frame := sf.(stackFrame).frameIndex
1369

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
	// Check if the function is optimized.
	fn, err := s.debugger.Function(goid, frame, 0, DefaultLoadConfig)
	if fn == nil || err != nil {
		s.sendErrorResponse(request.Request, UnableToListArgs, "Unable to find enclosing function", err.Error())
		return
	}
	suffix := ""
	if fn.Optimized() {
		suffix = " (warning: optimized function)"
	}
1380
	// Retrieve arguments
1381
	args, err := s.debugger.FunctionArguments(goid, frame, 0, DefaultLoadConfig)
1382 1383 1384 1385
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToListArgs, "Unable to list args", err.Error())
		return
	}
1386
	argScope := &fullyQualifiedVariable{&proc.Variable{Name: fmt.Sprintf("Arguments%s", suffix), Children: slicePtrVarToSliceVar(args)}, "", true}
1387 1388

	// Retrieve local variables
1389
	locals, err := s.debugger.LocalVariables(goid, frame, 0, DefaultLoadConfig)
1390
	if err != nil {
1391
		s.sendErrorResponse(request.Request, UnableToListLocals, "Unable to list locals", err.Error())
1392 1393
		return
	}
1394
	locScope := &fullyQualifiedVariable{&proc.Variable{Name: fmt.Sprintf("Locals%s", suffix), Children: slicePtrVarToSliceVar(locals)}, "", true}
1395 1396 1397 1398 1399

	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}

1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
	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)
1416
		globals, err := s.debugger.PackageVariables(currPkgFilter, DefaultLoadConfig)
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
		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+".")
		}

1427
		globScope := &fullyQualifiedVariable{&proc.Variable{
1428 1429
			Name:     fmt.Sprintf("Globals (package %s)", currPkg),
			Children: slicePtrVarToSliceVar(globals),
1430
		}, currPkg, true}
1431 1432 1433
		scopeGlobals := dap.Scope{Name: globScope.Name, VariablesReference: s.variableHandles.create(globScope)}
		scopes = append(scopes, scopeGlobals)
	}
1434 1435 1436 1437 1438
	response := &dap.ScopesResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ScopesResponseBody{Scopes: scopes},
	}
	s.send(response)
1439 1440
}

1441 1442 1443 1444 1445 1446 1447 1448
func slicePtrVarToSliceVar(vars []*proc.Variable) []proc.Variable {
	r := make([]proc.Variable, len(vars))
	for i := range vars {
		r[i] = *vars[i]
	}
	return r
}

1449
// onVariablesRequest handles 'variables' requests.
1450
// This is a mandatory request to support.
1451
func (s *Server) onVariablesRequest(request *dap.VariablesRequest) {
1452 1453
	ref := request.Arguments.VariablesReference
	v, ok := s.variableHandles.get(ref)
1454
	if !ok {
1455
		s.sendErrorResponse(request.Request, UnableToLookupVariable, "Unable to lookup variable", fmt.Sprintf("unknown reference %d", ref))
1456 1457
		return
	}
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476

	children, err := s.childrenToDAPVariables(v)
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToLookupVariable, "Unable to lookup variable", err.Error())
		return
	}
	response := &dap.VariablesResponse{
		Response: *newResponse(request.Request),
		Body:     dap.VariablesResponseBody{Variables: children},
	}
	s.send(response)
}

// childrenToDAPVariables returns the DAP presentation of the referenced variable's children.
func (s *Server) childrenToDAPVariables(v *fullyQualifiedVariable) ([]dap.Variable, error) {
	// TODO(polina): consider convertVariableToString instead of convertVariable
	// and avoid unnecessary creation of variable handles when this is called to
	// compute evaluate names when this is called from onSetVariableRequest.
	var children []dap.Variable
1477 1478 1479 1480 1481 1482 1483

	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.
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
			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)
1500 1501
			keyType := s.getTypeIfSupported(keyv)
			valType := s.getTypeIfSupported(valv)
1502 1503 1504 1505 1506 1507
			// 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),
1508
					EvaluateName:       keyexpr,
1509
					Type:               keyType,
1510 1511 1512 1513 1514
					Value:              key,
					VariablesReference: keyref,
				}
				valvar := dap.Variable{
					Name:               fmt.Sprintf("[val %d]", kvIndex),
1515
					EvaluateName:       valexpr,
1516
					Type:               valType,
1517 1518 1519 1520 1521
					Value:              val,
					VariablesReference: valref,
				}
				children = append(children, keyvar, valvar)
			} else { // At least one is a scalar
1522 1523 1524 1525
				keyValType := valType
				if len(keyType) > 0 && len(valType) > 0 {
					keyValType = fmt.Sprintf("%s: %s", keyType, valType)
				}
1526
				kvvar := dap.Variable{
1527 1528
					Name:         key,
					EvaluateName: valexpr,
1529
					Type:         keyValType,
1530
					Value:        val,
1531 1532
				}
				if keyref != 0 { // key is a type to be expanded
1533 1534 1535 1536
					if len(key) > DefaultLoadConfig.MaxStringLen {
						// Truncate and make unique
						kvvar.Name = fmt.Sprintf("%s... @ %#x", key[0:DefaultLoadConfig.MaxStringLen], keyv.Addr)
					}
1537 1538 1539 1540 1541 1542 1543 1544 1545
					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))
1546
		for i := range v.Children {
1547 1548
			cfqname := fmt.Sprintf("%s[%d]", v.fullyQualifiedNameOrExpr, i)
			cvalue, cvarref := s.convertVariable(&v.Children[i], cfqname)
1549 1550
			children[i] = dap.Variable{
				Name:               fmt.Sprintf("[%d]", i),
1551
				EvaluateName:       cfqname,
1552
				Type:               s.getTypeIfSupported(&v.Children[i]),
1553 1554
				Value:              cvalue,
				VariablesReference: cvarref,
1555 1556 1557 1558
			}
		}
	default:
		children = make([]dap.Variable, len(v.Children))
1559 1560
		for i := range v.Children {
			c := &v.Children[i]
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
			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)
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586

			// 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)
			}

1587
			children[i] = dap.Variable{
1588
				Name:               name,
1589
				EvaluateName:       cfqname,
1590
				Type:               s.getTypeIfSupported(c),
1591 1592
				Value:              cvalue,
				VariablesReference: cvarref,
1593 1594 1595
			}
		}
	}
1596
	return children, nil
1597 1598
}

1599 1600 1601 1602 1603 1604 1605
func (s *Server) getTypeIfSupported(v *proc.Variable) string {
	if !s.clientCapabilities.supportsVariableType {
		return ""
	}
	return v.TypeString()
}

1606 1607
// convertVariable converts proc.Variable to dap.Variable value and reference
// while keeping track of the full qualified name or load expression.
1608
// Variable reference is used to keep track of the children associated with each
1609 1610 1611 1612 1613 1614
// 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).
1615 1616
func (s *Server) convertVariable(v *proc.Variable, qualifiedNameOrExpr string) (value string, variablesReference int) {
	return s.convertVariableWithOpts(v, qualifiedNameOrExpr, false)
1617 1618 1619
}

func (s *Server) convertVariableToString(v *proc.Variable) string {
1620
	val, _ := s.convertVariableWithOpts(v, "", true)
1621 1622 1623
	return val
}

1624
// convertVariableWithOpts allows to skip reference generation in case all we need is
1625
// a string representation of the variable.
1626
func (s *Server) convertVariableWithOpts(v *proc.Variable, qualifiedNameOrExpr string, skipRef bool) (value string, variablesReference int) {
1627 1628 1629 1630
	maybeCreateVariableHandle := func(v *proc.Variable) int {
		if skipRef {
			return 0
		}
1631
		return s.variableHandles.create(&fullyQualifiedVariable{v, qualifiedNameOrExpr, false /*not a scope*/})
1632
	}
1633
	value = api.ConvertVar(v).SinglelineString()
1634
	if v.Unreadable != nil {
1635 1636
		return
	}
1637

1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
	// 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
	}
1666

1667 1668
	switch v.Kind {
	case reflect.UnsafePointer:
1669
		// Skip child reference
1670
	case reflect.Ptr:
1671
		if v.DwarfType != nil && len(v.Children) > 0 && v.Children[0].Addr != 0 && v.Children[0].Kind != reflect.Invalid {
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
			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 {
1698 1699
				variablesReference = maybeCreateVariableHandle(v)
			}
1700
		}
1701
	case reflect.Slice, reflect.Array:
1702
		if v.Len > int64(len(v.Children)) { // Not fully loaded
1703 1704 1705 1706 1707
			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
			}
1708
		}
1709
		if v.Base != 0 && len(v.Children) > 0 {
1710
			variablesReference = maybeCreateVariableHandle(v)
1711 1712
		}
	case reflect.Map:
1713
		if v.Len > int64(len(v.Children)/2) { // Not fully loaded
1714 1715 1716 1717 1718
			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
			}
1719
		}
1720
		if v.Base != 0 && len(v.Children) > 0 {
1721
			variablesReference = maybeCreateVariableHandle(v)
1722
		}
1723 1724
	case reflect.String:
		// TODO(polina): implement auto-loading here
1725
	case reflect.Interface:
1726
		if v.Addr != 0 && len(v.Children) > 0 && v.Children[0].Kind != reflect.Invalid && v.Children[0].Addr != 0 {
1727 1728
			if v.Children[0].OnlyAddr { // Not loaded
				value = reloadVariable(v, qualifiedNameOrExpr)
1729 1730
			}
			if !v.Children[0].OnlyAddr {
1731 1732 1733 1734 1735
				variablesReference = maybeCreateVariableHandle(v)
			}
		}
	case reflect.Struct:
		if v.Len > int64(len(v.Children)) { // Not fully loaded
1736 1737 1738 1739 1740
			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
			}
1741 1742
		}
		if len(v.Children) > 0 {
1743
			variablesReference = maybeCreateVariableHandle(v)
1744
		}
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
	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
1759
	default: // Complex, Scalar, Chan, Func
1760
		if len(v.Children) > 0 {
1761
			variablesReference = maybeCreateVariableHandle(v)
1762 1763 1764
		}
	}
	return
1765 1766
}

1767
// onEvaluateRequest handles 'evalute' requests.
1768
// This is a mandatory request to support.
1769 1770 1771 1772 1773 1774 1775
// 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) {
1776
	showErrorToUser := request.Arguments.Context != "watch" && request.Arguments.Context != "repl" && request.Arguments.Context != "hover"
1777 1778 1779 1780
	if s.debugger == nil {
		s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", "debugger is nil", showErrorToUser)
		return
	}
1781

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
	// 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}
1793 1794
		expr := strings.Replace(request.Arguments.Expression, "call ", "", 1)
		_, retVars, err := s.doCall(goid, frame, expr)
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), 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, ", "),
1811
				VariablesReference: s.variableHandles.create(&fullyQualifiedVariable{retVarsAsVar, "", false /*not a scope*/}),
1812 1813 1814
			}
		}
	} else { // {expression}
1815
		exprVar, err := s.debugger.EvalVariableInScope(goid, frame, 0, request.Arguments.Expression, DefaultLoadConfig)
1816 1817 1818 1819
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
			return
		}
1820 1821 1822
		// 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))
1823 1824 1825
		response.Body = dap.EvaluateResponseBody{Result: exprVal, VariablesReference: exprRef}
	}
	s.send(response)
1826 1827
}

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
func (s *Server) doCall(goid, frame int, expr string) (*api.DebuggerState, []*proc.Variable, error) {
	// 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 {
		return nil, nil, fmt.Errorf("call is only supported with topmost stack frame")
	}
	stateBeforeCall, err := s.debugger.State( /*nowait*/ true)
	if err != nil {
		return nil, nil, err
	}
	// 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.
	state, err := s.debugger.Command(&api.DebuggerCommand{
		Name:                 api.Call,
		ReturnInfoLoadConfig: api.LoadConfigFromProc(&DefaultLoadConfig),
		Expr:                 expr,
		UnsafeCall:           false,
		GoroutineID:          goid,
	}, nil)
	if _, isexited := err.(proc.ErrProcessExited); isexited || err == nil && state.Exited {
		e := &dap.TerminatedEvent{Event: *newEvent("terminated")}
		s.send(e)
		return nil, nil, errors.New("terminated")
	}
	if err != nil {
		return nil, nil, err
	}

	// 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
	found := false
	for _, t := range state.Threads {
		if t.GoroutineID == stateBeforeCall.SelectedGoroutine.ID &&
			t.Line == stateBeforeCall.SelectedGoroutine.CurrentLoc.Line && t.CallReturn {
			found = true
			// The call completed. Get the return values.
			retVars, err = s.debugger.FindThreadReturnValues(t.ID, DefaultLoadConfig)
			if err != nil {
				return nil, nil, err
			}
			break
		}
	}
	// Normal function calls expect return values, but call commands
	// used for variable assignments do not return a value when they succeed.
	// In go '=' is not an operator. Check if go/parser complains.
	// If the above Call command passed but the expression is not a valid
	// go expression, we just handled a variable assignment request.
	isAssignment := false
	if _, err := parser.ParseExpr(expr); err != nil {
		isAssignment = true
	}

	// note: as described in https://github.com/golang/go/issues/25578, function call injection
	// causes to resume the entire Go process. Due to this limitation, there is no guarantee
	// that the process is in the same state even after the injected call returns normally
	// without any surprises such as breakpoints or panic. To handle this correctly we need
	// to reset all the handles (both variables and stack frames).
	//
	// We considered sending a stopped event after each call unconditionally, but a stopped
	// event can be expensive and can interact badly with the client-side optimization
	// to refresh information. For example, VS Code reissues scopes/evaluate (for watch) after
	// completing a setVariable or evaluate request for repl context. Thus, for now, we
	// do not trigger a stopped event and hope editors to refetch the updated state as soon
	// as the user resumes debugging.

	if !found || !isAssignment && retVars == nil {
		// The call got interrupted by a stop (e.g. breakpoint in injected
		// function call or in another goroutine).
		s.resetHandlesForStoppedEvent()
		s.sendStoppedEvent(state)

		// 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
		// instead of returning an error 'call stopped' here.
		return nil, nil, errors.New("call stopped")
	}
	return state, retVars, nil
}

func (s *Server) sendStoppedEvent(state *api.DebuggerState) {
	stopped := &dap.StoppedEvent{Event: *newEvent("stopped")}
	stopped.Body.AllThreadsStopped = true
	stopped.Body.ThreadId = stoppedGoroutineID(state)
	stopped.Body.Reason = s.debugger.StopReason().String()
	s.send(stopped)
}

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
// 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)
}

1936 1937 1938 1939
// functionBpPrefix is the prefix of bp.Name for every breakpoint bp set
// in this request.
const functionBpPrefix = "functionBreakpoint"

1940
func (s *Server) onSetFunctionBreakpointsRequest(request *dap.SetFunctionBreakpointsRequest) {
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
	if s.noDebugProcess != nil {
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", "running in noDebug mode")
		return
	}

	// According to the spec, setFunctionBreakpoints "replaces all existing function
	// breakpoints with new function breakpoints." The simplest way is
	// to clear all and then set all.

	// Clear all existing function breakpoints in the file.
	// Function breakpoints are set with the Name field set to be the
	// function name. We cannot use FunctionName to determine this, because
	// the debugger sets the function name for all breakpoints.
	if err := s.clearMatchingBreakpoints(func(bp *api.Breakpoint) bool { return strings.HasPrefix(bp.Name, functionBpPrefix) }); err != nil {
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", err.Error())
		return
	}

	// Set all requested breakpoints.
	response := &dap.SetFunctionBreakpointsResponse{Response: *newResponse(request.Request)}
	response.Body.Breakpoints = make([]dap.Breakpoint, len(request.Arguments.Breakpoints))
	for i, want := range request.Arguments.Breakpoints {
		spec, err := locspec.Parse(want.Name)
		if err != nil {
			response.Body.Breakpoints[i].Message = err.Error()
			continue
		}
		if loc, ok := spec.(*locspec.NormalLocationSpec); !ok || loc.FuncBase == nil {
			// Other locations do not make sense in the context of function breakpoints.
			// Regex locations are likely to resolve to multiple places and offset locations
			// are only meaningful at the time the breakpoint was created.
			response.Body.Breakpoints[i].Message = fmt.Sprintf("breakpoint name %q could not be parsed as a function. name must be in the format 'funcName', 'funcName:line' or 'fileName:line'.", want.Name)
			continue
		}

		if want.Name[0] == '.' {
			response.Body.Breakpoints[i].Message = "breakpoint names that are relative paths are not supported."
			continue
		}
		// Find the location of the function name. CreateBreakpoint requires the name to include the base
		// (e.g. main.functionName is supported but not functionName).
		// We first find the location of the function, and then set breakpoints for that location.
		locs, err := s.debugger.FindLocationSpec(-1, 0, 0, want.Name, spec, true, s.args.substitutePathClientToServer)
		if err != nil {
			response.Body.Breakpoints[i].Message = err.Error()
			continue
		}
		if len(locs) == 0 {
			response.Body.Breakpoints[i].Message = fmt.Sprintf("no location found for %q", want.Name)
			continue
		}
		if len(locs) > 0 {
			s.log.Debugf("multiple locations found for %s", want.Name)
			response.Body.Breakpoints[i].Message = fmt.Sprintf("multiple locations found for %s, function breakpoint is only set for the first location", want.Name)
		}

		// Set breakpoint using the PCs that were found.
		loc := locs[0]
		got, err := s.debugger.CreateBreakpoint(
			&api.Breakpoint{Name: fmt.Sprintf("%s%d", functionBpPrefix, i), Addr: loc.PC, Addrs: loc.PCs, Cond: want.Condition})
		response.Body.Breakpoints[i].Verified = (err == nil)
		if err != nil {
			response.Body.Breakpoints[i].Message = err.Error()
		} else {
			response.Body.Breakpoints[i].Id = got.ID
			response.Body.Breakpoints[i].Line = got.Line
			response.Body.Breakpoints[i].Source = dap.Source{Name: filepath.Base(got.File), Path: got.File}
		}
	}
	s.send(response)
}

func (s *Server) clearMatchingBreakpoints(matchCondition func(*api.Breakpoint) bool) error {
	existing := s.debugger.Breakpoints()
	for _, bp := range existing {
		// Skip special breakpoints such as for panic.
		if bp.ID < 0 {
			continue
		}
		// Skip breakpoints that do not meet the condition.
		if !matchCondition(bp) {
			continue
		}
		_, err := s.debugger.ClearBreakpoint(bp)
		if err != nil {
			return err
		}
	}
	return nil
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
}

// 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)
}

2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
// computeEvaluateName finds the named child, and computes its evaluate name.
func (s *Server) computeEvaluateName(v *fullyQualifiedVariable, cname string) (string, error) {
	children, err := s.childrenToDAPVariables(v)
	if err != nil {
		return "", err
	}
	for _, c := range children {
		if c.Name == cname {
			if c.EvaluateName != "" {
				return c.EvaluateName, nil
			}
			return "", errors.New("cannot set the variable without evaluate name")
		}
	}
	return "", errors.New("failed to find the named variable")
}

// onSetVariableRequest handles 'setVariable' requests.
func (s *Server) onSetVariableRequest(request *dap.SetVariableRequest) {
	arg := request.Arguments

	v, ok := s.variableHandles.get(arg.VariablesReference)
	if !ok {
		s.sendErrorResponse(request.Request, UnableToSetVariable, "Unable to lookup variable", fmt.Sprintf("unknown reference %d", arg.VariablesReference))
		return
	}
	// We need to translate the arg.Name to its evaluateName if the name
	// refers to a field or element of a variable.
	// https://github.com/microsoft/vscode/issues/120774
	evaluateName, err := s.computeEvaluateName(v, arg.Name)
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToSetVariable, "Unable to set variable", err.Error())
		return
	}

	// By running EvalVariableInScope, we get the type info of the variable
	// that can be accessed with the evaluateName, and ensure the variable we are
	// trying to update is valid and accessible from the top most frame & the
	// current goroutine.
	goid, frame := -1, 0
	evaluated, err := s.debugger.EvalVariableInScope(goid, frame, 0, evaluateName, DefaultLoadConfig)
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToSetVariable, "Unable to lookup variable", err.Error())
		return
	}

	useFnCall := false
	switch evaluated.Kind {
	case reflect.String:
		useFnCall = true
	default:
		// TODO(hyangah): it's possible to set a non-string variable using (`call i = fn()`)
		// and we don't support it through the Set Variable request yet.
		// If we want to support it for non-string types, we need to parse arg.Value.
	}

	if useFnCall {
		// TODO(hyangah): function call injection currentlly allows to assign return values of
		// a function call to variables. So, curious users would find set variable
		// on string would accept expression like `fn()`.
		if state, retVals, err := s.doCall(goid, frame, fmt.Sprintf("%v=%v", evaluateName, arg.Value)); err != nil {
			s.sendErrorResponse(request.Request, UnableToSetVariable, "Unable to set variable", err.Error())
			return
		} else if retVals != nil {
			// The assignment expression isn't supposed to return values, but we got them.
			// That indicates something went wrong (e.g. panic).
			// TODO: isn't it simpler to do this in s.doCall?
			s.resetHandlesForStoppedEvent()
			s.sendStoppedEvent(state)

			var r []string
			for _, v := range retVals {
				r = append(r, s.convertVariableToString(v))
			}
			msg := "interrupted"
			if len(r) > 0 {
				msg = "interrupted:" + strings.Join(r, ", ")
			}

			s.sendErrorResponse(request.Request, UnableToSetVariable, "Unable to set variable", msg)
			return
		}
	} else {
		if err := s.debugger.SetVariableInScope(goid, frame, 0, evaluateName, arg.Value); err != nil {
			s.sendErrorResponse(request.Request, UnableToSetVariable, "Unable to set variable", err.Error())
			return
		}
	}
	// * Note on inconsistent state after set variable:
	//
	// The variable handles may be in inconsistent state - for example,
	// let's assume there are two aliased variables pointing to the same
	// memory and both are already loaded and cached in the variable handle.
	// VSCode tries to locally update the UI when the set variable
	// request succeeds, and may issue additional scopes or evaluate requests
	// to update the variable/watch sections if necessary.
	//
	// More complicated situation is when the set variable involves call
	// injection - after the injected call is completed, the debugee can
	// be in a completely different state (see the note in doCall) due to
	// how the call injection is implemented. Ideally, we need to also refresh
	// the stack frames but that is complicated. For now we don't try to actively
	// invalidate this state hoping that the editors will refetch the state
	// as soon as the user resumes debugging.

	response := &dap.SetVariableResponse{Response: *newResponse(request.Request)}
	response.Body.Value = arg.Value
	// TODO(hyangah): instead of arg.Value, reload the variable and return
	// the presentation of the new value.
	s.send(response)
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
}

// 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)
}

2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
// onExceptionInfoRequest handles 'exceptionInfo' requests.
// Capability 'supportsExceptionInfoRequest' is set in 'initialize' response.
func (s *Server) onExceptionInfoRequest(request *dap.ExceptionInfoRequest) {
	goroutineID := request.Arguments.ThreadId
	var body dap.ExceptionInfoResponseBody
	// Get the goroutine and the current state.
	g, err := s.debugger.FindGoroutine(goroutineID)
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToGetExceptionInfo, "Unable to get exception info", err.Error())
		return
	}
	if g == nil {
		s.sendErrorResponse(request.Request, UnableToGetExceptionInfo, "Unable to get exception info", fmt.Sprintf("could not find goroutine %d", goroutineID))
		return
	}
	var bpState *proc.BreakpointState
	if g.Thread != nil {
		bpState = g.Thread.Breakpoint()
	}
	// Check if this goroutine ID is stopped at a breakpoint.
	if bpState != nil && bpState.Breakpoint != nil && (bpState.Breakpoint.Name == proc.FatalThrow || bpState.Breakpoint.Name == proc.UnrecoveredPanic) {
		switch bpState.Breakpoint.Name {
		case proc.FatalThrow:
			// TODO(suzmue): add the fatal throw reason to body.Description.
			body.ExceptionId = "fatal error"
		case proc.UnrecoveredPanic:
			body.ExceptionId = "panic"
			// Attempt to get the value of the panic message.
			exprVar, err := s.debugger.EvalVariableInScope(goroutineID, 0, 0, "(*msgs).arg.(data)", DefaultLoadConfig)
			if err == nil {
				body.Description = exprVar.Value.String()
			}
		}
	} else {
		// If this thread is not stopped on a breakpoint, then a runtime error must have occurred.
		// If we do not have any error saved, or if this thread is not current thread,
		// return an error.
		if s.exceptionErr == nil {
			s.sendErrorResponse(request.Request, UnableToGetExceptionInfo, "Unable to get exception info", "no runtime error found")
			return
		}

		state, err := s.debugger.State( /*nowait*/ true)
		if err != nil {
			s.sendErrorResponse(request.Request, UnableToGetExceptionInfo, "Unable to get exception info", err.Error())
			return
		}
		if state == nil || state.CurrentThread == nil || g.Thread == nil || state.CurrentThread.ID != g.Thread.ThreadID() {
			s.sendErrorResponse(request.Request, UnableToGetExceptionInfo, "Unable to get exception info", fmt.Sprintf("no exception found for goroutine %d", goroutineID))
			return
		}
		body.ExceptionId = "runtime error"
		body.Description = s.exceptionErr.Error()
		if body.Description == "bad access" {
			body.Description = BetterBadAccessError
		}
	}

	frames, err := s.debugger.Stacktrace(goroutineID, s.args.stackTraceDepth, 0)
	if err == nil && len(frames) > 0 {
		apiFrames, err := s.debugger.ConvertStacktrace(frames, nil)
		if err == nil {
			var buf bytes.Buffer
			fmt.Fprintln(&buf, "Stack:")
			terminal.PrintStack(s.toClientPath, &buf, apiFrames, "\t", false)
			body.Details.StackTrace = buf.String()
		}
	}
	response := &dap.ExceptionInfoResponse{
		Response: *newResponse(request.Request),
		Body:     body,
	}
	s.send(response)
}

2261
// sendErrorResponseWithOpts offers configuration options.
2262 2263
//   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) {
2264 2265 2266 2267 2268 2269 2270 2271
	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)
2272
	er.Body.Error.ShowUser = showUser
2273
	s.log.Debug(er.Body.Error.Format)
2274 2275 2276
	s.send(er)
}

2277 2278 2279 2280 2281
// 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*/)
}

2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
// 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)
2293
	s.log.Debug(er.Body.Error.Format)
2294 2295 2296
	s.send(er)
}

2297 2298
func (s *Server) sendUnsupportedErrorResponse(request dap.Request) {
	s.sendErrorResponse(request, UnsupportedCommand, "Unsupported command",
2299
		fmt.Sprintf("cannot process %q request", request.Command))
2300 2301
}

2302 2303
func (s *Server) sendNotYetImplementedErrorResponse(request dap.Request) {
	s.sendErrorResponse(request, NotYetImplemented, "Not yet implemented",
2304
		fmt.Sprintf("cannot process %q request", request.Command))
2305 2306
}

2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
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,
	}
}

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

2332
func (s *Server) resetHandlesForStoppedEvent() {
2333 2334
	s.stackFrameHandles.reset()
	s.variableHandles.reset()
2335
	s.exceptionErr = nil
2336 2337
}

2338
// doRunCommand runs a debugger command until it stops on
2339
// termination, error, breakpoint, etc, when an appropriate
2340 2341 2342 2343
// 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.
2344 2345
func (s *Server) doRunCommand(command string, asyncSetupDone chan struct{}) {
	// TODO(polina): it appears that debugger.Command doesn't always close
2346 2347 2348 2349
	// 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)
2350
	if _, isexited := err.(proc.ErrProcessExited); isexited || err == nil && state.Exited {
2351
		s.send(&dap.TerminatedEvent{Event: *newEvent("terminated")})
2352 2353
		return
	}
2354

2355
	stopReason := s.debugger.StopReason()
2356 2357 2358 2359 2360
	file, line := "?", -1
	if state != nil && state.CurrentThread != nil {
		file, line = state.CurrentThread.File, state.CurrentThread.Line
	}
	s.log.Debugf("%q command stopped - reason %q, location %s:%d", command, stopReason, file, line)
2361

2362
	s.resetHandlesForStoppedEvent()
2363 2364 2365 2366
	stopped := &dap.StoppedEvent{Event: *newEvent("stopped")}
	stopped.Body.AllThreadsStopped = true

	if err == nil {
2367 2368 2369
		// TODO(suzmue): If stopped.Body.ThreadId is not a valid goroutine
		// then the stopped reason does not show up anywhere in the
		// vscode ui.
2370
		stopped.Body.ThreadId = stoppedGoroutineID(state)
2371

2372
		switch stopReason {
2373
		case proc.StopNextFinished:
2374
			stopped.Body.Reason = "step"
2375 2376
		case proc.StopManual: // triggered by halt
			stopped.Body.Reason = "pause"
2377
		case proc.StopUnknown: // can happen while terminating
2378
			stopped.Body.Reason = "unknown"
2379 2380
		case proc.StopWatchpoint:
			stopped.Body.Reason = "data breakpoint"
2381 2382 2383
		default:
			stopped.Body.Reason = "breakpoint"
		}
2384
		if state.CurrentThread != nil && state.CurrentThread.Breakpoint != nil {
2385 2386
			switch state.CurrentThread.Breakpoint.Name {
			case proc.FatalThrow:
2387 2388
				stopped.Body.Reason = "exception"
				stopped.Body.Description = "Paused on fatal error"
2389
			case proc.UnrecoveredPanic:
2390 2391
				stopped.Body.Reason = "exception"
				stopped.Body.Description = "Paused on panic"
2392
			}
2393 2394 2395
			if strings.HasPrefix(state.CurrentThread.Breakpoint.Name, functionBpPrefix) {
				stopped.Body.Reason = "function breakpoint"
			}
2396
		}
2397
	} else {
2398
		s.exceptionErr = err
2399
		s.log.Error("runtime error: ", err)
2400 2401
		stopped.Body.Reason = "exception"
		stopped.Body.Description = "Paused on runtime error"
2402 2403 2404 2405 2406 2407 2408
		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 {
2409
			stopped.Body.ThreadId = stoppedGoroutineID(state)
2410
		}
2411
	}
2412 2413 2414 2415 2416

	// 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)
2417
}
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439

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
}