command.go 36.5 KB
Newer Older
1
// Package terminal implements functions for responding to user
D
Dan Mace 已提交
2 3 4 5 6
// input and dispatching to appropriate backend commands.
package terminal

import (
	"bufio"
A
aarzilli 已提交
7
	"errors"
D
Dan Mace 已提交
8
	"fmt"
9 10
	"go/parser"
	"go/scanner"
11
	"io"
12
	"math"
D
Dan Mace 已提交
13 14 15 16 17
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
D
Derek Parker 已提交
18
	"text/tabwriter"
D
Dan Mace 已提交
19 20 21

	"github.com/derekparker/delve/service"
	"github.com/derekparker/delve/service/api"
22
	"github.com/derekparker/delve/service/debugger"
D
Dan Mace 已提交
23 24
)

25
type cmdPrefix int
26

27 28 29 30 31 32 33 34 35 36 37 38 39
const (
	noPrefix    = cmdPrefix(0)
	scopePrefix = cmdPrefix(1 << iota)
	onPrefix
)

type callContext struct {
	Prefix     cmdPrefix
	Scope      api.EvalScope
	Breakpoint *api.Breakpoint
}

type cmdfunc func(t *Term, ctx callContext, args string) error
D
Dan Mace 已提交
40 41

type command struct {
42 43 44 45
	aliases         []string
	allowedPrefixes cmdPrefix
	helpMsg         string
	cmdFn           cmdfunc
D
Dan Mace 已提交
46 47 48 49 50 51 52 53 54 55 56 57
}

// Returns true if the command string matches one of the aliases for this command
func (c command) match(cmdstr string) bool {
	for _, v := range c.aliases {
		if v == cmdstr {
			return true
		}
	}
	return false
}

D
Derek Parker 已提交
58
// Commands represents the commands for Delve terminal process.
D
Dan Mace 已提交
59
type Commands struct {
D
Derek Parker 已提交
60 61 62
	cmds    []command
	lastCmd cmdfunc
	client  service.Client
D
Dan Mace 已提交
63 64
}

65 66 67 68 69
var (
	LongLoadConfig  = api.LoadConfig{true, 1, 64, 64, -1}
	ShortLoadConfig = api.LoadConfig{false, 0, 64, 0, 3}
)

70 71 72 73 74 75
type ByFirstAlias []command

func (a ByFirstAlias) Len() int           { return len(a) }
func (a ByFirstAlias) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByFirstAlias) Less(i, j int) bool { return a[i].aliases[0] < a[j].aliases[0] }

D
Derek Parker 已提交
76
// DebugCommands returns a Commands struct with default commands defined.
D
Dan Mace 已提交
77 78 79 80
func DebugCommands(client service.Client) *Commands {
	c := &Commands{client: client}

	c.cmds = []command{
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
		{aliases: []string{"help", "h"}, cmdFn: c.help, helpMsg: `Prints the help message.

	help [command]
	
Type "help" followed by the name of a command for more information about it.`},
		{aliases: []string{"break", "b"}, cmdFn: breakpoint, helpMsg: `Sets a breakpoint.

	break [name] <linespec>

See $GOPATH/src/github.com/derekparker/delve/Documentation/cli/locspec.md for the syntax of linespec.

See also: "help on", "help cond" and "help clear"`},
		{aliases: []string{"trace", "t"}, cmdFn: tracepoint, helpMsg: `Set tracepoint.

	trace [name] <linespec>
	
A tracepoint is a breakpoint that does not stop the execution of the program, instead when the tracepoint is hit a notification is displayed. See $GOPATH/src/github.com/derekparker/delve/Documentation/cli/locspec.md for the syntax of linespec.

See also: "help on", "help cond" and "help clear"`},
D
Derek Parker 已提交
100
		{aliases: []string{"restart", "r"}, cmdFn: restart, helpMsg: "Restart process."},
D
Dan Mace 已提交
101
		{aliases: []string{"continue", "c"}, cmdFn: cont, helpMsg: "Run until breakpoint or program termination."},
102
		{aliases: []string{"step", "s"}, allowedPrefixes: scopePrefix, cmdFn: step, helpMsg: "Single step through program."},
103
		{aliases: []string{"step-instruction", "si"}, allowedPrefixes: scopePrefix, cmdFn: stepInstruction, helpMsg: "Single step a single cpu instruction."},
104
		{aliases: []string{"next", "n"}, allowedPrefixes: scopePrefix, cmdFn: next, helpMsg: "Step over to next source line."},
A
aarzilli 已提交
105
		{aliases: []string{"stepout"}, allowedPrefixes: scopePrefix, cmdFn: stepout, helpMsg: "Step out of the current function."},
D
Dan Mace 已提交
106
		{aliases: []string{"threads"}, cmdFn: threads, helpMsg: "Print out info for every traced thread."},
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
		{aliases: []string{"thread", "tr"}, cmdFn: thread, helpMsg: `Switch to the specified thread.

	thread <id>`},
		{aliases: []string{"clear"}, cmdFn: clear, helpMsg: `Deletes breakpoint.

	clear <breakpoint name or id>`},
		{aliases: []string{"clearall"}, cmdFn: clearAll, helpMsg: `Deletes multiple breakpoints.

	clearall [<linespec>]
	
If called with the linespec argument it will delete all the breakpoints matching the linespec. If linespec is omitted all breakpoints are deleted.`},
		{aliases: []string{"goroutines"}, cmdFn: goroutines, helpMsg: `List program goroutines.

	goroutines [-u (default: user location)|-r (runtime location)|-g (go statement location)]

Print out info for every goroutine. The flag controls what information is shown along with each goroutine:

	-u	displays location of topmost stackframe in user code
	-r	displays location of topmost stackframe (including frames inside private runtime functions)
	-g	displays location of go instruction that created the goroutine
	
If no flag is specified the default is -u.`},
		{aliases: []string{"goroutine"}, allowedPrefixes: onPrefix | scopePrefix, cmdFn: c.goroutine, helpMsg: `Shows or changes current goroutine

	goroutine
	goroutine <id>
	goroutine <id> <command>

Called without arguments it will show information about the current goroutine.
Called with a single argument it will switch to the specified goroutine.
Called with more arguments it will execute a command on the specified goroutine.`},
D
Dan Mace 已提交
138
		{aliases: []string{"breakpoints", "bp"}, cmdFn: breakpoints, helpMsg: "Print out info for active breakpoints."},
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
		{aliases: []string{"print", "p"}, allowedPrefixes: onPrefix | scopePrefix, cmdFn: printVar, helpMsg: `Evaluate an expression.

	[goroutine <n>] [frame <m>] print <expression>

See $GOPATH/src/github.com/derekparker/delve/Documentation/cli/expr.md for a description of supported expressions.`},
		{aliases: []string{"set"}, allowedPrefixes: scopePrefix, cmdFn: setVar, helpMsg: `Changes the value of a variable.

	[goroutine <n>] [frame <m>] set <variable> = <value>

See $GOPATH/src/github.com/derekparker/delve/Documentation/cli/expr.md for a description of supported expressions. Only numerical variables and pointers can be changed.`},
		{aliases: []string{"sources"}, cmdFn: sources, helpMsg: `Print list of source files.

	sources [<regex>]

If regex is specified only the source files matching it will be returned.`},
		{aliases: []string{"funcs"}, cmdFn: funcs, helpMsg: `Print list of functions.

	funcs [<regex>]

If regex is specified only the functions matching it will be returned.`},
		{aliases: []string{"types"}, cmdFn: types, helpMsg: `Print list of types

	types [<regex>]

If regex is specified only the functions matching it will be returned.`},
		{aliases: []string{"args"}, allowedPrefixes: scopePrefix | onPrefix, cmdFn: args, helpMsg: `Print function arguments.

	[goroutine <n>] [frame <m>] args [-v] [<regex>]

If regex is specified only function arguments with a name matching it will be returned. If -v is specified more information about each function argument will be shown.`},
		{aliases: []string{"locals"}, allowedPrefixes: scopePrefix | onPrefix, cmdFn: locals, helpMsg: `Print local variables.

	[goroutine <n>] [frame <m>] locals [-v] [<regex>]

If regex is specified only local variables with a name matching it will be returned. If -v is specified more information about each local variable will be shown.`},
		{aliases: []string{"vars"}, cmdFn: vars, helpMsg: `Print package variables.

	vars [-v] [<regex>]

If regex is specified only package variables with a name matching it will be returned. If -v is specified more information about each package variable will be shown.`},
A
aarzilli 已提交
179 180 181 182 183
		{aliases: []string{"regs"}, cmdFn: regs, helpMsg: `Print contents of CPU registers.

	regs [-a]
	
Argument -a shows more registers.`},
D
Derek Parker 已提交
184
		{aliases: []string{"exit", "quit", "q"}, cmdFn: exitCommand, helpMsg: "Exit the debugger."},
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
		{aliases: []string{"list", "ls"}, allowedPrefixes: scopePrefix, cmdFn: listCommand, helpMsg: `Show source code.

	[goroutine <n>] [frame <m>] list [<linespec>]

Show source around current point or provided linespec.`},
		{aliases: []string{"stack", "bt"}, allowedPrefixes: scopePrefix | onPrefix, cmdFn: stackCommand, helpMsg: `Print stack trace.

	[goroutine <n>] [frame <m>] stack [<depth>] [-full]

If -full is specified every stackframe will be decorated by the value of its local variables and function arguments.`},
		{aliases: []string{"frame"}, allowedPrefixes: scopePrefix, cmdFn: c.frame, helpMsg: `Executes command on a different frame.

	frame <frame index> <command>.`},
		{aliases: []string{"source"}, cmdFn: c.sourceCommand, helpMsg: `Executes a file containing a list of delve commands

	source <path>`},
		{aliases: []string{"disassemble", "disass"}, allowedPrefixes: scopePrefix, cmdFn: disassCommand, helpMsg: `Disassembler.

	[goroutine <n>] [frame <m>] disassemble [-a <start> <end>] [-l <locspec>]

If no argument is specified the function being executed in the selected stack frame will be executed.
	
	-a <start> <end>	disassembles the specified address range
	-l <locspec>		disassembles the specified function`},
		{aliases: []string{"on"}, cmdFn: c.onCmd, helpMsg: `Executes a command when a breakpoint is hit.

	on <breakpoint name or id> <command>.
	
Supported commands: print, stack and goroutine)`},
		{aliases: []string{"condition", "cond"}, cmdFn: conditionCmd, helpMsg: `Set breakpoint condition.

	condition <breakpoint name or id> <boolean expression>.
	
Specifies that the breakpoint or tracepoint should break only if the boolean expression is true.`},
D
Dan Mace 已提交
219 220
	}

221
	sort.Sort(ByFirstAlias(c.cmds))
D
Dan Mace 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
	return c
}

// Register custom commands. Expects cf to be a func of type cmdfunc,
// returning only an error.
func (c *Commands) Register(cmdstr string, cf cmdfunc, helpMsg string) {
	for _, v := range c.cmds {
		if v.match(cmdstr) {
			v.cmdFn = cf
			return
		}
	}

	c.cmds = append(c.cmds, command{aliases: []string{cmdstr}, cmdFn: cf, helpMsg: helpMsg})
}

// Find will look up the command function for the given command input.
D
Derek Parker 已提交
239
// If it cannot find the command it will default to noCmdAvailable().
D
Dan Mace 已提交
240
// If the command is an empty string it will replay the last command.
241
func (c *Commands) Find(cmdstr string, prefix cmdPrefix) cmdfunc {
D
Dan Mace 已提交
242 243 244 245 246 247 248 249 250 251
	// If <enter> use last command, if there was one.
	if cmdstr == "" {
		if c.lastCmd != nil {
			return c.lastCmd
		}
		return nullCommand
	}

	for _, v := range c.cmds {
		if v.match(cmdstr) {
252 253 254
			if prefix != noPrefix && v.allowedPrefixes&prefix == 0 {
				continue
			}
D
Dan Mace 已提交
255 256 257 258 259 260 261 262
			c.lastCmd = v.cmdFn
			return v.cmdFn
		}
	}

	return noCmdAvailable
}

263 264 265 266 267 268 269 270 271
func (c *Commands) CallWithContext(cmdstr, args string, t *Term, ctx callContext) error {
	return c.Find(cmdstr, ctx.Prefix)(t, ctx, args)
}

func (c *Commands) Call(cmdstr, args string, t *Term) error {
	ctx := callContext{Prefix: noPrefix, Scope: api.EvalScope{GoroutineID: -1, Frame: 0}}
	return c.CallWithContext(cmdstr, args, t, ctx)
}

272 273 274 275 276 277 278 279 280
// Merge takes aliases defined in the config struct and merges them with the default aliases.
func (c *Commands) Merge(allAliases map[string][]string) {
	for i := range c.cmds {
		if aliases, ok := allAliases[c.cmds[i].aliases[0]]; ok {
			c.cmds[i].aliases = append(c.cmds[i].aliases, aliases...)
		}
	}
}

281 282
var noCmdError = errors.New("command not available")

283
func noCmdAvailable(t *Term, ctx callContext, args string) error {
284
	return noCmdError
D
Dan Mace 已提交
285 286
}

287
func nullCommand(t *Term, ctx callContext, args string) error {
D
Dan Mace 已提交
288 289 290
	return nil
}

291
func (c *Commands) help(t *Term, ctx callContext, args string) error {
292 293 294 295 296 297 298 299 300 301 302 303
	if args != "" {
		for _, cmd := range c.cmds {
			for _, alias := range cmd.aliases {
				if alias == args {
					fmt.Println(cmd.helpMsg)
					return nil
				}
			}
		}
		return noCmdError
	}

D
Dan Mace 已提交
304
	fmt.Println("The following commands are available:")
D
Derek Parker 已提交
305 306
	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 8, 0, '-', 0)
D
Dan Mace 已提交
307
	for _, cmd := range c.cmds {
308 309 310 311
		h := cmd.helpMsg
		if idx := strings.Index(h, "\n"); idx >= 0 {
			h = h[:idx]
		}
D
Derek Parker 已提交
312
		if len(cmd.aliases) > 1 {
313
			fmt.Fprintf(w, "    %s (alias: %s) \t %s\n", cmd.aliases[0], strings.Join(cmd.aliases[1:], " | "), h)
D
Derek Parker 已提交
314
		} else {
315
			fmt.Fprintf(w, "    %s \t %s\n", cmd.aliases[0], h)
D
Derek Parker 已提交
316
		}
D
Dan Mace 已提交
317
	}
318 319 320 321 322
	if err := w.Flush(); err != nil {
		return err
	}
	fmt.Println("Type help followed by a command for full documentation.")
	return nil
D
Dan Mace 已提交
323 324
}

I
Ilia Choly 已提交
325
type byThreadID []*api.Thread
I
Ilia Choly 已提交
326

I
Ilia Choly 已提交
327 328 329
func (a byThreadID) Len() int           { return len(a) }
func (a byThreadID) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byThreadID) Less(i, j int) bool { return a[i].ID < a[j].ID }
I
Ilia Choly 已提交
330

331
func threads(t *Term, ctx callContext, args string) error {
332
	threads, err := t.client.ListThreads()
D
Dan Mace 已提交
333 334 335
	if err != nil {
		return err
	}
336
	state, err := t.client.GetState()
D
Dan Mace 已提交
337 338 339
	if err != nil {
		return err
	}
I
Ilia Choly 已提交
340
	sort.Sort(byThreadID(threads))
D
Dan Mace 已提交
341 342 343 344 345 346 347
	for _, th := range threads {
		prefix := "  "
		if state.CurrentThread != nil && state.CurrentThread.ID == th.ID {
			prefix = "* "
		}
		if th.Function != nil {
			fmt.Printf("%sThread %d at %#v %s:%d %s\n",
348
				prefix, th.ID, th.PC, ShortenFilePath(th.File),
D
Dan Mace 已提交
349 350
				th.Line, th.Function.Name)
		} else {
351
			fmt.Printf("%sThread %s\n", prefix, formatThread(th))
D
Dan Mace 已提交
352 353 354 355 356
		}
	}
	return nil
}

357
func thread(t *Term, ctx callContext, args string) error {
358 359 360
	if len(args) == 0 {
		return fmt.Errorf("you must specify a thread")
	}
361
	tid, err := strconv.Atoi(args)
D
Dan Mace 已提交
362 363 364
	if err != nil {
		return err
	}
365
	oldState, err := t.client.GetState()
D
Dan Mace 已提交
366 367 368
	if err != nil {
		return err
	}
369
	newState, err := t.client.SwitchThread(tid)
D
Dan Mace 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
	if err != nil {
		return err
	}

	oldThread := "<none>"
	newThread := "<none>"
	if oldState.CurrentThread != nil {
		oldThread = strconv.Itoa(oldState.CurrentThread.ID)
	}
	if newState.CurrentThread != nil {
		newThread = strconv.Itoa(newState.CurrentThread.ID)
	}
	fmt.Printf("Switched from %s to %s\n", oldThread, newThread)
	return nil
}

I
Ilia Choly 已提交
386 387 388 389 390 391
type byGoroutineID []*api.Goroutine

func (a byGoroutineID) Len() int           { return len(a) }
func (a byGoroutineID) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byGoroutineID) Less(i, j int) bool { return a[i].ID < a[j].ID }

392
func goroutines(t *Term, ctx callContext, argstr string) error {
393
	args := strings.Split(argstr, " ")
394 395 396 397 398 399 400 401 402 403 404 405 406
	var fgl = fglUserCurrent

	switch len(args) {
	case 0:
		// nothing to do
	case 1:
		switch args[0] {
		case "-u":
			fgl = fglUserCurrent
		case "-r":
			fgl = fglRuntimeCurrent
		case "-g":
			fgl = fglGo
407 408
		case "":
			// nothing to do
409
		default:
D
Derek Parker 已提交
410
			return fmt.Errorf("wrong argument: '%s'", args[0])
411 412 413 414
		}
	default:
		return fmt.Errorf("too many arguments")
	}
415
	state, err := t.client.GetState()
416 417 418
	if err != nil {
		return err
	}
419
	gs, err := t.client.ListGoroutines()
D
Dan Mace 已提交
420 421 422
	if err != nil {
		return err
	}
I
Ilia Choly 已提交
423
	sort.Sort(byGoroutineID(gs))
D
Dan Mace 已提交
424 425
	fmt.Printf("[%d goroutines]\n", len(gs))
	for _, g := range gs {
426
		prefix := "  "
427
		if state.SelectedGoroutine != nil && g.ID == state.SelectedGoroutine.ID {
428 429
			prefix = "* "
		}
430
		fmt.Printf("%sGoroutine %s\n", prefix, formatGoroutine(g, fgl))
431 432 433 434
	}
	return nil
}

435 436
func (c *Commands) goroutine(t *Term, ctx callContext, argstr string) error {
	args := strings.SplitN(argstr, " ", 3)
437

438 439 440
	if ctx.Prefix == onPrefix {
		if len(args) != 1 || args[0] != "" {
			return errors.New("too many arguments to goroutine")
441
		}
442
		ctx.Breakpoint.Goroutine = true
443 444 445
		return nil
	}

446 447 448 449
	switch len(args) {
	case 1:
		if ctx.Prefix == scopePrefix {
			return errors.New("no command passed to goroutine")
450
		}
451 452
		if args[0] == "" {
			return printscope(t)
H
Hubert Krauze 已提交
453 454 455 456 457
		}
		gid, err := strconv.Atoi(argstr)
		if err != nil {
			return err
		}
458

H
Hubert Krauze 已提交
459 460 461 462 463 464 465
		oldState, err := t.client.GetState()
		if err != nil {
			return err
		}
		newState, err := t.client.SwitchGoroutine(gid)
		if err != nil {
			return err
466
		}
H
Hubert Krauze 已提交
467 468 469

		fmt.Printf("Switched from %d to %d (thread %d)\n", oldState.SelectedGoroutine.ID, gid, newState.CurrentThread.ID)
		return nil
470 471
	case 2:
		args = append(args, "")
472 473
	}

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
	var err error
	ctx.Prefix = scopePrefix
	ctx.Scope.GoroutineID, err = strconv.Atoi(args[0])
	if err != nil {
		return err
	}
	return c.CallWithContext(args[1], args[2], t, ctx)
}

func (c *Commands) frame(t *Term, ctx callContext, args string) error {
	v := strings.SplitN(args, " ", 3)

	switch len(v) {
	case 0, 1:
		return errors.New("not enough arguments")
	case 2:
		v = append(v, "")
	}

H
Hubert Krauze 已提交
493
	var err error
494 495 496 497 498 499
	ctx.Prefix = scopePrefix
	ctx.Scope.Frame, err = strconv.Atoi(v[0])
	if err != nil {
		return err
	}
	return c.CallWithContext(v[1], v[2], t, ctx)
500 501
}

502 503
func printscope(t *Term) error {
	state, err := t.client.GetState()
504 505
	if err != nil {
		return err
D
Dan Mace 已提交
506
	}
507

508 509 510 511
	fmt.Printf("Thread %s\n", formatThread(state.CurrentThread))
	if state.SelectedGoroutine != nil {
		writeGoroutineLong(os.Stdout, state.SelectedGoroutine, "")
	}
D
Dan Mace 已提交
512 513 514
	return nil
}

515 516 517 518
func formatThread(th *api.Thread) string {
	if th == nil {
		return "<nil>"
	}
519
	return fmt.Sprintf("%d at %s:%d", th.ID, ShortenFilePath(th.File), th.Line)
520 521
}

522 523 524 525 526 527 528 529 530 531 532 533 534
type formatGoroutineLoc int

const (
	fglRuntimeCurrent = formatGoroutineLoc(iota)
	fglUserCurrent
	fglGo
)

func formatLocation(loc api.Location) string {
	fname := ""
	if loc.Function != nil {
		fname = loc.Function.Name
	}
535
	return fmt.Sprintf("%s:%d %s (%#v)", ShortenFilePath(loc.File), loc.Line, fname, loc.PC)
536 537 538
}

func formatGoroutine(g *api.Goroutine, fgl formatGoroutineLoc) string {
539 540 541
	if g == nil {
		return "<nil>"
	}
542 543 544 545 546
	var locname string
	var loc api.Location
	switch fgl {
	case fglRuntimeCurrent:
		locname = "Runtime"
547
		loc = g.CurrentLoc
548 549
	case fglUserCurrent:
		locname = "User"
550
		loc = g.UserCurrentLoc
551 552
	case fglGo:
		locname = "Go"
553
		loc = g.GoStatementLoc
A
aarzilli 已提交
554
	}
555 556 557 558 559
	thread := ""
	if g.ThreadID != 0 {
		thread = fmt.Sprintf(" (thread %d)", g.ThreadID)
	}
	return fmt.Sprintf("%d - %s: %s%s", g.ID, locname, formatLocation(loc), thread)
560 561 562 563 564
}

func writeGoroutineLong(w io.Writer, g *api.Goroutine, prefix string) {
	fmt.Fprintf(w, "%sGoroutine %d:\n%s\tRuntime: %s\n%s\tUser: %s\n%s\tGo: %s\n",
		prefix, g.ID,
565 566 567
		prefix, formatLocation(g.CurrentLoc),
		prefix, formatLocation(g.UserCurrentLoc),
		prefix, formatLocation(g.GoStatementLoc))
A
aarzilli 已提交
568 569
}

570
func restart(t *Term, ctx callContext, args string) error {
571
	if err := t.client.Restart(); err != nil {
D
Derek Parker 已提交
572 573
		return err
	}
574
	fmt.Println("Process restarted with PID", t.client.ProcessPid())
D
Derek Parker 已提交
575 576 577
	return nil
}

578
func cont(t *Term, ctx callContext, args string) error {
579
	stateChan := t.client.Continue()
580 581
	var state *api.DebuggerState
	for state = range stateChan {
A
aarzilli 已提交
582 583 584
		if state.Err != nil {
			return state.Err
		}
585
		printcontext(t, state)
D
Dan Mace 已提交
586
	}
587
	printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
D
Dan Mace 已提交
588 589 590
	return nil
}

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
func continueUntilCompleteNext(t *Term, state *api.DebuggerState, op string) error {
	if !state.NextInProgress {
		printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
		return nil
	}
	for {
		stateChan := t.client.Continue()
		var state *api.DebuggerState
		for state = range stateChan {
			if state.Err != nil {
				return state.Err
			}
			printcontext(t, state)
		}
		if !state.NextInProgress {
			printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
			return nil
		}
		fmt.Printf("\tbreakpoint hit during %s, continuing...\n", op)
	}
}

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
func scopePrefixSwitch(t *Term, ctx callContext) error {
	if ctx.Prefix != scopePrefix {
		return nil
	}
	if ctx.Scope.Frame != 0 {
		return errors.New("frame prefix not accepted")
	}
	if ctx.Scope.GoroutineID > 0 {
		_, err := t.client.SwitchGoroutine(ctx.Scope.GoroutineID)
		if err != nil {
			return err
		}
	}
	return nil
}

629
func step(t *Term, ctx callContext, args string) error {
630 631 632
	if err := scopePrefixSwitch(t, ctx); err != nil {
		return err
	}
633
	state, err := t.client.Step()
D
Dan Mace 已提交
634 635 636
	if err != nil {
		return err
	}
637
	printcontext(t, state)
638
	return continueUntilCompleteNext(t, state, "step")
D
Dan Mace 已提交
639 640
}

641
func stepInstruction(t *Term, ctx callContext, args string) error {
642 643 644
	if err := scopePrefixSwitch(t, ctx); err != nil {
		return err
	}
645 646 647 648 649
	state, err := t.client.StepInstruction()
	if err != nil {
		return err
	}
	printcontext(t, state)
650
	printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
651 652 653
	return nil
}

654
func next(t *Term, ctx callContext, args string) error {
655 656
	if err := scopePrefixSwitch(t, ctx); err != nil {
		return err
657
	}
658
	state, err := t.client.Next()
D
Dan Mace 已提交
659 660 661
	if err != nil {
		return err
	}
662
	printcontext(t, state)
663
	return continueUntilCompleteNext(t, state, "next")
D
Dan Mace 已提交
664 665
}

A
aarzilli 已提交
666 667 668 669 670 671 672 673 674 675 676 677
func stepout(t *Term, ctx callContext, args string) error {
	if err := scopePrefixSwitch(t, ctx); err != nil {
		return err
	}
	state, err := t.client.StepOut()
	if err != nil {
		return err
	}
	printcontext(t, state)
	return continueUntilCompleteNext(t, state, "stepout")
}

678
func clear(t *Term, ctx callContext, args string) error {
D
Dan Mace 已提交
679
	if len(args) == 0 {
D
Derek Parker 已提交
680
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
681
	}
682
	id, err := strconv.Atoi(args)
683 684 685 686 687
	var bp *api.Breakpoint
	if err == nil {
		bp, err = t.client.ClearBreakpoint(id)
	} else {
		bp, err = t.client.ClearBreakpointByName(args)
D
Dan Mace 已提交
688 689 690 691
	}
	if err != nil {
		return err
	}
692
	fmt.Printf("%s cleared at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp))
D
Dan Mace 已提交
693 694 695
	return nil
}

696
func clearAll(t *Term, ctx callContext, args string) error {
697
	breakPoints, err := t.client.ListBreakpoints()
D
Dan Mace 已提交
698 699 700
	if err != nil {
		return err
	}
701 702

	var locPCs map[uint64]struct{}
703
	if args != "" {
D
Derek Parker 已提交
704
		locs, err := t.client.FindLocation(api.EvalScope{GoroutineID: -1, Frame: 0}, args)
705 706 707 708 709 710 711 712 713
		if err != nil {
			return err
		}
		locPCs = make(map[uint64]struct{})
		for _, loc := range locs {
			locPCs[loc.PC] = struct{}{}
		}
	}

D
Dan Mace 已提交
714
	for _, bp := range breakPoints {
715 716 717 718 719 720
		if locPCs != nil {
			if _, ok := locPCs[bp.Addr]; !ok {
				continue
			}
		}

721 722 723 724
		if bp.ID < 0 {
			continue
		}

725
		_, err := t.client.ClearBreakpoint(bp.ID)
D
Dan Mace 已提交
726
		if err != nil {
727
			fmt.Printf("Couldn't delete %s at %s: %s\n", formatBreakpointName(bp, false), formatBreakpointLocation(bp), err)
D
Dan Mace 已提交
728
		}
729
		fmt.Printf("%s cleared at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp))
D
Dan Mace 已提交
730 731 732 733
	}
	return nil
}

D
Derek Parker 已提交
734 735
// ByID sorts breakpoints by ID.
type ByID []*api.Breakpoint
D
Dan Mace 已提交
736

D
Derek Parker 已提交
737 738 739
func (a ByID) Len() int           { return len(a) }
func (a ByID) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByID) Less(i, j int) bool { return a[i].ID < a[j].ID }
D
Dan Mace 已提交
740

741
func breakpoints(t *Term, ctx callContext, args string) error {
742
	breakPoints, err := t.client.ListBreakpoints()
D
Dan Mace 已提交
743 744 745
	if err != nil {
		return err
	}
D
Derek Parker 已提交
746
	sort.Sort(ByID(breakPoints))
D
Dan Mace 已提交
747
	for _, bp := range breakPoints {
748
		fmt.Printf("%s at %v (%d)\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp), bp.TotalHitCount)
A
aarzilli 已提交
749 750

		var attrs []string
751 752 753
		if bp.Cond != "" {
			attrs = append(attrs, fmt.Sprintf("\tcond %s", bp.Cond))
		}
A
aarzilli 已提交
754
		if bp.Stacktrace > 0 {
755
			attrs = append(attrs, fmt.Sprintf("\tstack %d", bp.Stacktrace))
A
aarzilli 已提交
756 757
		}
		if bp.Goroutine {
758
			attrs = append(attrs, "\tgoroutine")
A
aarzilli 已提交
759
		}
760 761 762 763 764 765 766 767 768 769 770 771 772 773
		if bp.LoadArgs != nil {
			if *(bp.LoadArgs) == LongLoadConfig {
				attrs = append(attrs, "\targs -v")
			} else {
				attrs = append(attrs, "\targs")
			}
		}
		if bp.LoadLocals != nil {
			if *(bp.LoadLocals) == LongLoadConfig {
				attrs = append(attrs, "\tlocals -v")
			} else {
				attrs = append(attrs, "\tlocals")
			}
		}
D
Derek Parker 已提交
774
		for i := range bp.Variables {
775
			attrs = append(attrs, fmt.Sprintf("\tprint %s", bp.Variables[i]))
A
aarzilli 已提交
776 777
		}
		if len(attrs) > 0 {
778
			fmt.Printf("%s\n", strings.Join(attrs, "\n"))
A
aarzilli 已提交
779
		}
D
Dan Mace 已提交
780 781 782 783
	}
	return nil
}

784
func setBreakpoint(t *Term, tracepoint bool, argstr string) error {
785
	args := strings.SplitN(argstr, " ", 2)
D
Dan Mace 已提交
786

787 788 789 790 791 792 793 794 795 796 797
	requestedBp := &api.Breakpoint{}
	locspec := ""
	switch len(args) {
	case 1:
		locspec = argstr
	case 2:
		if api.ValidBreakpointName(args[0]) == nil {
			requestedBp.Name = args[0]
			locspec = args[1]
		} else {
			locspec = argstr
A
aarzilli 已提交
798
		}
799 800
	default:
		return fmt.Errorf("address required")
A
aarzilli 已提交
801 802 803
	}

	requestedBp.Tracepoint = tracepoint
804
	locs, err := t.client.FindLocation(api.EvalScope{GoroutineID: -1, Frame: 0}, locspec)
D
Dan Mace 已提交
805
	if err != nil {
806 807 808 809 810 811
		if requestedBp.Name == "" {
			return err
		}
		requestedBp.Name = ""
		locspec = argstr
		var err2 error
H
Hubert Krauze 已提交
812
		locs, err2 = t.client.FindLocation(api.EvalScope{GoroutineID: -1, Frame: 0}, locspec)
813 814 815
		if err2 != nil {
			return err
		}
A
aarzilli 已提交
816
	}
817 818 819
	for _, loc := range locs {
		requestedBp.Addr = loc.PC

820
		bp, err := t.client.CreateBreakpoint(requestedBp)
821 822 823 824
		if err != nil {
			return err
		}

825
		fmt.Printf("%s set at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp))
826
	}
D
Dan Mace 已提交
827 828 829
	return nil
}

830
func breakpoint(t *Term, ctx callContext, args string) error {
831
	return setBreakpoint(t, false, args)
A
aarzilli 已提交
832 833
}

834
func tracepoint(t *Term, ctx callContext, args string) error {
835
	return setBreakpoint(t, true, args)
A
aarzilli 已提交
836 837
}

838
func printVar(t *Term, ctx callContext, args string) error {
D
Dan Mace 已提交
839
	if len(args) == 0 {
D
Derek Parker 已提交
840
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
841
	}
842 843 844 845
	if ctx.Prefix == onPrefix {
		ctx.Breakpoint.Variables = append(ctx.Breakpoint.Variables, args)
		return nil
	}
846
	val, err := t.client.EvalVariable(ctx.Scope, args, LongLoadConfig)
D
Dan Mace 已提交
847 848 849
	if err != nil {
		return err
	}
850 851

	fmt.Println(val.MultilineString(""))
D
Dan Mace 已提交
852 853 854
	return nil
}

855
func setVar(t *Term, ctx callContext, args string) error {
856 857 858 859
	// HACK: in go '=' is not an operator, we detect the error and try to recover from it by splitting the input string
	_, err := parser.ParseExpr(args)
	if err == nil {
		return fmt.Errorf("syntax error '=' not found")
860 861
	}

862 863 864 865 866 867 868
	el, ok := err.(scanner.ErrorList)
	if !ok || el[0].Msg != "expected '==', found '='" {
		return err
	}

	lexpr := args[:el[0].Pos.Offset]
	rexpr := args[el[0].Pos.Offset+1:]
869
	return t.client.SetVariable(ctx.Scope, lexpr, rexpr)
870 871
}

872
func printFilteredVariables(varType string, vars []api.Variable, filter string, cfg api.LoadConfig) error {
D
Derek Parker 已提交
873 874
	reg, err := regexp.Compile(filter)
	if err != nil {
875
		return err
D
Derek Parker 已提交
876
	}
877
	match := false
D
Dan Mace 已提交
878
	for _, v := range vars {
D
Derek Parker 已提交
879
		if reg == nil || reg.Match([]byte(v.Name)) {
880 881 882 883 884 885
			match = true
			if cfg == ShortLoadConfig {
				fmt.Printf("%s = %s\n", v.Name, v.SinglelineString())
			} else {
				fmt.Printf("%s = %s\n", v.Name, v.MultilineString(""))
			}
D
Dan Mace 已提交
886 887
		}
	}
888 889 890 891
	if !match {
		fmt.Printf("(no %s)\n", varType)
	}
	return nil
D
Dan Mace 已提交
892 893
}

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
func printSortedStrings(v []string, err error) error {
	if err != nil {
		return err
	}
	sort.Strings(v)
	for _, d := range v {
		fmt.Println(d)
	}
	return nil
}

func sources(t *Term, ctx callContext, args string) error {
	return printSortedStrings(t.client.ListSources(args))
}

func funcs(t *Term, ctx callContext, args string) error {
	return printSortedStrings(t.client.ListFunctions(args))
D
Derek Parker 已提交
911
}
D
Dan Mace 已提交
912

913 914
func types(t *Term, ctx callContext, args string) error {
	return printSortedStrings(t.client.ListTypes(args))
D
Derek Parker 已提交
915
}
D
Dan Mace 已提交
916

917 918 919 920 921 922 923 924 925
func parseVarArguments(args string) (filter string, cfg api.LoadConfig) {
	if v := strings.SplitN(args, " ", 2); len(v) >= 1 && v[0] == "-v" {
		if len(v) == 2 {
			return v[1], LongLoadConfig
		} else {
			return "", LongLoadConfig
		}
	}
	return args, ShortLoadConfig
A
aarzilli 已提交
926 927
}

928 929 930 931 932 933 934 935 936 937
func args(t *Term, ctx callContext, args string) error {
	filter, cfg := parseVarArguments(args)
	if ctx.Prefix == onPrefix {
		if filter != "" {
			return fmt.Errorf("filter not supported on breakpoint")
		}
		ctx.Breakpoint.LoadArgs = &cfg
		return nil
	}
	vars, err := t.client.ListFunctionArgs(ctx.Scope, cfg)
D
Derek Parker 已提交
938
	if err != nil {
939
		return err
D
Derek Parker 已提交
940
	}
941
	return printFilteredVariables("args", vars, filter, cfg)
D
Derek Parker 已提交
942
}
D
Dan Mace 已提交
943

944 945 946 947 948 949 950 951 952 953
func locals(t *Term, ctx callContext, args string) error {
	filter, cfg := parseVarArguments(args)
	if ctx.Prefix == onPrefix {
		if filter != "" {
			return fmt.Errorf("filter not supported on breakpoint")
		}
		ctx.Breakpoint.LoadLocals = &cfg
		return nil
	}
	locals, err := t.client.ListLocalVariables(ctx.Scope, cfg)
D
Derek Parker 已提交
954
	if err != nil {
955
		return err
D
Derek Parker 已提交
956
	}
957
	return printFilteredVariables("locals", locals, filter, cfg)
D
Derek Parker 已提交
958
}
D
Dan Mace 已提交
959

960 961 962
func vars(t *Term, ctx callContext, args string) error {
	filter, cfg := parseVarArguments(args)
	vars, err := t.client.ListPackageVariables(filter, cfg)
D
Derek Parker 已提交
963
	if err != nil {
964
		return err
D
Derek Parker 已提交
965
	}
966
	return printFilteredVariables("vars", vars, filter, cfg)
D
Derek Parker 已提交
967
}
D
Dan Mace 已提交
968

969
func regs(t *Term, ctx callContext, args string) error {
A
aarzilli 已提交
970 971 972 973 974
	includeFp := false
	if args == "-a" {
		includeFp = true
	}
	regs, err := t.client.ListRegisters(0, includeFp)
D
Derek Parker 已提交
975 976 977 978 979 980
	if err != nil {
		return err
	}
	fmt.Println(regs)
	return nil
}
981

982
func stackCommand(t *Term, ctx callContext, args string) error {
983 984 985 986
	depth, full, err := parseStackArgs(args)
	if err != nil {
		return err
	}
987 988 989 990
	if ctx.Prefix == onPrefix {
		ctx.Breakpoint.Stacktrace = depth
		return nil
	}
991 992 993 994 995
	var cfg *api.LoadConfig
	if full {
		cfg = &ShortLoadConfig
	}
	stack, err := t.client.Stacktrace(ctx.Scope.GoroutineID, depth, cfg)
996 997 998 999 1000 1001
	if err != nil {
		return err
	}
	printStack(stack, "")
	return nil
}
A
aarzilli 已提交
1002

1003
func parseStackArgs(argstr string) (int, bool, error) {
1004 1005 1006 1007
	var (
		depth = 10
		full  = false
	)
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
	if argstr != "" {
		args := strings.Split(argstr, " ")
		for i := range args {
			if args[i] == "-full" {
				full = true
			} else {
				n, err := strconv.Atoi(args[i])
				if err != nil {
					return 0, false, fmt.Errorf("depth must be a number")
				}
				depth = n
1019
			}
A
aarzilli 已提交
1020 1021
		}
	}
1022
	return depth, full, nil
A
aarzilli 已提交
1023 1024
}

1025 1026
func listCommand(t *Term, ctx callContext, args string) error {
	if ctx.Prefix == scopePrefix {
1027
		locs, err := t.client.Stacktrace(ctx.Scope.GoroutineID, ctx.Scope.Frame, nil)
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
		if err != nil {
			return err
		}
		if ctx.Scope.Frame >= len(locs) {
			return fmt.Errorf("Frame %d does not exist in goroutine %d", ctx.Scope.Frame, ctx.Scope.GoroutineID)
		}
		loc := locs[ctx.Scope.Frame]
		return printfile(t, loc.File, loc.Line, true)
	}

1038
	if len(args) == 0 {
1039
		state, err := t.client.GetState()
1040 1041 1042
		if err != nil {
			return err
		}
1043
		printcontext(t, state)
1044
		printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
1045 1046 1047
		return nil
	}

D
Derek Parker 已提交
1048
	locs, err := t.client.FindLocation(api.EvalScope{GoroutineID: -1, Frame: 0}, args)
1049 1050 1051 1052
	if err != nil {
		return err
	}
	if len(locs) > 1 {
1053
		return debugger.AmbiguousLocationError{Location: args, CandidatesLocation: locs}
1054
	}
1055
	printfile(t, locs[0].File, locs[0].Line, false)
1056 1057 1058
	return nil
}

1059
func (c *Commands) sourceCommand(t *Term, ctx callContext, args string) error {
1060
	if len(args) == 0 {
1061 1062 1063
		return fmt.Errorf("wrong number of arguments: source <filename>")
	}

D
Derek Parker 已提交
1064
	return c.executeFile(t, args)
1065 1066
}

A
aarzilli 已提交
1067 1068
var disasmUsageError = errors.New("wrong number of arguments: disassemble [-a <start> <end>] [-l <locspec>]")

1069
func disassCommand(t *Term, ctx callContext, args string) error {
A
aarzilli 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
	var cmd, rest string

	if args != "" {
		argv := strings.SplitN(args, " ", 2)
		if len(argv) != 2 {
			return disasmUsageError
		}
		cmd = argv[0]
		rest = argv[1]
	}

	var disasm api.AsmInstructions
	var disasmErr error

	switch cmd {
	case "":
1086
		locs, err := t.client.FindLocation(ctx.Scope, "+0")
A
aarzilli 已提交
1087 1088 1089
		if err != nil {
			return err
		}
1090
		disasm, disasmErr = t.client.DisassemblePC(ctx.Scope, locs[0].PC, api.IntelFlavour)
A
aarzilli 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
	case "-a":
		v := strings.SplitN(rest, " ", 2)
		if len(v) != 2 {
			return disasmUsageError
		}
		startpc, err := strconv.ParseInt(v[0], 0, 64)
		if err != nil {
			return fmt.Errorf("wrong argument: %s is not a number", v[0])
		}
		endpc, err := strconv.ParseInt(v[1], 0, 64)
		if err != nil {
			return fmt.Errorf("wrong argument: %s is not a number", v[1])
		}
1104
		disasm, disasmErr = t.client.DisassembleRange(ctx.Scope, uint64(startpc), uint64(endpc), api.IntelFlavour)
A
aarzilli 已提交
1105
	case "-l":
1106
		locs, err := t.client.FindLocation(ctx.Scope, rest)
A
aarzilli 已提交
1107 1108 1109 1110 1111 1112
		if err != nil {
			return err
		}
		if len(locs) != 1 {
			return errors.New("expression specifies multiple locations")
		}
1113
		disasm, disasmErr = t.client.DisassemblePC(ctx.Scope, locs[0].PC, api.IntelFlavour)
A
aarzilli 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
	default:
		return disasmUsageError
	}

	if disasmErr != nil {
		return disasmErr
	}

	fmt.Printf("printing\n")
	DisasmPrint(disasm, os.Stdout)

	return nil
}

1128
func digits(n int) int {
1129 1130 1131
	if n <= 0 {
		return 1
	}
1132 1133 1134 1135
	return int(math.Floor(math.Log10(float64(n)))) + 1
}

func printStack(stack []api.Stackframe, ind string) {
1136 1137 1138
	if len(stack) == 0 {
		return
	}
1139 1140
	d := digits(len(stack) - 1)
	fmtstr := "%s%" + strconv.Itoa(d) + "d  0x%016x in %s\n"
1141
	s := ind + strings.Repeat(" ", d+2+len(ind))
1142

A
aarzilli 已提交
1143 1144 1145 1146 1147
	for i := range stack {
		name := "(nil)"
		if stack[i].Function != nil {
			name = stack[i].Function.Name
		}
1148
		fmt.Printf(fmtstr, ind, i, stack[i].PC, name)
1149
		fmt.Printf("%sat %s:%d\n", s, ShortenFilePath(stack[i].File), stack[i].Line)
1150 1151

		for j := range stack[i].Arguments {
1152
			fmt.Printf("%s    %s = %s\n", s, stack[i].Arguments[j].Name, stack[i].Arguments[j].SinglelineString())
1153 1154
		}
		for j := range stack[i].Locals {
1155
			fmt.Printf("%s    %s = %s\n", s, stack[i].Locals[j].Name, stack[i].Locals[j].SinglelineString())
1156
		}
A
aarzilli 已提交
1157 1158 1159
	}
}

1160
func printcontext(t *Term, state *api.DebuggerState) error {
1161 1162 1163 1164 1165 1166 1167 1168 1169
	for i := range state.Threads {
		if (state.CurrentThread != nil) && (state.Threads[i].ID == state.CurrentThread.ID) {
			continue
		}
		if state.Threads[i].Breakpoint != nil {
			printcontextThread(t, state.Threads[i])
		}
	}

D
Dan Mace 已提交
1170 1171 1172 1173 1174 1175
	if state.CurrentThread == nil {
		fmt.Println("No current thread available")
		return nil
	}
	if len(state.CurrentThread.File) == 0 {
		fmt.Printf("Stopped at: 0x%x\n", state.CurrentThread.PC)
1176
		t.Println("=>", "no source available")
D
Dan Mace 已提交
1177 1178
		return nil
	}
1179 1180 1181 1182 1183

	printcontextThread(t, state.CurrentThread)

	return nil
}
1184

1185 1186 1187 1188
func printcontextThread(t *Term, th *api.Thread) {
	fn := th.Function

	if th.Breakpoint == nil {
A
aarzilli 已提交
1189
		fmt.Printf("> %s() %s:%d (PC: %#v)\n", fn.Name, ShortenFilePath(th.File), th.Line, th.PC)
1190 1191 1192 1193
		return
	}

	args := ""
1194
	if th.BreakpointInfo != nil && th.Breakpoint.LoadArgs != nil && *th.Breakpoint.LoadArgs == ShortLoadConfig {
1195
		var arg []string
1196
		for _, ar := range th.BreakpointInfo.Arguments {
1197
			arg = append(arg, ar.SinglelineString())
D
Derek Parker 已提交
1198
		}
1199 1200 1201
		args = strings.Join(arg, ", ")
	}

1202 1203 1204 1205 1206
	bpname := ""
	if th.Breakpoint.Name != "" {
		bpname = fmt.Sprintf("[%s] ", th.Breakpoint.Name)
	}

1207
	if hitCount, ok := th.Breakpoint.HitCount[strconv.Itoa(th.GoroutineID)]; ok {
1208 1209
		fmt.Printf("> %s%s(%s) %s:%d (hits goroutine(%d):%d total:%d) (PC: %#v)\n",
			bpname,
1210 1211 1212 1213 1214 1215
			fn.Name,
			args,
			ShortenFilePath(th.File),
			th.Line,
			th.GoroutineID,
			hitCount,
A
aarzilli 已提交
1216 1217
			th.Breakpoint.TotalHitCount,
			th.PC)
D
Derek Parker 已提交
1218
	} else {
1219 1220
		fmt.Printf("> %s%s(%s) %s:%d (hits total:%d) (PC: %#v)\n",
			bpname,
1221 1222 1223 1224
			fn.Name,
			args,
			ShortenFilePath(th.File),
			th.Line,
A
aarzilli 已提交
1225 1226
			th.Breakpoint.TotalHitCount,
			th.PC)
D
Dan Mace 已提交
1227 1228
	}

1229
	if th.BreakpointInfo != nil {
1230
		bp := th.Breakpoint
1231
		bpi := th.BreakpointInfo
A
aarzilli 已提交
1232 1233

		if bpi.Goroutine != nil {
1234
			writeGoroutineLong(os.Stdout, bpi.Goroutine, "\t")
A
aarzilli 已提交
1235 1236
		}

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
		for _, v := range bpi.Variables {
			fmt.Printf("\t%s: %s\n", v.Name, v.MultilineString("\t"))
		}

		for _, v := range bpi.Locals {
			if *bp.LoadLocals == LongLoadConfig {
				fmt.Printf("\t%s: %s\n", v.Name, v.MultilineString("\t"))
			} else {
				fmt.Printf("\t%s: %s\n", v.Name, v.SinglelineString())
			}
		}

		if bp.LoadArgs != nil && *bp.LoadArgs == LongLoadConfig {
			for _, v := range bpi.Arguments {
				fmt.Printf("\t%s: %s\n", v.Name, v.MultilineString("\t"))
1252
			}
A
aarzilli 已提交
1253 1254 1255 1256 1257 1258 1259
		}

		if bpi.Stacktrace != nil {
			fmt.Printf("\tStack:\n")
			printStack(bpi.Stacktrace, "\t\t")
		}
	}
1260 1261
}

1262
func printfile(t *Term, filename string, line int, showArrow bool) error {
1263
	file, err := os.Open(t.substitutePath(filename))
D
Dan Mace 已提交
1264 1265 1266 1267 1268
	if err != nil {
		return err
	}
	defer file.Close()

1269
	buf := bufio.NewScanner(file)
1270
	l := line
D
Dan Mace 已提交
1271
	for i := 1; i < l-5; i++ {
1272 1273
		if !buf.Scan() {
			return nil
D
Dan Mace 已提交
1274 1275 1276
		}
	}

1277 1278 1279 1280 1281 1282
	s := l - 5
	if s < 1 {
		s = 1
	}

	for i := s; i <= l+5; i++ {
1283 1284
		if !buf.Scan() {
			return nil
D
Dan Mace 已提交
1285 1286
		}

1287
		var prefix string
1288
		if showArrow {
1289
			prefix = "  "
1290
			if i == l {
1291
				prefix = "=>"
1292
			}
D
Dan Mace 已提交
1293 1294
		}

1295 1296
		prefix = fmt.Sprintf("%s%4d:\t", prefix, i)
		t.Println(prefix, buf.Text())
D
Dan Mace 已提交
1297 1298 1299
	}
	return nil
}
D
Derek Parker 已提交
1300

D
Derek Parker 已提交
1301 1302
// ExitRequestError is returned when the user
// exits Delve.
D
Derek Parker 已提交
1303 1304 1305 1306 1307 1308
type ExitRequestError struct{}

func (ere ExitRequestError) Error() string {
	return ""
}

1309
func exitCommand(t *Term, ctx callContext, args string) error {
D
Derek Parker 已提交
1310 1311
	return ExitRequestError{}
}
1312

H
Hubert Krauze 已提交
1313
func getBreakpointByIDOrName(t *Term, arg string) (*api.Breakpoint, error) {
1314
	if id, err := strconv.Atoi(arg); err == nil {
H
Hubert Krauze 已提交
1315
		return t.client.GetBreakpoint(id)
1316
	}
H
Hubert Krauze 已提交
1317
	return t.client.GetBreakpointByName(arg)
1318 1319
}

1320
func (c *Commands) onCmd(t *Term, ctx callContext, argstr string) error {
1321 1322 1323
	args := strings.SplitN(argstr, " ", 3)

	if len(args) < 2 {
1324 1325 1326 1327 1328
		return errors.New("not enough arguments")
	}

	if len(args) < 3 {
		args = append(args, "")
1329 1330 1331 1332 1333 1334 1335
	}

	bp, err := getBreakpointByIDOrName(t, args[0])
	if err != nil {
		return err
	}

1336 1337 1338 1339 1340
	ctx.Prefix = onPrefix
	ctx.Breakpoint = bp
	err = c.CallWithContext(args[1], args[2], t, ctx)
	if err != nil {
		return err
1341
	}
1342
	return t.client.AmendBreakpoint(ctx.Breakpoint)
1343 1344
}

1345
func conditionCmd(t *Term, ctx callContext, argstr string) error {
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
	args := strings.SplitN(argstr, " ", 2)

	if len(args) < 2 {
		return fmt.Errorf("not enough arguments")
	}

	bp, err := getBreakpointByIDOrName(t, args[0])
	if err != nil {
		return err
	}
	bp.Cond = args[1]

	return t.client.AmendBreakpoint(bp)
}

D
Derek Parker 已提交
1361 1362
// ShortenFilePath take a full file path and attempts to shorten
// it by replacing the current directory to './'.
1363
func ShortenFilePath(fullPath string) string {
1364 1365 1366
	workingDir, _ := os.Getwd()
	return strings.Replace(fullPath, workingDir, ".", 1)
}
1367

D
Derek Parker 已提交
1368
func (c *Commands) executeFile(t *Term, name string) error {
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
	fh, err := os.Open(name)
	if err != nil {
		return err
	}
	defer fh.Close()

	scanner := bufio.NewScanner(fh)
	lineno := 0
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		lineno++

		if line == "" || line[0] == '#' {
			continue
		}

		cmdstr, args := parseCommand(line)

1387
		if err := c.Call(cmdstr, args, t); err != nil {
1388 1389 1390 1391 1392 1393
			fmt.Printf("%s:%d: %v\n", name, lineno, err)
		}
	}

	return scanner.Err()
}
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

func formatBreakpointName(bp *api.Breakpoint, upcase bool) string {
	thing := "breakpoint"
	if bp.Tracepoint {
		thing = "tracepoint"
	}
	if upcase {
		thing = strings.Title(thing)
	}
	id := bp.Name
	if id == "" {
		id = strconv.Itoa(bp.ID)
	}
	return fmt.Sprintf("%s %s", thing, id)
}

func formatBreakpointLocation(bp *api.Breakpoint) string {
	p := ShortenFilePath(bp.File)
	if bp.FunctionName != "" {
		return fmt.Sprintf("%#v for %s() %s:%d", bp.Addr, bp.FunctionName, p, bp.Line)
	}
H
Hubert Krauze 已提交
1415
	return fmt.Sprintf("%#v for %s:%d", bp.Addr, p, bp.Line)
1416
}