commands.go 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package cmds

import (
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"runtime"
	"strconv"
	"syscall"

D
Derek Parker 已提交
15
	"github.com/derekparker/delve/pkg/config"
16
	"github.com/derekparker/delve/pkg/goversion"
D
Derek Parker 已提交
17 18
	"github.com/derekparker/delve/pkg/terminal"
	"github.com/derekparker/delve/pkg/version"
19 20
	"github.com/derekparker/delve/service"
	"github.com/derekparker/delve/service/api"
21
	"github.com/derekparker/delve/service/rpc2"
A
aarzilli 已提交
22
	"github.com/derekparker/delve/service/rpccommon"
23 24 25 26 27 28 29 30
	"github.com/spf13/cobra"
)

var (
	// Log is whether to log debug statements.
	Log bool
	// Headless is whether to run without terminal.
	Headless bool
A
aarzilli 已提交
31 32
	// APIVersion is the requested API version while running headless
	APIVersion int
33 34 35 36 37 38 39 40
	// AcceptMulti allows multiple clients to connect to the same server
	AcceptMulti bool
	// Addr is the debugging server listen address.
	Addr string
	// InitFile is the path to initialization file.
	InitFile string
	// BuildFlags is the flags passed during compiler invocation.
	BuildFlags string
E
Evgeny L 已提交
41 42
	// WorkingDir is the working directory for running the program.
	WorkingDir string
43

44 45 46
	// Backend selection
	Backend string

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	// RootCommand is the root of the command tree.
	RootCommand *cobra.Command

	traceAttachPid  int
	traceStackDepth int

	conf *config.Config
)

const (
	debugname     = "debug"
	testdebugname = "debug.test"
)

const dlvCommandLongDesc = `Delve is a source level debugger for Go programs.

Delve enables you to interact with your program by controlling the execution of the process,
evaluating variables, and providing information of thread / goroutine state, CPU register state and more.

The goal of this tool is to provide a simple yet powerful interface for debugging Go programs.
67 68 69 70

Pass flags to the program you are debugging using ` + "`--`" + `, for example:

` + "`dlv exec ./hello -- server --config conf/config.toml`"
71 72

// New returns an initialized command tree.
73
func New(docCall bool) *cobra.Command {
74 75 76 77
	// Config setup and load.
	conf = config.LoadConfig()
	buildFlagsDefault := ""
	if runtime.GOOS == "windows" {
78 79 80 81 82
		ver, _ := goversion.Installed()
		if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
			// Work-around for https://github.com/golang/go/issues/13154
			buildFlagsDefault = "-ldflags='-linkmode internal'"
		}
83 84 85 86 87 88 89 90 91 92 93 94
	}

	// Main dlv root command.
	RootCommand = &cobra.Command{
		Use:   "dlv",
		Short: "Delve is a debugger for the Go programming language.",
		Long:  dlvCommandLongDesc,
	}

	RootCommand.PersistentFlags().StringVarP(&Addr, "listen", "l", "localhost:0", "Debugging server listen address.")
	RootCommand.PersistentFlags().BoolVarP(&Log, "log", "", false, "Enable debugging server logging.")
	RootCommand.PersistentFlags().BoolVarP(&Headless, "headless", "", false, "Run debug server only, in headless mode.")
95
	RootCommand.PersistentFlags().BoolVarP(&AcceptMulti, "accept-multiclient", "", false, "Allows a headless server to accept multiple client connections. Note that the server API is not reentrant and clients will have to coordinate.")
A
aarzilli 已提交
96
	RootCommand.PersistentFlags().IntVar(&APIVersion, "api-version", 1, "Selects API version when headless.")
97 98
	RootCommand.PersistentFlags().StringVar(&InitFile, "init", "", "Init file, executed by the terminal client.")
	RootCommand.PersistentFlags().StringVar(&BuildFlags, "build-flags", buildFlagsDefault, "Build flags, to be passed to the compiler.")
E
Evgeny L 已提交
99
	RootCommand.PersistentFlags().StringVar(&WorkingDir, "wd", ".", "Working directory for running the program.")
100 101 102
	RootCommand.PersistentFlags().StringVar(&Backend, "backend", "default", `Backend selection:
	default		Uses lldb on macOS, native everywhere else.
	native		Native backend.
103 104 105
	lldb		Uses lldb-server or debugserver.
	rr		Uses mozilla rr (https://github.com/mozilla/rr).
`)
106

107 108
	// 'attach' subcommand.
	attachCommand := &cobra.Command{
109
		Use:   "attach pid [executable]",
110
		Short: "Attach to running process and begin debugging.",
111 112 113 114 115 116
		Long: `Attach to an already running process and begin debugging it.

This command will cause Delve to take control of an already running process, and
begin a new debug session.  When exiting the debug session you will have the
option to let the process continue or kill it.
`,
117 118 119 120 121
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New("you must provide a PID")
			}
			return nil
122
		},
123
		Run: attachCmd,
124
	}
125
	RootCommand.AddCommand(attachCommand)
126

127 128 129 130
	// 'connect' subcommand.
	connectCommand := &cobra.Command{
		Use:   "connect addr",
		Short: "Connect to a headless debug server.",
131
		Long:  "Connect to a running headless debug server.",
132 133 134 135 136
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New("you must provide an address as the first argument")
			}
			return nil
137
		},
138
		Run: connectCmd,
139
	}
140
	RootCommand.AddCommand(connectCommand)
141 142 143 144

	// 'debug' subcommand.
	debugCommand := &cobra.Command{
		Use:   "debug [package]",
145
		Short: "Compile and begin debugging main package in current directory, or the package specified.",
146 147 148 149 150 151
		Long: `Compiles your program with optimizations disabled, starts and attaches to it.

By default, with no arguments, Delve will compile the 'main' package in the
current directory, and begin to debug it. Alternatively you can specify a
package name and Delve will compile that package instead, and begin a new debug
session.`,
152 153 154 155 156 157
		Run: debugCmd,
	}
	RootCommand.AddCommand(debugCommand)

	// 'exec' subcommand.
	execCommand := &cobra.Command{
158
		Use:   "exec <path/to/binary>",
159 160 161 162 163 164 165
		Short: "Execute a precompiled binary, and begin a debug session.",
		Long: `Execute a precompiled binary and begin a debug session.

This command will cause Delve to exec the binary and immediately attach to it to
begin a new debug session. Please note that if the binary was not compiled with
optimizations disabled, it may be difficult to properly debug it. Please
consider compiling debugging binaries with -gcflags="-N -l".`,
166 167 168 169 170 171 172
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New("you must provide a path to a binary")
			}
			return nil
		},
		Run: func(cmd *cobra.Command, args []string) {
173
			os.Exit(execute(0, args, conf, "", executingExistingFile))
174 175 176 177
		},
	}
	RootCommand.AddCommand(execCommand)

178 179 180 181 182 183 184 185
	// Deprecated 'run' subcommand.
	runCommand := &cobra.Command{
		Use:   "run",
		Short: "Deprecated command. Use 'debug' instead.",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("This command is deprecated, please use 'debug' instead.")
			os.Exit(0)
		},
186
	}
187
	RootCommand.AddCommand(runCommand)
188 189 190 191 192

	// 'test' subcommand.
	testCommand := &cobra.Command{
		Use:   "test [package]",
		Short: "Compile test binary and begin debugging program.",
193 194 195 196 197 198 199
		Long: `Compiles a test binary with optimizations disabled and begins a new debug session.

The test command allows you to begin a new debug session in the context of your
unit tests. By default Delve will debug the tests in the current directory.
Alternatively you can specify a package name, and Delve will debug the tests in
that package instead.`,
		Run: testCmd,
200 201 202
	}
	RootCommand.AddCommand(testCommand)

203 204 205 206
	// 'trace' subcommand.
	traceCommand := &cobra.Command{
		Use:   "trace [package] regexp",
		Short: "Compile and begin tracing program.",
207 208 209 210 211 212 213
		Long: `Trace program execution.

The trace sub command will set a tracepoint on every function matching the
provided regular expression and output information when tracepoint is hit.  This
is useful if you do not want to begin an entire debug session, but merely want
to know what functions your process is executing.`,
		Run: traceCmd,
214
	}
215 216 217
	traceCommand.Flags().IntVarP(&traceAttachPid, "pid", "p", 0, "Pid to attach to.")
	traceCommand.Flags().IntVarP(&traceStackDepth, "stack", "s", 0, "Show stack trace with given depth.")
	RootCommand.AddCommand(traceCommand)
218

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	coreCommand := &cobra.Command{
		Use:   "core <executable> <core>",
		Short: "Examine a core dump.",
		Long: `Examine a core dump.
		
The core command will open the specified core file and the associated
executable and let you examine the state of the process when the
core dump was taken.`,
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			if len(args) != 2 {
				return errors.New("you must provide a core file and an executable")
			}
			return nil
		},
		Run: coreCmd,
	}
	RootCommand.AddCommand(coreCommand)

237 238 239 240 241 242
	// 'version' subcommand.
	versionCommand := &cobra.Command{
		Use:   "version",
		Short: "Prints version.",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Printf("Delve Debugger\n%s\n", version.DelveVersion)
243 244
		},
	}
245
	RootCommand.AddCommand(versionCommand)
246

247
	if path, _ := exec.LookPath("rr"); path != "" || docCall {
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
		replayCommand := &cobra.Command{
			Use:   "replay [trace directory]",
			Short: "Replays a rr trace.",
			Long: `Replays a rr trace.
			
The replay command will open a trace generated by mozilla rr. Mozilla rr must be installed:
https://github.com/mozilla/rr
			`,
			PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
				if len(args) == 0 {
					return errors.New("you must provide a path to a binary")
				}
				return nil
			},
			Run: func(cmd *cobra.Command, args []string) {
				Backend = "rr"
				os.Exit(execute(0, []string{}, conf, args[0], executingOther))
			},
		}
		RootCommand.AddCommand(replayCommand)
	}

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
	return RootCommand
}

func debugCmd(cmd *cobra.Command, args []string) {
	status := func() int {
		var pkg string
		dlvArgs, targetArgs := splitArgs(cmd, args)

		if len(dlvArgs) > 0 {
			pkg = args[0]
		}
		err := gobuild(debugname, pkg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			return 1
		}
		fp, err := filepath.Abs("./" + debugname)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			return 1
		}
		defer os.Remove(fp)
E
Evgeny L 已提交
292 293 294 295 296 297
		abs, err := filepath.Abs(debugname)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			return 1
		}
		processArgs := append([]string{abs}, targetArgs...)
298
		return execute(0, processArgs, conf, "", executingGeneratedFile)
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
	}()
	os.Exit(status)
}

func traceCmd(cmd *cobra.Command, args []string) {
	status := func() int {
		var regexp string
		var processArgs []string

		dlvArgs, targetArgs := splitArgs(cmd, args)

		if traceAttachPid == 0 {
			var pkg string
			switch len(dlvArgs) {
			case 1:
				regexp = args[0]
			case 2:
				pkg = args[0]
				regexp = args[1]
			}
			if err := gobuild(debugname, pkg); err != nil {
				return 1
			}
			defer os.Remove("./" + debugname)

			processArgs = append([]string{"./" + debugname}, targetArgs...)
		}
		// Make a TCP listener
		listener, err := net.Listen("tcp", Addr)
		if err != nil {
			fmt.Printf("couldn't start listener: %s\n", err)
			return 1
		}
		defer listener.Close()

		// Create and start a debug server
A
aarzilli 已提交
335
		server := rpccommon.NewServer(&service.Config{
336 337 338
			Listener:    listener,
			ProcessArgs: processArgs,
			AttachPid:   traceAttachPid,
A
aarzilli 已提交
339
			APIVersion:  2,
E
Evgeny L 已提交
340
			WorkingDir:  WorkingDir,
341
			Backend:     Backend,
342 343 344 345 346
		}, Log)
		if err := server.Run(); err != nil {
			fmt.Fprintln(os.Stderr, err)
			return 1
		}
347
		client := rpc2.NewClient(listener.Addr().String())
348 349 350 351 352 353
		funcs, err := client.ListFunctions(regexp)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return 1
		}
		for i := range funcs {
354
			_, err = client.CreateBreakpoint(&api.Breakpoint{FunctionName: funcs[i], Tracepoint: true, Line: -1, Stacktrace: traceStackDepth, LoadArgs: &terminal.ShortLoadConfig})
355 356 357 358 359 360 361 362
			if err != nil {
				fmt.Fprintln(os.Stderr, err)
				return 1
			}
		}
		cmds := terminal.DebugCommands(client)
		t := terminal.New(client, nil)
		defer t.Close()
363
		err = cmds.Call("continue", t)
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return 1
		}
		return 0
	}()
	os.Exit(status)
}

func testCmd(cmd *cobra.Command, args []string) {
	status := func() int {
		var pkg string
		dlvArgs, targetArgs := splitArgs(cmd, args)

		if len(dlvArgs) > 0 {
			pkg = args[0]
		}
		err := gotestbuild(pkg)
		if err != nil {
			return 1
		}
		defer os.Remove("./" + testdebugname)
		processArgs := append([]string{"./" + testdebugname}, targetArgs...)

388
		return execute(0, processArgs, conf, "", executingGeneratedTest)
389 390 391 392 393 394 395 396 397 398
	}()
	os.Exit(status)
}

func attachCmd(cmd *cobra.Command, args []string) {
	pid, err := strconv.Atoi(args[0])
	if err != nil {
		fmt.Fprintf(os.Stderr, "Invalid pid: %s\n", args[0])
		os.Exit(1)
	}
399
	os.Exit(execute(pid, args[1:], conf, "", executingOther))
400 401 402 403
}

func coreCmd(cmd *cobra.Command, args []string) {
	os.Exit(execute(0, []string{args[0]}, conf, args[1], executingOther))
404 405 406 407 408
}

func connectCmd(cmd *cobra.Command, args []string) {
	addr := args[0]
	if addr == "" {
409
		fmt.Fprint(os.Stderr, "An empty address was provided. You must provide an address as the first argument.\n")
410 411 412 413 414 415 416 417 418 419 420 421 422 423
		os.Exit(1)
	}
	os.Exit(connect(addr, conf))
}

func splitArgs(cmd *cobra.Command, args []string) ([]string, []string) {
	if cmd.ArgsLenAtDash() >= 0 {
		return args[:cmd.ArgsLenAtDash()], args[cmd.ArgsLenAtDash():]
	}
	return args, []string{}
}

func connect(addr string, conf *config.Config) int {
	// Create and start a terminal - attach to running instance
424
	client := rpc2.NewClient(addr)
425 426 427 428 429 430 431 432
	term := terminal.New(client, conf)
	status, err := term.Run()
	if err != nil {
		fmt.Println(err)
	}
	return status
}

433 434 435 436 437
type executeKind int

const (
	executingExistingFile = executeKind(iota)
	executingGeneratedFile
438
	executingGeneratedTest
439 440 441
	executingOther
)

442
func execute(attachPid int, processArgs []string, conf *config.Config, coreFile string, kind executeKind) int {
443 444 445 446 447 448 449 450 451
	// Make a TCP listener
	listener, err := net.Listen("tcp", Addr)
	if err != nil {
		fmt.Printf("couldn't start listener: %s\n", err)
		return 1
	}
	defer listener.Close()

	if Headless && (InitFile != "") {
452
		fmt.Fprint(os.Stderr, "Warning: init file ignored\n")
453 454
	}

455 456 457 458 459
	var server interface {
		Run() error
		Stop(bool) error
	}

460 461
	disconnectChan := make(chan struct{})

462
	// Create and start a debugger server
A
aarzilli 已提交
463 464 465
	switch APIVersion {
	case 1, 2:
		server = rpccommon.NewServer(&service.Config{
466 467 468 469
			Listener:    listener,
			ProcessArgs: processArgs,
			AttachPid:   attachPid,
			AcceptMulti: AcceptMulti,
A
aarzilli 已提交
470
			APIVersion:  APIVersion,
E
Evgeny L 已提交
471
			WorkingDir:  WorkingDir,
472
			Backend:     Backend,
473
			CoreFile:    coreFile,
474 475

			DisconnectChan: disconnectChan,
476 477
		}, Log)
	default:
D
Derek Parker 已提交
478
		fmt.Printf("Unknown API version: %d\n", APIVersion)
479 480 481
		return 1
	}

482
	if err := server.Run(); err != nil {
483 484 485 486 487 488 489 490 491 492 493 494
		if err == api.NotExecutableErr {
			switch kind {
			case executingGeneratedFile:
				fmt.Fprintln(os.Stderr, "Can not debug non-main package")
				return 1
			case executingExistingFile:
				fmt.Fprintf(os.Stderr, "%s is not executable\n", processArgs[0])
				return 1
			default:
				// fallthrough
			}
		}
495 496 497 498 499 500
		fmt.Fprintln(os.Stderr, err)
		return 1
	}

	var status int
	if Headless {
501 502
		// Print listener address
		fmt.Printf("API server listening at: %s\n", listener.Addr())
503
		ch := make(chan os.Signal, 1)
504
		signal.Notify(ch, syscall.SIGINT)
505 506 507 508
		select {
		case <-ch:
		case <-disconnectChan:
		}
509 510 511
		err = server.Stop(true)
	} else {
		// Create and start a terminal
512
		client := rpc2.NewClient(listener.Addr().String())
513 514 515 516 517 518 519
		if client.Recorded() && (kind == executingGeneratedFile || kind == executingGeneratedTest) {
			// When using the rr backend remove the trace directory if we built the
			// executable
			if tracedir, err := client.TraceDirectory(); err == nil {
				defer SafeRemoveAll(tracedir)
			}
		}
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
		term := terminal.New(client, conf)
		term.InitFile = InitFile
		status, err = term.Run()
	}

	if err != nil {
		fmt.Println(err)
	}

	return status
}

func gobuild(debugname, pkg string) error {
	args := []string{"-gcflags", "-N -l", "-o", debugname}
	if BuildFlags != "" {
A
aarzilli 已提交
535
		args = append(args, config.SplitQuotedFields(BuildFlags, '\'')...)
536
	}
A
aarzilli 已提交
537 538 539 540
	if ver, _ := goversion.Installed(); ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
		// after go1.9 building with -gcflags='-N -l' and -a simultaneously works
		args = append(args, "-a")
	}
541 542 543 544 545 546 547
	args = append(args, pkg)
	return gocommand("build", args...)
}

func gotestbuild(pkg string) error {
	args := []string{"-gcflags", "-N -l", "-c", "-o", testdebugname}
	if BuildFlags != "" {
A
aarzilli 已提交
548
		args = append(args, config.SplitQuotedFields(BuildFlags, '\'')...)
549
	}
A
aarzilli 已提交
550 551 552 553
	if ver, _ := goversion.Installed(); ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
		// after go1.9 building with -gcflags='-N -l' and -a simultaneously works
		args = append(args, "-a")
	}
554 555 556 557 558 559 560 561 562 563 564
	args = append(args, pkg)
	return gocommand("test", args...)
}

func gocommand(command string, args ...string) error {
	allargs := []string{command}
	allargs = append(allargs, args...)
	goBuild := exec.Command("go", allargs...)
	goBuild.Stderr = os.Stderr
	return goBuild.Run()
}
565

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
// SafeRemoveAll removes dir and its contents but only as long as dir does
// not contain directories.
func SafeRemoveAll(dir string) {
	dh, err := os.Open(dir)
	if err != nil {
		return
	}
	defer dh.Close()
	fis, err := dh.Readdir(-1)
	if err != nil {
		return
	}
	for _, fi := range fis {
		if fi.IsDir() {
			return
		}
	}
	for _, fi := range fis {
		if err := os.Remove(filepath.Join(dir, fi.Name())); err != nil {
			return
		}
	}
	os.Remove(dir)
}