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

import (
	"bufio"
	"fmt"
8
	"math"
D
Dan Mace 已提交
9 10 11 12 13
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
D
Derek Parker 已提交
14
	"text/tabwriter"
D
Dan Mace 已提交
15 16 17

	"github.com/derekparker/delve/service"
	"github.com/derekparker/delve/service/api"
18
	"github.com/derekparker/delve/service/debugger"
D
Dan Mace 已提交
19 20
)

21 22
type cmdfunc func(t *Term, args ...string) error
type scopedCmdfunc func(t *Term, scope api.EvalScope, args ...string) error
23

24 25
type filteringFunc func(t *Term, filter string) ([]string, error)
type scopedFilteringFunc func(t *Term, scope api.EvalScope, filter string) ([]string, error)
D
Dan Mace 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

type command struct {
	aliases []string
	helpMsg string
	cmdFn   cmdfunc
}

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

type Commands struct {
	cmds    []command
	lastCmd cmdfunc
	client  service.Client
}

// Returns a Commands struct with default commands defined.
func DebugCommands(client service.Client) *Commands {
	c := &Commands{client: client}

	c.cmds = []command{
		{aliases: []string{"help"}, cmdFn: c.help, helpMsg: "Prints the help message."},
55
		{aliases: []string{"break", "b"}, cmdFn: breakpoint, helpMsg: "break <linespec> [-stack <n>|-goroutine|<variable name>]*"},
D
Derek Parker 已提交
56
		{aliases: []string{"trace", "t"}, cmdFn: tracepoint, helpMsg: "Set tracepoint, takes the same arguments as break."},
D
Derek Parker 已提交
57
		{aliases: []string{"restart", "r"}, cmdFn: restart, helpMsg: "Restart process."},
D
Dan Mace 已提交
58 59 60 61
		{aliases: []string{"continue", "c"}, cmdFn: cont, helpMsg: "Run until breakpoint or program termination."},
		{aliases: []string{"step", "si"}, cmdFn: step, helpMsg: "Single step through program."},
		{aliases: []string{"next", "n"}, cmdFn: next, helpMsg: "Step over to next source line."},
		{aliases: []string{"threads"}, cmdFn: threads, helpMsg: "Print out info for every traced thread."},
D
Derek Parker 已提交
62
		{aliases: []string{"thread", "tr"}, cmdFn: thread, helpMsg: "Switch to the specified thread."},
D
Dan Mace 已提交
63 64 65
		{aliases: []string{"clear"}, cmdFn: clear, helpMsg: "Deletes breakpoint."},
		{aliases: []string{"clearall"}, cmdFn: clearAll, helpMsg: "Deletes all breakpoints."},
		{aliases: []string{"goroutines"}, cmdFn: goroutines, helpMsg: "Print out info for every goroutine."},
66
		{aliases: []string{"goroutine"}, cmdFn: goroutine, helpMsg: "Sets current goroutine."},
D
Dan Mace 已提交
67
		{aliases: []string{"breakpoints", "bp"}, cmdFn: breakpoints, helpMsg: "Print out info for active breakpoints."},
68
		{aliases: []string{"print", "p"}, cmdFn: g0f0(printVar), helpMsg: "Evaluate a variable."},
69
		{aliases: []string{"set"}, cmdFn: g0f0(setVar), helpMsg: "Changes the value of a variable."},
D
Derek Parker 已提交
70 71
		{aliases: []string{"sources"}, cmdFn: filterSortAndOutput(sources), helpMsg: "Print list of source files, optionally filtered by a regexp."},
		{aliases: []string{"funcs"}, cmdFn: filterSortAndOutput(funcs), helpMsg: "Print list of functions, optionally filtered by a regexp."},
72 73
		{aliases: []string{"args"}, cmdFn: filterSortAndOutput(g0f0filter(args)), helpMsg: "Print function arguments, optionally filtered by a regexp."},
		{aliases: []string{"locals"}, cmdFn: filterSortAndOutput(g0f0filter(locals)), helpMsg: "Print function locals, optionally filtered by a regexp."},
D
Derek Parker 已提交
74 75
		{aliases: []string{"vars"}, cmdFn: filterSortAndOutput(vars), helpMsg: "Print package variables, optionally filtered by a regexp."},
		{aliases: []string{"regs"}, cmdFn: regs, helpMsg: "Print contents of CPU registers."},
D
Derek Parker 已提交
76
		{aliases: []string{"exit", "quit", "q"}, cmdFn: exitCommand, helpMsg: "Exit the debugger."},
77
		{aliases: []string{"list", "ls"}, cmdFn: listCommand, helpMsg: "list <linespec>.  Show source around current point or provided linespec."},
78
		{aliases: []string{"stack", "bt"}, cmdFn: stackCommand, helpMsg: "stack [<depth>] [-full]. Prints stack."},
79
		{aliases: []string{"frame"}, cmdFn: frame, helpMsg: "Sets current stack frame (0 is the top of the stack)"},
D
Dan Mace 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
	}

	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 已提交
99
// If it cannot find the command it will default to noCmdAvailable().
D
Dan Mace 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
// If the command is an empty string it will replay the last command.
func (c *Commands) Find(cmdstr string) cmdfunc {
	// 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) {
			c.lastCmd = v.cmdFn
			return v.cmdFn
		}
	}

	return noCmdAvailable
}

120 121 122 123 124 125 126 127 128
// 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...)
		}
	}
}

D
Dan Mace 已提交
129
func CommandFunc(fn func() error) cmdfunc {
130
	return func(t *Term, args ...string) error {
D
Dan Mace 已提交
131 132 133 134
		return fn()
	}
}

135
func noCmdAvailable(t *Term, args ...string) error {
D
Derek Parker 已提交
136
	return fmt.Errorf("command not available")
D
Dan Mace 已提交
137 138
}

139
func nullCommand(t *Term, args ...string) error {
D
Dan Mace 已提交
140 141 142
	return nil
}

143
func (c *Commands) help(t *Term, args ...string) error {
D
Dan Mace 已提交
144
	fmt.Println("The following commands are available:")
D
Derek Parker 已提交
145 146
	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 8, 0, '-', 0)
D
Dan Mace 已提交
147
	for _, cmd := range c.cmds {
D
Derek Parker 已提交
148 149 150 151 152
		if len(cmd.aliases) > 1 {
			fmt.Fprintf(w, "    %s (alias: %s) \t %s\n", cmd.aliases[0], strings.Join(cmd.aliases[1:], " | "), cmd.helpMsg)
		} else {
			fmt.Fprintf(w, "    %s \t %s\n", cmd.aliases[0], cmd.helpMsg)
		}
D
Dan Mace 已提交
153
	}
D
Derek Parker 已提交
154
	return w.Flush()
D
Dan Mace 已提交
155 156
}

I
Ilia Choly 已提交
157
type byThreadID []*api.Thread
I
Ilia Choly 已提交
158

I
Ilia Choly 已提交
159 160 161
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 已提交
162

163 164
func threads(t *Term, args ...string) error {
	threads, err := t.client.ListThreads()
D
Dan Mace 已提交
165 166 167
	if err != nil {
		return err
	}
168
	state, err := t.client.GetState()
D
Dan Mace 已提交
169 170 171
	if err != nil {
		return err
	}
I
Ilia Choly 已提交
172
	sort.Sort(byThreadID(threads))
D
Dan Mace 已提交
173 174 175 176 177 178 179
	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",
180
				prefix, th.ID, th.PC, shortenFilePath(th.File),
D
Dan Mace 已提交
181 182
				th.Line, th.Function.Name)
		} else {
183
			fmt.Printf("%sThread %s\n", prefix, formatThread(th))
D
Dan Mace 已提交
184 185 186 187 188
		}
	}
	return nil
}

189
func thread(t *Term, args ...string) error {
190 191 192
	if len(args) == 0 {
		return fmt.Errorf("you must specify a thread")
	}
D
Dan Mace 已提交
193 194 195 196
	tid, err := strconv.Atoi(args[0])
	if err != nil {
		return err
	}
197
	oldState, err := t.client.GetState()
D
Dan Mace 已提交
198 199 200
	if err != nil {
		return err
	}
201
	newState, err := t.client.SwitchThread(tid)
D
Dan Mace 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
	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 已提交
218 219 220 221 222 223
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 }

224 225
func goroutines(t *Term, args ...string) error {
	state, err := t.client.GetState()
226 227 228
	if err != nil {
		return err
	}
229
	gs, err := t.client.ListGoroutines()
D
Dan Mace 已提交
230 231 232
	if err != nil {
		return err
	}
I
Ilia Choly 已提交
233
	sort.Sort(byGoroutineID(gs))
D
Dan Mace 已提交
234 235
	fmt.Printf("[%d goroutines]\n", len(gs))
	for _, g := range gs {
236 237 238 239 240 241 242 243 244
		prefix := "  "
		if g.ID == state.SelectedGoroutine.ID {
			prefix = "* "
		}
		fmt.Printf("%sGoroutine %s\n", prefix, formatGoroutine(g))
	}
	return nil
}

245
func goroutine(t *Term, args ...string) error {
246 247
	switch len(args) {
	case 0:
248
		return printscope(t)
249 250 251 252 253 254 255

	case 1:
		gid, err := strconv.Atoi(args[0])
		if err != nil {
			return err
		}

256
		oldState, err := t.client.GetState()
257 258 259
		if err != nil {
			return err
		}
260
		newState, err := t.client.SwitchGoroutine(gid)
261 262 263 264 265 266 267 268
		if err != nil {
			return err
		}

		fmt.Printf("Switched from %d to %d (thread %d)\n", oldState.SelectedGoroutine.ID, gid, newState.CurrentThread.ID)
		return nil

	default:
269
		return scopePrefix(t, "goroutine", args...)
270 271 272
	}
}

273 274
func frame(t *Term, args ...string) error {
	return scopePrefix(t, "frame", args...)
275 276
}

277
func scopePrefix(t *Term, cmdname string, pargs ...string) error {
278 279 280 281 282 283 284 285
	fullargs := make([]string, 0, len(pargs)+1)
	fullargs = append(fullargs, cmdname)
	fullargs = append(fullargs, pargs...)

	scope := api.EvalScope{-1, 0}
	lastcmd := ""

	callFilterSortAndOutput := func(fn scopedFilteringFunc, fnargs []string) error {
286 287
		outfn := filterSortAndOutput(func(t *Term, filter string) ([]string, error) {
			return fn(t, scope, filter)
288
		})
289
		return outfn(t, fnargs...)
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
	}

	for i := 0; i < len(fullargs); i++ {
		lastcmd = fullargs[i]
		switch fullargs[i] {
		case "goroutine":
			if i+1 >= len(fullargs) {
				return fmt.Errorf("goroutine command needs an argument")
			}
			n, err := strconv.Atoi(fullargs[i+1])
			if err != nil {
				return fmt.Errorf("invalid argument to goroutine, expected integer")
			}
			scope.GoroutineID = int(n)
			i++
		case "frame":
			if i+1 >= len(fullargs) {
				return fmt.Errorf("frame command needs an argument")
			}
			n, err := strconv.Atoi(fullargs[i+1])
			if err != nil {
				return fmt.Errorf("invalid argument to frame, expected integer")
			}
			scope.Frame = int(n)
			i++
315 316
		case "list", "ls":
			frame, gid := scope.Frame, scope.GoroutineID
317
			locs, err := t.client.Stacktrace(gid, frame, false)
318 319 320 321 322 323 324
			if err != nil {
				return err
			}
			if frame >= len(locs) {
				return fmt.Errorf("Frame %d does not exist in goroutine %d", frame, gid)
			}
			loc := locs[frame]
325
			return printfile(t, loc.File, loc.Line, true)
326 327 328 329 330
		case "stack", "bt":
			depth, full, err := parseStackArgs(fullargs[i+1:])
			if err != nil {
				return err
			}
331
			stack, err := t.client.Stacktrace(scope.GoroutineID, depth, full)
332 333 334 335 336
			if err != nil {
				return err
			}
			printStack(stack, "")
			return nil
337 338 339 340 341
		case "locals":
			return callFilterSortAndOutput(locals, fullargs[i+1:])
		case "args":
			return callFilterSortAndOutput(args, fullargs[i+1:])
		case "print", "p":
342
			return printVar(t, scope, fullargs[i+1:]...)
343 344 345 346 347 348 349 350
		default:
			return fmt.Errorf("unknown command %s", fullargs[i])
		}
	}

	return fmt.Errorf("no command passed to %s", lastcmd)
}

351 352
func printscope(t *Term) error {
	state, err := t.client.GetState()
353 354
	if err != nil {
		return err
D
Dan Mace 已提交
355
	}
356 357

	fmt.Printf("Thread %s\nGoroutine %s\n", formatThread(state.CurrentThread), formatGoroutine(state.SelectedGoroutine))
D
Dan Mace 已提交
358 359 360
	return nil
}

361 362 363 364 365 366 367
func formatThread(th *api.Thread) string {
	if th == nil {
		return "<nil>"
	}
	return fmt.Sprintf("%d at %s:%d", th.ID, shortenFilePath(th.File), th.Line)
}

A
aarzilli 已提交
368
func formatGoroutine(g *api.Goroutine) string {
369 370 371
	if g == nil {
		return "<nil>"
	}
A
aarzilli 已提交
372 373 374 375
	fname := ""
	if g.Function != nil {
		fname = g.Function.Name
	}
376
	return fmt.Sprintf("%d - %s:%d %s (%#v)", g.ID, shortenFilePath(g.File), g.Line, fname, g.PC)
A
aarzilli 已提交
377 378
}

379 380
func restart(t *Term, args ...string) error {
	if err := t.client.Restart(); err != nil {
D
Derek Parker 已提交
381 382
		return err
	}
383
	fmt.Println("Process restarted with PID", t.client.ProcessPid())
D
Derek Parker 已提交
384 385 386
	return nil
}

387 388
func cont(t *Term, args ...string) error {
	stateChan := t.client.Continue()
D
Derek Parker 已提交
389
	for state := range stateChan {
A
aarzilli 已提交
390 391 392
		if state.Err != nil {
			return state.Err
		}
393
		printcontext(t, state)
D
Dan Mace 已提交
394 395 396 397
	}
	return nil
}

398 399
func step(t *Term, args ...string) error {
	state, err := t.client.Step()
D
Dan Mace 已提交
400 401 402
	if err != nil {
		return err
	}
403
	printcontext(t, state)
D
Dan Mace 已提交
404 405 406
	return nil
}

407 408
func next(t *Term, args ...string) error {
	state, err := t.client.Next()
D
Dan Mace 已提交
409 410 411
	if err != nil {
		return err
	}
412
	printcontext(t, state)
D
Dan Mace 已提交
413 414 415
	return nil
}

416
func clear(t *Term, args ...string) error {
D
Dan Mace 已提交
417
	if len(args) == 0 {
D
Derek Parker 已提交
418
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
419 420 421 422 423
	}
	id, err := strconv.Atoi(args[0])
	if err != nil {
		return err
	}
424
	bp, err := t.client.ClearBreakpoint(id)
D
Dan Mace 已提交
425 426 427
	if err != nil {
		return err
	}
428
	fmt.Printf("Breakpoint %d cleared at %#v for %s %s:%d\n", bp.ID, bp.Addr, bp.FunctionName, shortenFilePath(bp.File), bp.Line)
D
Dan Mace 已提交
429 430 431
	return nil
}

432 433
func clearAll(t *Term, args ...string) error {
	breakPoints, err := t.client.ListBreakpoints()
D
Dan Mace 已提交
434 435 436 437
	if err != nil {
		return err
	}
	for _, bp := range breakPoints {
438
		_, err := t.client.ClearBreakpoint(bp.ID)
D
Dan Mace 已提交
439
		if err != nil {
440
			fmt.Printf("Couldn't delete breakpoint %d at %#v %s:%d: %s\n", bp.ID, bp.Addr, shortenFilePath(bp.File), bp.Line, err)
D
Dan Mace 已提交
441
		}
442
		fmt.Printf("Breakpoint %d cleared at %#v for %s %s:%d\n", bp.ID, bp.Addr, bp.FunctionName, shortenFilePath(bp.File), bp.Line)
D
Dan Mace 已提交
443 444 445 446
	}
	return nil
}

D
Derek Parker 已提交
447
type ById []*api.Breakpoint
D
Dan Mace 已提交
448 449 450 451 452

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 }

453 454
func breakpoints(t *Term, args ...string) error {
	breakPoints, err := t.client.ListBreakpoints()
D
Dan Mace 已提交
455 456 457 458 459
	if err != nil {
		return err
	}
	sort.Sort(ById(breakPoints))
	for _, bp := range breakPoints {
A
aarzilli 已提交
460 461 462 463
		thing := "Breakpoint"
		if bp.Tracepoint {
			thing = "Tracepoint"
		}
464
		fmt.Printf("%s %d at %#v %s:%d\n", thing, bp.ID, bp.Addr, shortenFilePath(bp.File), bp.Line)
A
aarzilli 已提交
465 466 467 468 469 470 471 472 473

		var attrs []string
		if bp.Stacktrace > 0 {
			attrs = append(attrs, "-stack")
			attrs = append(attrs, strconv.Itoa(bp.Stacktrace))
		}
		if bp.Goroutine {
			attrs = append(attrs, "-goroutine")
		}
D
Derek Parker 已提交
474 475
		for i := range bp.Variables {
			attrs = append(attrs, bp.Variables[i])
A
aarzilli 已提交
476 477 478 479
		}
		if len(attrs) > 0 {
			fmt.Printf("\t%s\n", strings.Join(attrs, " "))
		}
D
Dan Mace 已提交
480 481 482 483
	}
	return nil
}

484
func setBreakpoint(t *Term, tracepoint bool, args ...string) error {
A
aarzilli 已提交
485 486
	if len(args) < 1 {
		return fmt.Errorf("address required, specify either a function name or <file:line>")
D
Dan Mace 已提交
487
	}
D
Derek Parker 已提交
488
	requestedBp := &api.Breakpoint{}
D
Dan Mace 已提交
489

A
aarzilli 已提交
490 491 492 493 494 495 496 497 498 499 500 501
	for i := 1; i < len(args); i++ {
		switch args[i] {
		case "-stack":
			i++
			n, err := strconv.Atoi(args[i])
			if err != nil {
				return fmt.Errorf("argument of -stack must be a number")
			}
			requestedBp.Stacktrace = n
		case "-goroutine":
			requestedBp.Goroutine = true
		default:
D
Derek Parker 已提交
502
			requestedBp.Variables = append(requestedBp.Variables, args[i])
A
aarzilli 已提交
503 504 505 506
		}
	}

	requestedBp.Tracepoint = tracepoint
507
	locs, err := t.client.FindLocation(api.EvalScope{-1, 0}, args[0])
D
Dan Mace 已提交
508 509 510
	if err != nil {
		return err
	}
A
aarzilli 已提交
511 512 513 514
	thing := "Breakpoint"
	if tracepoint {
		thing = "Tracepoint"
	}
515 516 517
	for _, loc := range locs {
		requestedBp.Addr = loc.PC

518
		bp, err := t.client.CreateBreakpoint(requestedBp)
519 520 521 522
		if err != nil {
			return err
		}

523
		fmt.Printf("%s %d set at %#v for %s %s:%d\n", thing, bp.ID, bp.Addr, bp.FunctionName, shortenFilePath(bp.File), bp.Line)
524
	}
D
Dan Mace 已提交
525 526 527
	return nil
}

528 529
func breakpoint(t *Term, args ...string) error {
	return setBreakpoint(t, false, args...)
A
aarzilli 已提交
530 531
}

532 533
func tracepoint(t *Term, args ...string) error {
	return setBreakpoint(t, true, args...)
A
aarzilli 已提交
534 535
}

536
func g0f0(fn scopedCmdfunc) cmdfunc {
537 538
	return func(t *Term, args ...string) error {
		return fn(t, api.EvalScope{-1, 0}, args...)
539 540 541 542
	}
}

func g0f0filter(fn scopedFilteringFunc) filteringFunc {
543 544
	return func(t *Term, filter string) ([]string, error) {
		return fn(t, api.EvalScope{-1, 0}, filter)
545 546 547
	}
}

548
func printVar(t *Term, scope api.EvalScope, args ...string) error {
D
Dan Mace 已提交
549
	if len(args) == 0 {
D
Derek Parker 已提交
550
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
551
	}
552
	val, err := t.client.EvalVariable(scope, args[0])
D
Dan Mace 已提交
553 554 555 556 557 558 559
	if err != nil {
		return err
	}
	fmt.Println(val.Value)
	return nil
}

560
func setVar(t *Term, scope api.EvalScope, args ...string) error {
561 562 563 564
	if len(args) != 2 {
		return fmt.Errorf("wrong number of arguments")
	}

565
	return t.client.SetVariable(scope, args[0], args[1])
566 567
}

D
Derek Parker 已提交
568 569 570 571 572 573
func filterVariables(vars []api.Variable, filter string) []string {
	reg, err := regexp.Compile(filter)
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		return nil
	}
D
Dan Mace 已提交
574 575
	data := make([]string, 0, len(vars))
	for _, v := range vars {
D
Derek Parker 已提交
576
		if reg == nil || reg.Match([]byte(v.Name)) {
D
Dan Mace 已提交
577 578 579 580 581 582
			data = append(data, fmt.Sprintf("%s = %s", v.Name, v.Value))
		}
	}
	return data
}

583 584
func sources(t *Term, filter string) ([]string, error) {
	return t.client.ListSources(filter)
D
Derek Parker 已提交
585
}
D
Dan Mace 已提交
586

587 588
func funcs(t *Term, filter string) ([]string, error) {
	return t.client.ListFunctions(filter)
D
Derek Parker 已提交
589
}
D
Dan Mace 已提交
590

591 592
func args(t *Term, scope api.EvalScope, filter string) ([]string, error) {
	vars, err := t.client.ListFunctionArgs(scope)
D
Derek Parker 已提交
593 594 595 596 597
	if err != nil {
		return nil, err
	}
	return filterVariables(vars, filter), nil
}
D
Dan Mace 已提交
598

599 600
func locals(t *Term, scope api.EvalScope, filter string) ([]string, error) {
	locals, err := t.client.ListLocalVariables(scope)
D
Derek Parker 已提交
601 602 603 604 605
	if err != nil {
		return nil, err
	}
	return filterVariables(locals, filter), nil
}
D
Dan Mace 已提交
606

607 608
func vars(t *Term, filter string) ([]string, error) {
	vars, err := t.client.ListPackageVariables(filter)
D
Derek Parker 已提交
609 610 611 612 613
	if err != nil {
		return nil, err
	}
	return filterVariables(vars, filter), nil
}
D
Dan Mace 已提交
614

615 616
func regs(t *Term, args ...string) error {
	regs, err := t.client.ListRegisters()
D
Derek Parker 已提交
617 618 619 620 621 622
	if err != nil {
		return err
	}
	fmt.Println(regs)
	return nil
}
623

624
func filterSortAndOutput(fn filteringFunc) cmdfunc {
625
	return func(t *Term, args ...string) error {
D
Derek Parker 已提交
626 627 628 629 630 631
		var filter string
		if len(args) == 1 {
			if _, err := regexp.Compile(args[0]); err != nil {
				return fmt.Errorf("invalid filter argument: %s", err.Error())
			}
			filter = args[0]
D
Dan Mace 已提交
632
		}
633
		data, err := fn(t, filter)
D
Dan Mace 已提交
634 635 636
		if err != nil {
			return err
		}
D
Derek Parker 已提交
637 638 639
		sort.Sort(sort.StringSlice(data))
		for _, d := range data {
			fmt.Println(d)
D
Dan Mace 已提交
640
		}
D
Derek Parker 已提交
641
		return nil
D
Dan Mace 已提交
642 643 644
	}
}

645
func stackCommand(t *Term, args ...string) error {
646 647 648 649 650 651 652 653
	var (
		err         error
		goroutineid = -1
	)
	depth, full, err := parseStackArgs(args)
	if err != nil {
		return err
	}
654
	stack, err := t.client.Stacktrace(goroutineid, depth, full)
655 656 657 658 659 660
	if err != nil {
		return err
	}
	printStack(stack, "")
	return nil
}
A
aarzilli 已提交
661

662 663 664 665 666
func parseStackArgs(args []string) (int, bool, error) {
	var (
		depth = 10
		full  = false
	)
667 668 669 670 671 672
	for i := range args {
		if args[i] == "-full" {
			full = true
		} else {
			n, err := strconv.Atoi(args[i])
			if err != nil {
673
				return 0, false, fmt.Errorf("depth must be a number")
674
			}
675
			depth = n
A
aarzilli 已提交
676 677
		}
	}
678
	return depth, full, nil
A
aarzilli 已提交
679 680
}

681
func listCommand(t *Term, args ...string) error {
682
	if len(args) == 0 {
683
		state, err := t.client.GetState()
684 685 686
		if err != nil {
			return err
		}
687
		printcontext(t, state)
688 689 690
		return nil
	}

691
	locs, err := t.client.FindLocation(api.EvalScope{-1, 0}, args[0])
692 693 694 695 696 697
	if err != nil {
		return err
	}
	if len(locs) > 1 {
		return debugger.AmbiguousLocationError{Location: args[0], CandidatesLocation: locs}
	}
698
	printfile(t, locs[0].File, locs[0].Line, false)
699 700 701
	return nil
}

702 703 704 705 706 707 708
func digits(n int) int {
	return int(math.Floor(math.Log10(float64(n)))) + 1
}

func printStack(stack []api.Stackframe, ind string) {
	d := digits(len(stack) - 1)
	fmtstr := "%s%" + strconv.Itoa(d) + "d  0x%016x in %s\n"
709
	s := strings.Repeat(" ", d+2+len(ind))
710

A
aarzilli 已提交
711 712 713 714 715
	for i := range stack {
		name := "(nil)"
		if stack[i].Function != nil {
			name = stack[i].Function.Name
		}
716 717 718 719 720 721 722 723 724
		fmt.Printf(fmtstr, ind, i, stack[i].PC, name)
		fmt.Printf("%sat %s:%d\n", s, shortenFilePath(stack[i].File), stack[i].Line)

		for j := range stack[i].Arguments {
			fmt.Printf("%s    %s = %s\n", s, stack[i].Arguments[j].Name, stack[i].Arguments[j].Value)
		}
		for j := range stack[i].Locals {
			fmt.Printf("%s    %s = %s\n", s, stack[i].Locals[j].Name, stack[i].Locals[j].Value)
		}
A
aarzilli 已提交
725 726 727
	}
}

728
func printcontext(t *Term, state *api.DebuggerState) error {
D
Dan Mace 已提交
729 730 731 732 733 734
	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)
735
		t.Println("=>", "no source available")
D
Dan Mace 已提交
736 737
		return nil
	}
D
Derek Parker 已提交
738
	var fn *api.Function
D
Dan Mace 已提交
739
	if state.CurrentThread.Function != nil {
D
Derek Parker 已提交
740 741 742 743 744 745 746
		fn = state.CurrentThread.Function
	}
	if state.Breakpoint != nil && state.Breakpoint.Tracepoint {
		var args []string
		for _, arg := range state.CurrentThread.Function.Args {
			args = append(args, arg.Value)
		}
747
		fmt.Printf("> %s(%s) %s:%d\n", fn.Name, strings.Join(args, ", "), shortenFilePath(state.CurrentThread.File), state.CurrentThread.Line)
D
Derek Parker 已提交
748
	} else {
749
		fmt.Printf("> %s() %s:%d\n", fn.Name, shortenFilePath(state.CurrentThread.File), state.CurrentThread.Line)
D
Dan Mace 已提交
750 751
	}

A
aarzilli 已提交
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
	if state.BreakpointInfo != nil {
		bpi := state.BreakpointInfo

		if bpi.Goroutine != nil {
			fmt.Printf("\tGoroutine %s\n", formatGoroutine(bpi.Goroutine))
		}

		ss := make([]string, len(bpi.Variables))
		for i, v := range bpi.Variables {
			ss[i] = fmt.Sprintf("%s: <%v>", v.Name, v.Value)
		}
		fmt.Printf("\t%s\n", strings.Join(ss, ", "))

		if bpi.Stacktrace != nil {
			fmt.Printf("\tStack:\n")
			printStack(bpi.Stacktrace, "\t\t")
		}
	}
	if state.Breakpoint != nil && state.Breakpoint.Tracepoint {
		return nil
	}
773
	return printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
774 775
}

776
func printfile(t *Term, filename string, line int, showArrow bool) error {
777
	file, err := os.Open(filename)
D
Dan Mace 已提交
778 779 780 781 782
	if err != nil {
		return err
	}
	defer file.Close()

783
	buf := bufio.NewScanner(file)
784
	l := line
D
Dan Mace 已提交
785
	for i := 1; i < l-5; i++ {
786 787
		if !buf.Scan() {
			return nil
D
Dan Mace 已提交
788 789 790
		}
	}

791 792 793 794 795 796
	s := l - 5
	if s < 1 {
		s = 1
	}

	for i := s; i <= l+5; i++ {
797 798
		if !buf.Scan() {
			return nil
D
Dan Mace 已提交
799 800
		}

801 802 803 804 805 806
		var arrow string
		if showArrow {
			arrow = "  "
			if i == l {
				arrow = "=>"
			}
D
Dan Mace 已提交
807 808
		}

809
		var lineNum string
810 811
		if i < 10 {
			lineNum = fmt.Sprintf("%s  %d:\t", arrow, i)
812
		} else {
813
			lineNum = fmt.Sprintf("%s %d:\t", arrow, i)
814
		}
815
		t.Println(lineNum, buf.Text())
D
Dan Mace 已提交
816 817 818
	}
	return nil
}
D
Derek Parker 已提交
819 820 821 822 823 824 825

type ExitRequestError struct{}

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

826
func exitCommand(t *Term, args ...string) error {
D
Derek Parker 已提交
827 828
	return ExitRequestError{}
}
829 830 831 832 833

func shortenFilePath(fullPath string) string {
	workingDir, _ := os.Getwd()
	return strings.Replace(fullPath, workingDir, ".", 1)
}