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

import (
	"bufio"
	"encoding/json"
	"fmt"
15
	"go/constant"
16 17
	"io"
	"net"
18
	"os"
19
	"path/filepath"
20
	"reflect"
21
	"regexp"
22
	"strings"
23

24
	"github.com/go-delve/delve/pkg/gobuild"
25 26 27 28 29
	"github.com/go-delve/delve/pkg/logflags"
	"github.com/go-delve/delve/pkg/proc"
	"github.com/go-delve/delve/service"
	"github.com/go-delve/delve/service/api"
	"github.com/go-delve/delve/service/debugger"
30
	"github.com/google/go-dap"
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
	"github.com/sirupsen/logrus"
)

// Server implements a DAP server that can accept a single client for
// a single debug session. It does not support restarting.
// The server operates via two goroutines:
// (1) Main goroutine where the server is created via NewServer(),
// started via Run() and stopped via Stop().
// (2) Run goroutine started from Run() that accepts a client connection,
// reads, decodes and processes each request, issuing commands to the
// underlying debugger and sending back events and responses.
// TODO(polina): make it asynchronous (i.e. launch goroutine per request)
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
	// conn is the accepted client connection.
	conn net.Conn
50 51 52
	// stopChan is closed when the server is Stop()-ed. This can be used to signal
	// to goroutines run by the server that it's time to quit.
	stopChan chan struct{}
53 54 55 56 57 58
	// reader is used to read requests from the connection.
	reader *bufio.Reader
	// debugger is the underlying debugger service.
	debugger *debugger.Debugger
	// log is used for structured logging.
	log *logrus.Entry
59 60
	// binaryToRemove is the compiled binary to be removed on disconnect.
	binaryToRemove string
61
	// stackFrameHandles maps frames of each goroutine to unique ids across all goroutines.
62
	// Reset at every stop.
63
	stackFrameHandles *handlesMap
64
	// variableHandles maps compound variables to unique references within their stack frame.
65
	// Reset at every stop.
66
	// See also comment for convertVariable.
67
	variableHandles *variablesHandlesMap
68 69 70 71 72 73 74 75 76 77 78
	// args tracks special settings for handling debug session requests.
	args launchAttachArgs
}

// 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
79 80
	// showGlobalVariables indicates if global package variables should be loaded.
	showGlobalVariables bool
81 82 83 84
}

// defaultArgs borrows the defaults for the arguments from the original vscode-go adapter.
var defaultArgs = launchAttachArgs{
85 86 87
	stopOnEntry:         false,
	stackTraceDepth:     50,
	showGlobalVariables: false,
88 89 90
}

// NewServer creates a new DAP Server. It takes an opened Listener
91 92 93
// via config and assumes its ownership. config.disconnectChan has to be set;
// it will be closed by the server when the client disconnects or requests
// shutdown. Once disconnectChan is closed, Server.Stop() must be called.
94 95 96
func NewServer(config *service.Config) *Server {
	logger := logflags.DAPLogger()
	logflags.WriteDAPListeningMessage(config.Listener.Addr().String())
97
	logger.Debug("DAP server pid = ", os.Getpid())
98
	return &Server{
99 100 101 102 103
		config:            config,
		listener:          config.Listener,
		stopChan:          make(chan struct{}),
		log:               logger,
		stackFrameHandles: newHandlesMap(),
104
		variableHandles:   newVariablesHandlesMap(),
105
		args:              defaultArgs,
106 107 108
	}
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
// If user-specified options are provided via Launch/AttachRequest,
// we override the defaults for optional args.
func (s *Server) setLaunchAttachArgs(request dap.LaunchAttachRequest) {
	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
	}
}

126 127 128 129
// Stop stops the DAP debugger service, closes the listener and the client
// connection. It shuts down the underlying debugger and kills the target
// process if it was launched by it. This method mustn't be called more than
// once.
130 131
func (s *Server) Stop() {
	s.listener.Close()
132
	close(s.stopChan)
133 134 135 136 137 138 139 140
	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.
		s.conn.Close()
	}
	if s.debugger != nil {
141
		kill := s.config.Debugger.AttachPid == 0
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
		if err := s.debugger.Detach(kill); err != nil {
			s.log.Error(err)
		}
	}
}

// signalDisconnect closes config.DisconnectChan if not nil, which
// signals that the client disconnected or there was a client
// connection failure. Since the server currently services only one
// client, this can be used as a signal to the entire server via
// Stop(). The function safeguards agaist closing the channel more
// than once and can be called multiple times. It is not thread-safe
// and is currently only called from the run goroutine.
// TODO(polina): lock this when we add more goroutines that could call
// this when we support asynchronous request-response communication.
func (s *Server) signalDisconnect() {
158 159 160 161 162 163 164 165 166 167
	// 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()
	// -- run goroutine: calls signalDisconnect()
	// -- main goroutine: calls Stop()
	// -- main goroutine: Stop() closes client connection
	// -- run goroutine: serveDAPCodec() gets "closed network connection"
	// -- run goroutine: serveDAPCodec() returns
	// -- run goroutine: serveDAPCodec calls signalDisconnect()
168 169 170 171
	if s.config.DisconnectChan != nil {
		close(s.config.DisconnectChan)
		s.config.DisconnectChan = nil
	}
172 173 174
	if s.binaryToRemove != "" {
		gobuild.Remove(s.binaryToRemove)
	}
175 176 177 178 179 180 181 182 183 184 185 186 187
}

// 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() {
		conn, err := s.listener.Accept()
		if err != nil {
188 189 190 191 192
			select {
			case <-s.stopChan:
			default:
				s.log.Errorf("Error accepting client connection: %s\n", err)
			}
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
			s.signalDisconnect()
			return
		}
		s.conn = conn
		s.serveDAPCodec()
	}()
}

// serveDAPCodec reads and decodes requests from the client
// until it encounters an error or EOF, when it sends
// the disconnect signal and returns.
func (s *Server) serveDAPCodec() {
	defer s.signalDisconnect()
	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 {
217 218 219 220 221 222 223
			stopRequested := false
			select {
			case <-s.stopChan:
				stopRequested = true
			default:
			}
			if err != io.EOF && !stopRequested {
224 225 226 227 228 229 230 231 232
				s.log.Error("DAP error: ", err)
			}
			return
		}
		s.handleRequest(request)
	}
}

func (s *Server) handleRequest(request dap.Message) {
233 234 235 236 237 238 239 240
	defer func() {
		// In case a handler panics, we catch the panic and send an error response
		// back to the client.
		if ierr := recover(); ierr != nil {
			s.sendInternalErrorResponse(request.GetSeq(), fmt.Sprintf("%v", ierr))
		}
	}()

241 242 243 244 245
	jsonmsg, _ := json.Marshal(request)
	s.log.Debug("[<- from client]", string(jsonmsg))

	switch request := request.(type) {
	case *dap.InitializeRequest:
246
		// Required
247 248
		s.onInitializeRequest(request)
	case *dap.LaunchRequest:
249
		// Required
250 251
		s.onLaunchRequest(request)
	case *dap.AttachRequest:
252 253
		// Required
		s.onAttachRequest(request)
254
	case *dap.DisconnectRequest:
255
		// Required
256 257
		s.onDisconnectRequest(request)
	case *dap.TerminateRequest:
258 259 260
		// Optional (capability ‘supportsTerminateRequest‘)
		// TODO: implement this request in V1
		s.onTerminateRequest(request)
261
	case *dap.RestartRequest:
262 263 264
		// Optional (capability ‘supportsRestartRequest’)
		// TODO: implement this request in V1
		s.onRestartRequest(request)
265
	case *dap.SetBreakpointsRequest:
266
		// Required
267 268
		s.onSetBreakpointsRequest(request)
	case *dap.SetFunctionBreakpointsRequest:
269 270 271
		// Optional (capability ‘supportsFunctionBreakpoints’)
		// TODO: implement this request in V1
		s.onSetFunctionBreakpointsRequest(request)
272
	case *dap.SetExceptionBreakpointsRequest:
273
		// Optional (capability ‘exceptionBreakpointFilters’)
274 275
		s.onSetExceptionBreakpointsRequest(request)
	case *dap.ConfigurationDoneRequest:
276 277
		// Optional (capability ‘supportsConfigurationDoneRequest’)
		// Supported by vscode-go
278 279
		s.onConfigurationDoneRequest(request)
	case *dap.ContinueRequest:
280
		// Required
281 282
		s.onContinueRequest(request)
	case *dap.NextRequest:
283 284
		// Required
		s.onNextRequest(request)
285
	case *dap.StepInRequest:
286 287
		// Required
		s.onStepInRequest(request)
288
	case *dap.StepOutRequest:
289 290
		// Required
		s.onStepOutRequest(request)
291
	case *dap.StepBackRequest:
292 293 294
		// Optional (capability ‘supportsStepBack’)
		// TODO: implement this request in V1
		s.onStepBackRequest(request)
295
	case *dap.ReverseContinueRequest:
296 297 298
		// Optional (capability ‘supportsStepBack’)
		// TODO: implement this request in V1
		s.onReverseContinueRequest(request)
299
	case *dap.RestartFrameRequest:
300
		// Optional (capability ’supportsRestartFrame’)
301 302
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.GotoRequest:
303
		// Optional (capability ‘supportsGotoTargetsRequest’)
304 305
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.PauseRequest:
306 307 308
		// Required
		// TODO: implement this request in V0
		s.onPauseRequest(request)
309
	case *dap.StackTraceRequest:
310 311
		// Required
		s.onStackTraceRequest(request)
312
	case *dap.ScopesRequest:
313 314
		// Required
		s.onScopesRequest(request)
315
	case *dap.VariablesRequest:
316 317
		// Required
		s.onVariablesRequest(request)
318
	case *dap.SetVariableRequest:
319 320 321 322
		// Optional (capability ‘supportsSetVariable’)
		// Supported by vscode-go
		// TODO: implement this request in V0
		s.onSetVariableRequest(request)
323
	case *dap.SetExpressionRequest:
324 325 326
		// Optional (capability ‘supportsSetExpression’)
		// TODO: implement this request in V1
		s.onSetExpressionRequest(request)
327
	case *dap.SourceRequest:
328 329 330
		// Required
		// This does not make sense in the context of Go as
		// the source cannot be a string eval'ed at runtime.
331 332
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.ThreadsRequest:
333
		// Required
334
		s.onThreadsRequest(request)
335
	case *dap.TerminateThreadsRequest:
336
		// Optional (capability ‘supportsTerminateThreadsRequest’)
337 338
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.EvaluateRequest:
339
		// Required
340
		s.onEvaluateRequest(request)
341
	case *dap.StepInTargetsRequest:
342
		// Optional (capability ‘supportsStepInTargetsRequest’)
343 344
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.GotoTargetsRequest:
345
		// Optional (capability ‘supportsGotoTargetsRequest’)
346 347
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.CompletionsRequest:
348
		// Optional (capability ‘supportsCompletionsRequest’)
349 350
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.ExceptionInfoRequest:
351 352
		// Optional (capability ‘supportsExceptionInfoRequest’)
		// TODO: does this request make sense for delve?
353 354
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.LoadedSourcesRequest:
355 356 357
		// Optional (capability ‘supportsLoadedSourcesRequest’)
		// TODO: implement this request in V1
		s.onLoadedSourcesRequest(request)
358
	case *dap.DataBreakpointInfoRequest:
359
		// Optional (capability ‘supportsDataBreakpoints’)
360 361
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.SetDataBreakpointsRequest:
362
		// Optional (capability ‘supportsDataBreakpoints’)
363 364
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.ReadMemoryRequest:
365 366 367
		// Optional (capability ‘supportsReadMemoryRequest‘)
		// TODO: implement this request in V1
		s.onReadMemoryRequest(request)
368
	case *dap.DisassembleRequest:
369 370 371
		// Optional (capability ‘supportsDisassembleRequest’)
		// TODO: implement this request in V1
		s.onDisassembleRequest(request)
372
	case *dap.CancelRequest:
373 374 375
		// Optional (capability ‘supportsCancelRequest’)
		// TODO: does this request make sense for delve?
		s.onCancelRequest(request)
376
	case *dap.BreakpointLocationsRequest:
377 378 379 380 381
		// Optional (capability ‘supportsBreakpointLocationsRequest’)
		s.sendUnsupportedErrorResponse(request.Request)
	case *dap.ModulesRequest:
		// Optional (capability ‘supportsModulesRequest’)
		// TODO: does this request make sense for delve?
382 383 384 385
		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
386 387
		// to handle.
		s.sendInternalErrorResponse(request.GetSeq(), fmt.Sprintf("Unable to process %#v\n", request))
388 389 390 391 392 393 394 395 396 397 398 399 400
	}
}

func (s *Server) send(message dap.Message) {
	jsonmsg, _ := json.Marshal(message)
	s.log.Debug("[-> to client]", string(jsonmsg))
	dap.WriteProtocolMessage(s.conn, message)
}

func (s *Server) onInitializeRequest(request *dap.InitializeRequest) {
	// TODO(polina): Respond with an error if debug session is in progress?
	response := &dap.InitializeResponse{Response: *newResponse(request.Request)}
	response.Body.SupportsConfigurationDoneRequest = true
401
	response.Body.SupportsConditionalBreakpoints = true
402
	response.Body.SupportsDelayedStackTraceLoading = true
403
	response.Body.SupportTerminateDebuggee = true
404 405
	// TODO(polina): support this to match vscode-go functionality
	response.Body.SupportsSetVariable = false
406 407 408 409 410 411 412 413 414 415
	// TODO(polina): support these requests in addition to vscode-go feature parity
	response.Body.SupportsTerminateRequest = false
	response.Body.SupportsRestartRequest = false
	response.Body.SupportsFunctionBreakpoints = false
	response.Body.SupportsStepBack = false
	response.Body.SupportsSetExpression = false
	response.Body.SupportsLoadedSourcesRequest = false
	response.Body.SupportsReadMemoryRequest = false
	response.Body.SupportsDisassembleRequest = false
	response.Body.SupportsCancelRequest = false
416 417 418
	s.send(response)
}

419 420 421
// Output path for the compiled binary in debug or test modes.
const debugBinary string = "./__debug_bin"

422 423
func (s *Server) onLaunchRequest(request *dap.LaunchRequest) {
	// TODO(polina): Respond with an error if debug session is in progress?
424 425

	program, ok := request.Arguments["program"].(string)
426 427
	if !ok || program == "" {
		s.sendErrorResponse(request.Request,
428
			FailedToLaunch, "Failed to launch",
429 430 431 432 433 434 435 436
			"The program attribute is missing in debug configuration.")
		return
	}

	mode, ok := request.Arguments["mode"]
	if !ok || mode == "" {
		mode = "debug"
	}
437 438 439 440 441 442 443 444 445 446 447 448

	if mode == "debug" || mode == "test" {
		output, ok := request.Arguments["output"].(string)
		if !ok || output == "" {
			output = debugBinary
		}
		debugname, err := filepath.Abs(output)
		if err != nil {
			s.sendInternalErrorResponse(request.Seq, err.Error())
			return
		}

449 450 451 452 453 454
		buildFlags := ""
		buildFlagsArg, ok := request.Arguments["buildFlags"]
		if ok {
			buildFlags, ok = buildFlagsArg.(string)
			if !ok {
				s.sendErrorResponse(request.Request,
455
					FailedToLaunch, "Failed to launch",
456 457 458
					fmt.Sprintf("'buildFlags' attribute '%v' in debug configuration is not a string.", buildFlagsArg))
				return
			}
459 460 461 462 463 464 465 466 467 468
		}

		switch mode {
		case "debug":
			err = gobuild.GoBuild(debugname, []string{program}, buildFlags)
		case "test":
			err = gobuild.GoTestBuild(debugname, []string{program}, buildFlags)
		}
		if err != nil {
			s.sendErrorResponse(request.Request,
469
				FailedToLaunch, "Failed to launch",
470 471 472 473 474 475 476 477 478
				fmt.Sprintf("Build error: %s", err.Error()))
			return
		}
		program = debugname
		s.binaryToRemove = debugname
	}

	// TODO(polina): support "remote" mode
	if mode != "exec" && mode != "debug" && mode != "test" {
479
		s.sendErrorResponse(request.Request,
480
			FailedToLaunch, "Failed to launch",
481
			fmt.Sprintf("Unsupported 'mode' value %q in debug configuration.", mode))
482 483 484
		return
	}

485
	s.setLaunchAttachArgs(request)
486

487 488 489 490 491 492
	var targetArgs []string
	args, ok := request.Arguments["args"]
	if ok {
		argsParsed, ok := args.([]interface{})
		if !ok {
			s.sendErrorResponse(request.Request,
493
				FailedToLaunch, "Failed to launch",
494 495 496 497 498 499 500
				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,
501
					FailedToLaunch, "Failed to launch",
502 503 504 505 506 507 508 509
					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...)
510
	s.config.Debugger.WorkingDir = filepath.Dir(program)
511

512
	var err error
513
	if s.debugger, err = debugger.New(&s.config.Debugger, s.config.ProcessArgs); err != nil {
514
		s.sendErrorResponse(request.Request,
515
			FailedToLaunch, "Failed to launch", err.Error())
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
		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.LaunchResponse{Response: *newResponse(request.Request)})
}

// 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) {
	s.send(&dap.DisconnectResponse{Response: *newResponse(request.Request)})
	if s.debugger != nil {
		_, err := s.debugger.Command(&api.DebuggerCommand{Name: api.Halt})
		if err != nil {
			s.log.Error(err)
		}
536
		// We always kill launched programs
537
		kill := s.config.Debugger.AttachPid == 0
538 539 540 541 542 543
		// In case of attach, we leave the program
		// running but default, which can be
		// overridden by an explicit request to terminate.
		if request.Arguments.TerminateDebuggee {
			kill = true
		}
544 545 546 547 548 549 550 551 552 553
		err = s.debugger.Detach(kill)
		if err != nil {
			s.log.Error(err)
		}
	}
	// TODO(polina): make thread-safe when handlers become asynchronous.
	s.signalDisconnect()
}

func (s *Server) onSetBreakpointsRequest(request *dap.SetBreakpointsRequest) {
554 555
	// TODO(polina): handle this while running by halting first.

556
	if request.Arguments.Source.Path == "" {
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
		s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", "empty file path")
		return
	}

	// According to the spec we should "set multiple breakpoints for a single source
	// and clear all previous breakpoints in that source." The simplest way is
	// to clear all and then set all.
	//
	// TODO(polina): should we optimize this as follows?
	// See https://github.com/golang/vscode-go/issues/163 for details.
	// If a breakpoint:
	// -- exists and not in request => ClearBreakpoint
	// -- exists and in request => AmendBreakpoint
	// -- doesn't exist and in request => SetBreakpoint

	// Clear all existing breakpoints in the file.
	existing := s.debugger.Breakpoints()
	for _, bp := range existing {
		// Skip special breakpoints such as for panic.
		if bp.ID < 0 {
			continue
		}
		// Skip other source files.
		// TODO(polina): should this be normalized because of different OSes?
		if bp.File != request.Arguments.Source.Path {
			continue
		}
		_, err := s.debugger.ClearBreakpoint(bp)
		if err != nil {
			s.sendErrorResponse(request.Request, UnableToSetBreakpoints, "Unable to set or clear breakpoints", err.Error())
			return
		}
589
	}
590 591

	// Set all requested breakpoints.
592 593
	response := &dap.SetBreakpointsResponse{Response: *newResponse(request.Request)}
	response.Body.Breakpoints = make([]dap.Breakpoint, len(request.Arguments.Breakpoints))
594 595 596 597
	for i, want := range request.Arguments.Breakpoints {
		got, err := s.debugger.CreateBreakpoint(
			&api.Breakpoint{File: request.Arguments.Source.Path, Line: want.Line, Cond: want.Condition})
		response.Body.Breakpoints[i].Verified = (err == nil)
598
		if err != nil {
599 600 601
			response.Body.Breakpoints[i].Line = want.Line
			response.Body.Breakpoints[i].Message = err.Error()
		} else {
602
			response.Body.Breakpoints[i].Id = got.ID
603
			response.Body.Breakpoints[i].Line = got.Line
604
			response.Body.Breakpoints[i].Source = dap.Source{Name: request.Arguments.Source.Name, Path: request.Arguments.Source.Path}
605 606 607 608 609 610 611
		}
	}
	s.send(response)
}

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

func (s *Server) onConfigurationDoneRequest(request *dap.ConfigurationDoneRequest) {
617
	if s.args.stopOnEntry {
618 619
		e := &dap.StoppedEvent{
			Event: *newEvent("stopped"),
620
			Body:  dap.StoppedEventBody{Reason: "entry", ThreadId: 1, AllThreadsStopped: true},
621 622 623 624
		}
		s.send(e)
	}
	s.send(&dap.ConfigurationDoneResponse{Response: *newResponse(request.Request)})
625
	if !s.args.stopOnEntry {
626
		s.doCommand(api.Continue)
627 628 629 630
	}
}

func (s *Server) onContinueRequest(request *dap.ContinueRequest) {
631 632 633 634
	s.send(&dap.ContinueResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ContinueResponseBody{AllThreadsContinued: true}})
	s.doCommand(api.Continue)
635 636
}

637 638 639 640 641 642 643
func fnName(loc *proc.Location) string {
	if loc.Fn == nil {
		return "???"
	}
	return loc.Fn.Name
}

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
func (s *Server) onThreadsRequest(request *dap.ThreadsRequest) {
	if s.debugger == nil {
		s.sendErrorResponse(request.Request, UnableToDisplayThreads, "Unable to display threads", "debugger is nil")
		return
	}
	gs, _, err := s.debugger.Goroutines(0, 0)
	if err != nil {
		switch err.(type) {
		case *proc.ErrProcessExited:
			// 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 {
671 672 673 674 675 676 677 678
		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()

679
		for i, g := range gs {
680 681 682 683 684 685 686
			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())
687
			}
688 689 690 691 692
			// 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
693 694 695 696 697 698 699 700 701
		}
	}
	response := &dap.ThreadsResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ThreadsResponseBody{Threads: threads},
	}
	s.send(response)
}

702
// onAttachRequest handles 'attach' request.
703
// This is a mandatory request to support.
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
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)
		s.setLaunchAttachArgs(request)
		var err error
		if s.debugger, err = debugger.New(&s.config.Debugger, nil); err != nil {
			s.sendErrorResponse(request.Request,
				FailedToAttach, "Failed to attach", err.Error())
			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)})
737 738
}

739
// onNextRequest handles 'next' request.
740
// This is a mandatory request to support.
741
func (s *Server) onNextRequest(request *dap.NextRequest) {
742
	// This ignores threadId argument to match the original vscode-go implementation.
743 744 745
	// TODO(polina): use SwitchGoroutine to change the current goroutine.
	s.send(&dap.NextResponse{Response: *newResponse(request.Request)})
	s.doCommand(api.Next)
746 747
}

748
// onStepInRequest handles 'stepIn' request
749
// This is a mandatory request to support.
750
func (s *Server) onStepInRequest(request *dap.StepInRequest) {
751
	// This ignores threadId argument to match the original vscode-go implementation.
752 753 754
	// TODO(polina): use SwitchGoroutine to change the current goroutine.
	s.send(&dap.StepInResponse{Response: *newResponse(request.Request)})
	s.doCommand(api.Step)
755 756
}

757
// onStepOutRequest handles 'stepOut' request
758
// This is a mandatory request to support.
759
func (s *Server) onStepOutRequest(request *dap.StepOutRequest) {
760
	// This ignores threadId argument to match the original vscode-go implementation.
761 762 763
	// TODO(polina): use SwitchGoroutine to change the current goroutine.
	s.send(&dap.StepOutResponse{Response: *newResponse(request.Request)})
	s.doCommand(api.StepOut)
764 765 766 767 768 769 770 771
}

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

772 773 774 775 776 777 778 779
// 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.
780
// This is a mandatory request to support.
781 782
func (s *Server) onStackTraceRequest(request *dap.StackTraceRequest) {
	goroutineID := request.Arguments.ThreadId
783
	frames, err := s.debugger.Stacktrace(goroutineID, s.args.stackTraceDepth, 0)
784 785 786 787 788
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToProduceStackTrace, "Unable to produce stack trace", err.Error())
		return
	}

789 790 791
	stackFrames := make([]dap.StackFrame, len(frames))
	for i, frame := range frames {
		loc := &frame.Call
792
		uniqueStackFrameID := s.stackFrameHandles.create(stackFrame{goroutineID, i})
793
		stackFrames[i] = dap.StackFrame{Id: uniqueStackFrameID, Line: loc.Line, Name: fnName(loc)}
794 795 796 797 798
		if loc.File != "<autogenerated>" {
			stackFrames[i].Source = dap.Source{Name: filepath.Base(loc.File), Path: loc.File}
		}
		stackFrames[i].Column = 0
	}
799 800 801 802 803
	// 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.
804 805 806 807 808 809 810 811
	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),
812
		Body:     dap.StackTraceResponseBody{StackFrames: stackFrames, TotalFrames: len(frames)},
813 814
	}
	s.send(response)
815 816
}

817
// onScopesRequest handles 'scopes' requests.
818
// This is a mandatory request to support.
819 820 821 822 823 824 825
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
	}

826 827
	goid := sf.(stackFrame).goroutineID
	frame := sf.(stackFrame).frameIndex
828 829 830 831
	// TODO(polina): Support setting config via launch/attach args
	cfg := proc.LoadConfig{FollowPointers: true, MaxVariableRecurse: 1, MaxStringLen: 64, MaxArrayValues: 64, MaxStructFields: -1}

	// Retrieve arguments
832
	args, err := s.debugger.FunctionArguments(goid, frame, 0, cfg)
833 834 835 836
	if err != nil {
		s.sendErrorResponse(request.Request, UnableToListArgs, "Unable to list args", err.Error())
		return
	}
837
	argScope := &fullyQualifiedVariable{&proc.Variable{Name: "Arguments", Children: slicePtrVarToSliceVar(args)}, "", true}
838 839

	// Retrieve local variables
840
	locals, err := s.debugger.LocalVariables(goid, frame, 0, cfg)
841
	if err != nil {
842
		s.sendErrorResponse(request.Request, UnableToListLocals, "Unable to list locals", err.Error())
843 844
		return
	}
845
	locScope := &fullyQualifiedVariable{&proc.Variable{Name: "Locals", Children: slicePtrVarToSliceVar(locals)}, "", true}
846 847 848 849 850 851 852

	// TODO(polina): Annotate shadowed variables

	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}

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
	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)
869
		globals, err := s.debugger.PackageVariables(currPkgFilter, cfg)
870 871 872 873 874 875 876 877 878 879
		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+".")
		}

880
		globScope := &fullyQualifiedVariable{&proc.Variable{
881 882
			Name:     fmt.Sprintf("Globals (package %s)", currPkg),
			Children: slicePtrVarToSliceVar(globals),
883
		}, currPkg, true}
884 885 886
		scopeGlobals := dap.Scope{Name: globScope.Name, VariablesReference: s.variableHandles.create(globScope)}
		scopes = append(scopes, scopeGlobals)
	}
887 888 889 890 891
	response := &dap.ScopesResponse{
		Response: *newResponse(request.Request),
		Body:     dap.ScopesResponseBody{Scopes: scopes},
	}
	s.send(response)
892 893
}

894 895 896 897 898 899 900 901
func slicePtrVarToSliceVar(vars []*proc.Variable) []proc.Variable {
	r := make([]proc.Variable, len(vars))
	for i := range vars {
		r[i] = *vars[i]
	}
	return r
}

902
// onVariablesRequest handles 'variables' requests.
903
// This is a mandatory request to support.
904
func (s *Server) onVariablesRequest(request *dap.VariablesRequest) {
905
	v, ok := s.variableHandles.get(request.Arguments.VariablesReference)
906 907 908 909 910 911 912 913 914 915 916 917 918 919
	if !ok {
		s.sendErrorResponse(request.Request, UnableToLookupVariable, "Unable to lookup variable", fmt.Sprintf("unknown reference %d", request.Arguments.VariablesReference))
		return
	}
	children := make([]dap.Variable, 0)
	// TODO(polina): check and handle if variable loaded incompletely
	// https://github.com/go-delve/delve/blob/master/Documentation/api/ClientHowto.md#looking-into-variables

	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.
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
			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)
				}
				// TODO(polina): use nil for nil keys of different types
			}
			key, keyref := s.convertVariable(keyv, keyexpr)
			val, valref := s.convertVariable(valv, valexpr)
937 938 939 940 941 942
			// 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),
943
					EvaluateName:       keyexpr,
944 945 946 947 948
					Value:              key,
					VariablesReference: keyref,
				}
				valvar := dap.Variable{
					Name:               fmt.Sprintf("[val %d]", kvIndex),
949
					EvaluateName:       valexpr,
950 951 952 953 954 955
					Value:              val,
					VariablesReference: valref,
				}
				children = append(children, keyvar, valvar)
			} else { // At least one is a scalar
				kvvar := dap.Variable{
956 957 958
					Name:         key,
					EvaluateName: valexpr,
					Value:        val,
959 960
				}
				if keyref != 0 { // key is a type to be expanded
961
					kvvar.Name = fmt.Sprintf("%s(%#x)", kvvar.Name, keyv.Addr) // Make the name unique
962 963 964 965 966 967 968 969 970
					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))
971
		for i := range v.Children {
972 973
			cfqname := fmt.Sprintf("%s[%d]", v.fullyQualifiedNameOrExpr, i)
			cvalue, cvarref := s.convertVariable(&v.Children[i], cfqname)
974 975
			children[i] = dap.Variable{
				Name:               fmt.Sprintf("[%d]", i),
976 977 978
				EvaluateName:       cfqname,
				Value:              cvalue,
				VariablesReference: cvarref,
979 980 981 982
			}
		}
	default:
		children = make([]dap.Variable, len(v.Children))
983 984
		for i := range v.Children {
			c := &v.Children[i]
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
			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)
1001 1002
			children[i] = dap.Variable{
				Name:               c.Name,
1003 1004 1005
				EvaluateName:       cfqname,
				Value:              cvalue,
				VariablesReference: cvarref,
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
			}
		}
	}
	response := &dap.VariablesResponse{
		Response: *newResponse(request.Request),
		Body:     dap.VariablesResponseBody{Variables: children},
	}
	s.send(response)
}

1016 1017
// convertVariable converts proc.Variable to dap.Variable value and reference
// while keeping track of the full qualified name or load expression.
1018
// Variable reference is used to keep track of the children associated with each
1019 1020 1021 1022 1023 1024
// 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).
1025 1026
func (s *Server) convertVariable(v *proc.Variable, qualifiedNameOrExpr string) (value string, variablesReference int) {
	return s.convertVariableWithOpts(v, qualifiedNameOrExpr, false)
1027 1028 1029
}

func (s *Server) convertVariableToString(v *proc.Variable) string {
1030
	val, _ := s.convertVariableWithOpts(v, "", true)
1031 1032 1033
	return val
}

1034
// convertVariableWithOpts allows to skip reference generation in case all we need is
1035
// a string representation of the variable.
1036
func (s *Server) convertVariableWithOpts(v *proc.Variable, qualifiedNameOrExpr string, skipRef bool) (value string, variablesReference int) {
1037 1038 1039 1040
	maybeCreateVariableHandle := func(v *proc.Variable) int {
		if skipRef {
			return 0
		}
1041
		return s.variableHandles.create(&fullyQualifiedVariable{v, qualifiedNameOrExpr, false /*not a scope*/})
1042
	}
1043 1044
	if v.Unreadable != nil {
		value = fmt.Sprintf("unreadable <%v>", v.Unreadable)
1045 1046
		return
	}
1047
	typeName := api.PrettyTypeName(v.DwarfType)
1048 1049 1050 1051 1052 1053 1054 1055
	switch v.Kind {
	case reflect.UnsafePointer:
		if len(v.Children) == 0 {
			value = "unsafe.Pointer(nil)"
		} else {
			value = fmt.Sprintf("unsafe.Pointer(%#x)", v.Children[0].Addr)
		}
	case reflect.Ptr:
1056
		if v.DwarfType == nil || len(v.Children) == 0 {
1057 1058
			value = "nil"
		} else if v.Children[0].Addr == 0 {
1059 1060
			value = "nil <" + typeName + ">"
		} else if v.Children[0].Kind == reflect.Invalid {
1061 1062
			value = "void"
		} else {
1063
			value = fmt.Sprintf("<%s>(%#x)", typeName, v.Children[0].Addr)
1064
			variablesReference = maybeCreateVariableHandle(v)
1065 1066
		}
	case reflect.Array:
1067
		value = "<" + typeName + ">"
1068
		if len(v.Children) > 0 {
1069
			variablesReference = maybeCreateVariableHandle(v)
1070 1071 1072
		}
	case reflect.Slice:
		if v.Base == 0 {
1073
			value = "nil <" + typeName + ">"
1074
		} else {
1075
			value = fmt.Sprintf("<%s> (length: %d, cap: %d)", typeName, v.Len, v.Cap)
1076
			if len(v.Children) > 0 {
1077
				variablesReference = maybeCreateVariableHandle(v)
1078 1079 1080 1081
			}
		}
	case reflect.Map:
		if v.Base == 0 {
1082
			value = "nil <" + typeName + ">"
1083
		} else {
1084
			value = fmt.Sprintf("<%s> (length: %d)", typeName, v.Len)
1085
			if len(v.Children) > 0 {
1086
				variablesReference = maybeCreateVariableHandle(v)
1087 1088 1089
			}
		}
	case reflect.String:
1090 1091
		vvalue := constant.StringVal(v.Value)
		lenNotLoaded := v.Len - int64(len(vvalue))
1092 1093 1094 1095 1096 1097
		if lenNotLoaded > 0 {
			vvalue += fmt.Sprintf("...+%d more", lenNotLoaded)
		}
		value = fmt.Sprintf("%q", vvalue)
	case reflect.Chan:
		if len(v.Children) == 0 {
1098
			value = "nil <" + typeName + ">"
1099
		} else {
1100
			value = "<" + typeName + ">"
1101
			variablesReference = maybeCreateVariableHandle(v)
1102 1103
		}
	case reflect.Interface:
1104
		if v.Addr == 0 {
1105
			// An escaped interface variable that points to nil: this shouldn't
1106 1107 1108 1109 1110 1111
			// happen in normal code but can happen if the variable is out of scope,
			// such as if an interface variable has been captured by a
			// closure and replaced by a pointer to interface, and the pointer
			// happens to contain 0.
			value = "nil"
		} else if len(v.Children) == 0 || v.Children[0].Kind == reflect.Invalid && v.Children[0].Addr == 0 {
1112
			value = "nil <" + typeName + ">"
1113
		} else {
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
			value = "<" + typeName + "(" + v.Children[0].TypeString() + ")" + ">"
			// TODO(polina): should we remove one level of indirection and skip "data"?
			// Then we will have:
			// Before:
			//   i: <interface{}(int)>
			//      data: 123
			// After:
			//   i: <interface{}(int)> 123
			// Before:
			//   i: <interface{}(main.MyStruct)>
			//      data: <main.MyStruct>
			//         field1: ...
			// After:
			//   i: <interface{}(main.MyStruct)>
			//      field1: ...
1129
			variablesReference = maybeCreateVariableHandle(v)
1130
		}
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
	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
1145
	default: // Struct, complex, scalar
1146 1147 1148
		vvalue := api.VariableValueAsString(v)
		if vvalue != "" {
			value = vvalue
1149
		} else {
1150
			value = "<" + typeName + ">"
1151 1152
		}
		if len(v.Children) > 0 {
1153
			variablesReference = maybeCreateVariableHandle(v)
1154 1155 1156
		}
	}
	return
1157 1158
}

1159
// onEvaluateRequest handles 'evalute' requests.
1160
// This is a mandatory request to support.
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
// 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) {
	showErrorToUser := request.Arguments.Context != "watch"
	if s.debugger == nil {
		s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", "debugger is nil", showErrorToUser)
		return
	}
	// 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
	}
	// TODO(polina): Support config settings via launch/attach args vs auto-loading?
	apiCfg := &api.LoadConfig{FollowPointers: true, MaxVariableRecurse: 1, MaxStringLen: 64, MaxArrayValues: 64, MaxStructFields: -1}
	prcCfg := proc.LoadConfig{FollowPointers: true, MaxVariableRecurse: 1, MaxStringLen: 64, MaxArrayValues: 64, MaxStructFields: -1}

	response := &dap.EvaluateResponse{Response: *newResponse(request.Request)}
	isCall, err := regexp.MatchString(`^\s*call\s+\S+`, request.Arguments.Expression)
	if err == nil && isCall { // call {expression}
		// This call might be evaluated in the context of the frame that is not topmost
		// if the editor is set to view the variables for one of the parent frames.
		// If the call expression refers to any of these variables, unlike regular
		// expressions, it will evaluate them in the context of the topmost frame,
		// and the user will get an unexpected result or an unexpected symbol error.
		// We prevent this but disallowing any frames other than topmost.
		if frame > 0 {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", "call is only supported with topmost stack frame", showErrorToUser)
			return
		}
		stateBeforeCall, err := s.debugger.State( /*nowait*/ true)
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
			return
		}
		state, err := s.debugger.Command(&api.DebuggerCommand{
			Name:                 api.Call,
			ReturnInfoLoadConfig: apiCfg,
			Expr:                 strings.Replace(request.Arguments.Expression, "call ", "", 1),
			UnsafeCall:           false,
			GoroutineID:          goid,
		})
		if _, isexited := err.(proc.ErrProcessExited); isexited || err == nil && state.Exited {
			e := &dap.TerminatedEvent{Event: *newEvent("terminated")}
			s.send(e)
			return
		}
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
			return
		}
		// After the call is done, the goroutine where we injected the call should
		// return to the original stopped line with return values. However,
		// it is not guaranteed to be selected due to the possibility of the
		// of simultaenous breakpoints. Therefore, we check all threads.
		var retVars []*proc.Variable
		for _, t := range state.Threads {
			if t.GoroutineID == stateBeforeCall.SelectedGoroutine.ID &&
1225
				t.Line == stateBeforeCall.SelectedGoroutine.CurrentLoc.Line && t.CallReturn {
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
				// The call completed. Get the return values.
				retVars, err = s.debugger.FindThreadReturnValues(t.ID, prcCfg)
				if err != nil {
					s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
					return
				}
				break
			}
		}
		if retVars == nil {
			// The call got interrupted by a stop (e.g. breakpoint in injected
			// function call or in another goroutine)
			s.resetHandlesForStop()
			stopped := &dap.StoppedEvent{Event: *newEvent("stopped")}
			stopped.Body.AllThreadsStopped = true
			if state.SelectedGoroutine != nil {
				stopped.Body.ThreadId = state.SelectedGoroutine.ID
			}
			stopped.Body.Reason = s.debugger.StopReason().String()
			s.send(stopped)
			// TODO(polina): once this is asynchronous, we could wait to reply until the user
			// continues, call ends, original stop point is hit and return values are available.
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", "call stopped", showErrorToUser)
			return
		}
		// The call completed and we can reply with its return values (if any)
		if len(retVars) > 0 {
			// Package one or more return values in a single scope-like nameless variable
			// that preserves their names.
			retVarsAsVar := &proc.Variable{Children: slicePtrVarToSliceVar(retVars)}
			// As a shortcut also express the return values as a single string.
			retVarsAsStr := ""
			for _, v := range retVars {
				retVarsAsStr += s.convertVariableToString(v) + ", "
			}
			response.Body = dap.EvaluateResponseBody{
				Result:             strings.TrimRight(retVarsAsStr, ", "),
1263
				VariablesReference: s.variableHandles.create(&fullyQualifiedVariable{retVarsAsVar, "", false /*not a scope*/}),
1264 1265 1266 1267 1268 1269 1270 1271
			}
		}
	} else { // {expression}
		exprVar, err := s.debugger.EvalVariableInScope(goid, frame, 0, request.Arguments.Expression, prcCfg)
		if err != nil {
			s.sendErrorResponseWithOpts(request.Request, UnableToEvaluateExpression, "Unable to evaluate expression", err.Error(), showErrorToUser)
			return
		}
1272 1273 1274
		// 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))
1275 1276 1277
		response.Body = dap.EvaluateResponseBody{Result: exprVal, VariablesReference: exprRef}
	}
	s.send(response)
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
}

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

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

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

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

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

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

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

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

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

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

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

1346 1347 1348
// sendERrorResponseWithOpts offers configuration options.
//   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) {
1349 1350 1351 1352 1353 1354 1355 1356
	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)
1357
	er.Body.Error.ShowUser = showUser
1358 1359 1360 1361
	s.log.Error(er.Body.Error.Format)
	s.send(er)
}

1362 1363 1364 1365 1366
// 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*/)
}

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
// 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)
	s.log.Error(er.Body.Error.Format)
	s.send(er)
}

1382 1383 1384 1385 1386
func (s *Server) sendUnsupportedErrorResponse(request dap.Request) {
	s.sendErrorResponse(request, UnsupportedCommand, "Unsupported command",
		fmt.Sprintf("cannot process '%s' request", request.Command))
}

1387 1388 1389 1390 1391
func (s *Server) sendNotYetImplementedErrorResponse(request dap.Request) {
	s.sendErrorResponse(request, NotYetImplemented, "Not yet implemented",
		fmt.Sprintf("cannot process '%s' request", request.Command))
}

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
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,
	}
}

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

1417 1418 1419 1420 1421
func (s *Server) resetHandlesForStop() {
	s.stackFrameHandles.reset()
	s.variableHandles.reset()
}

1422 1423 1424 1425
// doCommand runs a debugger command until it stops on
// termination, error, breakpoint, etc, when an appropriate
// event needs to be sent to the client.
func (s *Server) doCommand(command string) {
1426 1427 1428
	if s.debugger == nil {
		return
	}
1429 1430 1431 1432 1433

	state, err := s.debugger.Command(&api.DebuggerCommand{Name: command})
	if _, isexited := err.(proc.ErrProcessExited); isexited || err == nil && state.Exited {
		e := &dap.TerminatedEvent{Event: *newEvent("terminated")}
		s.send(e)
1434 1435
		return
	}
1436

1437
	s.resetHandlesForStop()
1438 1439 1440 1441
	stopped := &dap.StoppedEvent{Event: *newEvent("stopped")}
	stopped.Body.AllThreadsStopped = true

	if err == nil {
1442 1443 1444 1445 1446 1447
		if state.SelectedGoroutine != nil {
			stopped.Body.ThreadId = state.SelectedGoroutine.ID
		}

		switch s.debugger.StopReason() {
		case proc.StopNextFinished:
1448 1449 1450 1451
			stopped.Body.Reason = "step"
		default:
			stopped.Body.Reason = "breakpoint"
		}
1452 1453 1454 1455 1456 1457 1458 1459
		if state.CurrentThread.Breakpoint != nil {
			switch state.CurrentThread.Breakpoint.Name {
			case proc.FatalThrow:
				stopped.Body.Reason = "fatal error"
			case proc.UnrecoveredPanic:
				stopped.Body.Reason = "panic"
			}
		}
1460
		s.send(stopped)
1461
	} else {
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
		s.log.Error("runtime error: ", err)
		stopped.Body.Reason = "runtime error"
		stopped.Body.Text = err.Error()
		// Special case in the spirit of https://github.com/microsoft/vscode-go/issues/1903
		if stopped.Body.Text == "bad access" {
			stopped.Body.Text = BetterBadAccessError
		}
		state, err := s.debugger.State( /*nowait*/ true)
		if err == nil {
			stopped.Body.ThreadId = state.CurrentThread.GoroutineID
		}
		s.send(stopped)

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