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

import (
	"bufio"
	"fmt"
	"io"
	"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
)

type cmdfunc func(client service.Client, args ...string) error
22 23 24 25
type scopedCmdfunc func(client service.Client, scope api.EvalScope, args ...string) error

type filteringFunc func(client service.Client, filter string) ([]string, error)
type scopedFilteringFunc func(client service.Client, 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."},
D
Derek Parker 已提交
69 70
		{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."},
71 72
		{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 已提交
73 74
		{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 已提交
75
		{aliases: []string{"exit", "quit", "q"}, cmdFn: exitCommand, helpMsg: "Exit the debugger."},
76
		{aliases: []string{"stack", "bt"}, cmdFn: stackCommand, helpMsg: "stack [<depth> [<goroutine id>]]. Prints stack."},
77
		{aliases: []string{"list", "ls"}, cmdFn: listCommand, helpMsg: "list <linespec>.  Show source around current point or provided linespec."},
78
		{aliases: []string{"frame"}, cmdFn: frame, helpMsg: "Sets current stack frame (0 is the top of the stack)"},
D
Dan Mace 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
	}

	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 已提交
98
// If it cannot find the command it will default to noCmdAvailable().
D
Dan Mace 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
// 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
}

119 120 121 122 123 124 125 126 127
// 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 已提交
128 129 130 131 132 133 134
func CommandFunc(fn func() error) cmdfunc {
	return func(client service.Client, args ...string) error {
		return fn()
	}
}

func noCmdAvailable(client service.Client, args ...string) error {
D
Derek Parker 已提交
135
	return fmt.Errorf("command not available")
D
Dan Mace 已提交
136 137 138 139 140 141 142 143
}

func nullCommand(client service.Client, args ...string) error {
	return nil
}

func (c *Commands) help(client service.Client, args ...string) error {
	fmt.Println("The following commands are available:")
D
Derek Parker 已提交
144 145
	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 8, 0, '-', 0)
D
Dan Mace 已提交
146
	for _, cmd := range c.cmds {
D
Derek Parker 已提交
147 148 149 150 151
		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 已提交
152
	}
D
Derek Parker 已提交
153
	return w.Flush()
D
Dan Mace 已提交
154 155
}

I
Ilia Choly 已提交
156 157 158 159 160 161
type byID []*api.Thread

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

func thread(client service.Client, args ...string) error {
189 190 191
	if len(args) == 0 {
		return fmt.Errorf("you must specify a thread")
	}
D
Dan Mace 已提交
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
	tid, err := strconv.Atoi(args[0])
	if err != nil {
		return err
	}
	oldState, err := client.GetState()
	if err != nil {
		return err
	}
	newState, err := client.SwitchThread(tid)
	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
}

func goroutines(client service.Client, args ...string) error {
218 219 220 221
	state, err := client.GetState()
	if err != nil {
		return err
	}
D
Dan Mace 已提交
222 223 224 225 226 227
	gs, err := client.ListGoroutines()
	if err != nil {
		return err
	}
	fmt.Printf("[%d goroutines]\n", len(gs))
	for _, g := range gs {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 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 315 316 317 318 319 320 321 322 323 324
		prefix := "  "
		if g.ID == state.SelectedGoroutine.ID {
			prefix = "* "
		}
		fmt.Printf("%sGoroutine %s\n", prefix, formatGoroutine(g))
	}
	return nil
}

func goroutine(client service.Client, args ...string) error {
	switch len(args) {
	case 0:
		return printscope(client)

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

		oldState, err := client.GetState()
		if err != nil {
			return err
		}
		newState, err := client.SwitchGoroutine(gid)
		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:
		return scopePrefix(client, "goroutine", args...)
	}
}

func frame(client service.Client, args ...string) error {
	return scopePrefix(client, "frame", args...)
}

func scopePrefix(client service.Client, cmdname string, pargs ...string) error {
	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 {
		outfn := filterSortAndOutput(func(client service.Client, filter string) ([]string, error) {
			return fn(client, scope, filter)
		})
		return outfn(client, fnargs...)
	}

	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++
		case "locals":
			return callFilterSortAndOutput(locals, fullargs[i+1:])
		case "args":
			return callFilterSortAndOutput(args, fullargs[i+1:])
		case "print", "p":
			return printVar(client, scope, fullargs[i+1:]...)
		default:
			return fmt.Errorf("unknown command %s", fullargs[i])
		}
	}

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

func printscope(client service.Client) error {
	state, err := client.GetState()
	if err != nil {
		return err
D
Dan Mace 已提交
325
	}
326 327

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

331 332 333 334 335 336 337
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 已提交
338
func formatGoroutine(g *api.Goroutine) string {
339 340 341
	if g == nil {
		return "<nil>"
	}
A
aarzilli 已提交
342 343 344 345
	fname := ""
	if g.Function != nil {
		fname = g.Function.Name
	}
346
	return fmt.Sprintf("%d - %s:%d %s (%#v)", g.ID, shortenFilePath(g.File), g.Line, fname, g.PC)
A
aarzilli 已提交
347 348
}

D
Derek Parker 已提交
349 350 351 352 353 354 355 356
func restart(client service.Client, args ...string) error {
	if err := client.Restart(); err != nil {
		return err
	}
	fmt.Println("Process restarted with PID", client.ProcessPid())
	return nil
}

D
Dan Mace 已提交
357
func cont(client service.Client, args ...string) error {
D
Derek Parker 已提交
358 359
	stateChan := client.Continue()
	for state := range stateChan {
A
aarzilli 已提交
360 361 362 363
		if state.Err != nil {
			return state.Err
		}
		printcontext(state)
D
Dan Mace 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	}
	return nil
}

func step(client service.Client, args ...string) error {
	state, err := client.Step()
	if err != nil {
		return err
	}
	printcontext(state)
	return nil
}

func next(client service.Client, args ...string) error {
	state, err := client.Next()
	if err != nil {
		return err
	}
	printcontext(state)
	return nil
}

func clear(client service.Client, args ...string) error {
	if len(args) == 0 {
D
Derek Parker 已提交
388
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
389 390 391 392 393
	}
	id, err := strconv.Atoi(args[0])
	if err != nil {
		return err
	}
D
Derek Parker 已提交
394
	bp, err := client.ClearBreakpoint(id)
D
Dan Mace 已提交
395 396 397
	if err != nil {
		return err
	}
398
	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 已提交
399 400 401 402
	return nil
}

func clearAll(client service.Client, args ...string) error {
D
Derek Parker 已提交
403
	breakPoints, err := client.ListBreakpoints()
D
Dan Mace 已提交
404 405 406 407
	if err != nil {
		return err
	}
	for _, bp := range breakPoints {
D
Derek Parker 已提交
408
		_, err := client.ClearBreakpoint(bp.ID)
D
Dan Mace 已提交
409
		if err != nil {
410
			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 已提交
411
		}
412
		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 已提交
413 414 415 416
	}
	return nil
}

D
Derek Parker 已提交
417
type ById []*api.Breakpoint
D
Dan Mace 已提交
418 419 420 421 422 423

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 }

func breakpoints(client service.Client, args ...string) error {
D
Derek Parker 已提交
424
	breakPoints, err := client.ListBreakpoints()
D
Dan Mace 已提交
425 426 427 428 429
	if err != nil {
		return err
	}
	sort.Sort(ById(breakPoints))
	for _, bp := range breakPoints {
A
aarzilli 已提交
430 431 432 433
		thing := "Breakpoint"
		if bp.Tracepoint {
			thing = "Tracepoint"
		}
434
		fmt.Printf("%s %d at %#v %s:%d\n", thing, bp.ID, bp.Addr, shortenFilePath(bp.File), bp.Line)
A
aarzilli 已提交
435 436 437 438 439 440 441 442 443

		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 已提交
444 445
		for i := range bp.Variables {
			attrs = append(attrs, bp.Variables[i])
A
aarzilli 已提交
446 447 448 449
		}
		if len(attrs) > 0 {
			fmt.Printf("\t%s\n", strings.Join(attrs, " "))
		}
D
Dan Mace 已提交
450 451 452 453
	}
	return nil
}

D
Derek Parker 已提交
454
func setBreakpoint(client service.Client, tracepoint bool, args ...string) error {
A
aarzilli 已提交
455 456
	if len(args) < 1 {
		return fmt.Errorf("address required, specify either a function name or <file:line>")
D
Dan Mace 已提交
457
	}
D
Derek Parker 已提交
458
	requestedBp := &api.Breakpoint{}
D
Dan Mace 已提交
459

A
aarzilli 已提交
460 461 462 463 464 465 466 467 468 469 470 471
	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 已提交
472
			requestedBp.Variables = append(requestedBp.Variables, args[i])
A
aarzilli 已提交
473 474 475 476
		}
	}

	requestedBp.Tracepoint = tracepoint
477
	locs, err := client.FindLocation(api.EvalScope{-1, 0}, args[0])
D
Dan Mace 已提交
478 479 480
	if err != nil {
		return err
	}
A
aarzilli 已提交
481 482 483 484
	thing := "Breakpoint"
	if tracepoint {
		thing = "Tracepoint"
	}
485 486 487 488 489 490 491 492
	for _, loc := range locs {
		requestedBp.Addr = loc.PC

		bp, err := client.CreateBreakpoint(requestedBp)
		if err != nil {
			return err
		}

493
		fmt.Printf("%s %d set at %#v for %s %s:%d\n", thing, bp.ID, bp.Addr, bp.FunctionName, shortenFilePath(bp.File), bp.Line)
494
	}
D
Dan Mace 已提交
495 496 497
	return nil
}

A
aarzilli 已提交
498
func breakpoint(client service.Client, args ...string) error {
D
Derek Parker 已提交
499
	return setBreakpoint(client, false, args...)
A
aarzilli 已提交
500 501 502
}

func tracepoint(client service.Client, args ...string) error {
D
Derek Parker 已提交
503
	return setBreakpoint(client, true, args...)
A
aarzilli 已提交
504 505
}

506 507 508 509 510 511 512 513 514 515 516 517 518
func g0f0(fn scopedCmdfunc) cmdfunc {
	return func(client service.Client, args ...string) error {
		return fn(client, api.EvalScope{-1, 0}, args...)
	}
}

func g0f0filter(fn scopedFilteringFunc) filteringFunc {
	return func(client service.Client, filter string) ([]string, error) {
		return fn(client, api.EvalScope{-1, 0}, filter)
	}
}

func printVar(client service.Client, scope api.EvalScope, args ...string) error {
D
Dan Mace 已提交
519
	if len(args) == 0 {
D
Derek Parker 已提交
520
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
521
	}
522
	val, err := client.EvalVariable(scope, args[0])
D
Dan Mace 已提交
523 524 525 526 527 528 529
	if err != nil {
		return err
	}
	fmt.Println(val.Value)
	return nil
}

D
Derek Parker 已提交
530 531 532 533 534 535
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 已提交
536 537
	data := make([]string, 0, len(vars))
	for _, v := range vars {
D
Derek Parker 已提交
538
		if reg == nil || reg.Match([]byte(v.Name)) {
D
Dan Mace 已提交
539 540 541 542 543 544
			data = append(data, fmt.Sprintf("%s = %s", v.Name, v.Value))
		}
	}
	return data
}

D
Derek Parker 已提交
545 546 547
func sources(client service.Client, filter string) ([]string, error) {
	return client.ListSources(filter)
}
D
Dan Mace 已提交
548

D
Derek Parker 已提交
549 550 551
func funcs(client service.Client, filter string) ([]string, error) {
	return client.ListFunctions(filter)
}
D
Dan Mace 已提交
552

553 554
func args(client service.Client, scope api.EvalScope, filter string) ([]string, error) {
	vars, err := client.ListFunctionArgs(scope)
D
Derek Parker 已提交
555 556 557 558 559
	if err != nil {
		return nil, err
	}
	return filterVariables(vars, filter), nil
}
D
Dan Mace 已提交
560

561 562
func locals(client service.Client, scope api.EvalScope, filter string) ([]string, error) {
	locals, err := client.ListLocalVariables(scope)
D
Derek Parker 已提交
563 564 565 566 567
	if err != nil {
		return nil, err
	}
	return filterVariables(locals, filter), nil
}
D
Dan Mace 已提交
568

D
Derek Parker 已提交
569 570 571 572 573 574 575
func vars(client service.Client, filter string) ([]string, error) {
	vars, err := client.ListPackageVariables(filter)
	if err != nil {
		return nil, err
	}
	return filterVariables(vars, filter), nil
}
D
Dan Mace 已提交
576

D
Derek Parker 已提交
577 578 579 580 581 582 583 584
func regs(client service.Client, args ...string) error {
	regs, err := client.ListRegisters()
	if err != nil {
		return err
	}
	fmt.Println(regs)
	return nil
}
585

586
func filterSortAndOutput(fn filteringFunc) cmdfunc {
D
Derek Parker 已提交
587 588 589 590 591 592 593
	return func(client service.Client, args ...string) error {
		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 已提交
594
		}
D
Derek Parker 已提交
595
		data, err := fn(client, filter)
D
Dan Mace 已提交
596 597 598
		if err != nil {
			return err
		}
D
Derek Parker 已提交
599 600 601
		sort.Sort(sort.StringSlice(data))
		for _, d := range data {
			fmt.Println(d)
D
Dan Mace 已提交
602
		}
D
Derek Parker 已提交
603
		return nil
D
Dan Mace 已提交
604 605 606
	}
}

A
aarzilli 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
func stackCommand(client service.Client, args ...string) error {
	var err error

	goroutineid := -1
	depth := 10

	switch len(args) {
	case 0:
		// nothing to do
	case 2:
		goroutineid, err = strconv.Atoi(args[1])
		if err != nil {
			return fmt.Errorf("Wrong argument: expected integer")
		}
		fallthrough
	case 1:
		depth, err = strconv.Atoi(args[0])
		if err != nil {
			return fmt.Errorf("Wrong argument: expected integer")
		}

	default:
		return fmt.Errorf("Wrong number of arguments to stack")
	}

	stack, err := client.Stacktrace(goroutineid, depth)
	if err != nil {
		return err
	}
A
aarzilli 已提交
636 637 638 639
	printStack(stack, "")
	return nil
}

640 641 642 643 644 645 646 647 648 649
func listCommand(client service.Client, args ...string) error {
	if len(args) == 0 {
		state, err := client.GetState()
		if err != nil {
			return err
		}
		printcontext(state)
		return nil
	}

650
	locs, err := client.FindLocation(api.EvalScope{-1, 0}, args[0])
651 652 653 654 655 656 657 658 659 660
	if err != nil {
		return err
	}
	if len(locs) > 1 {
		return debugger.AmbiguousLocationError{Location: args[0], CandidatesLocation: locs}
	}
	printfile(locs[0].File, locs[0].Line, false)
	return nil
}

A
aarzilli 已提交
661
func printStack(stack []api.Location, ind string) {
A
aarzilli 已提交
662 663 664 665 666
	for i := range stack {
		name := "(nil)"
		if stack[i].Function != nil {
			name = stack[i].Function.Name
		}
667
		fmt.Printf("%s%d. %s %s:%d (%#v)\n", ind, i, name, shortenFilePath(stack[i].File), stack[i].Line, stack[i].PC)
A
aarzilli 已提交
668 669 670
	}
}

D
Dan Mace 已提交
671 672 673 674 675 676 677 678 679 680
func printcontext(state *api.DebuggerState) error {
	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)
		fmt.Printf("\033[34m=>\033[0m    no source available\n")
		return nil
	}
D
Derek Parker 已提交
681
	var fn *api.Function
D
Dan Mace 已提交
682
	if state.CurrentThread.Function != nil {
D
Derek Parker 已提交
683 684 685 686 687 688 689
		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)
		}
690
		fmt.Printf("> %s(%s) %s:%d\n", fn.Name, strings.Join(args, ", "), shortenFilePath(state.CurrentThread.File), state.CurrentThread.Line)
D
Derek Parker 已提交
691
	} else {
692
		fmt.Printf("> %s() %s:%d\n", fn.Name, shortenFilePath(state.CurrentThread.File), state.CurrentThread.Line)
D
Dan Mace 已提交
693 694
	}

A
aarzilli 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
	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
	}
716 717 718 719 720
	return printfile(state.CurrentThread.File, state.CurrentThread.Line, true)
}

func printfile(filename string, line int, showArrow bool) error {
	file, err := os.Open(filename)
D
Dan Mace 已提交
721 722 723 724 725
	if err != nil {
		return err
	}
	defer file.Close()

726
	var context []string
D
Dan Mace 已提交
727
	buf := bufio.NewReader(file)
728
	l := line
D
Dan Mace 已提交
729 730 731 732 733 734 735
	for i := 1; i < l-5; i++ {
		_, err := buf.ReadString('\n')
		if err != nil && err != io.EOF {
			return err
		}
	}

736 737 738 739 740 741
	s := l - 5
	if s < 1 {
		s = 1
	}

	for i := s; i <= l+5; i++ {
D
Dan Mace 已提交
742 743 744 745 746 747 748 749 750 751 752
		line, err := buf.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				return err
			}

			if err == io.EOF {
				break
			}
		}

753 754 755 756 757 758
		var arrow string
		if showArrow {
			arrow = "  "
			if i == l {
				arrow = "=>"
			}
D
Dan Mace 已提交
759 760
		}

761 762 763 764 765 766 767
		var lineNum string
		if i < 10 {
			lineNum = fmt.Sprintf("\033[34m%s  %d\033[0m:\t", arrow, i)
		} else {
			lineNum = fmt.Sprintf("\033[34m%s %d\033[0m:\t", arrow, i)
		}
		context = append(context, lineNum+line)
D
Dan Mace 已提交
768 769 770 771 772 773
	}

	fmt.Println(strings.Join(context, ""))

	return nil
}
D
Derek Parker 已提交
774 775 776 777 778 779 780 781 782 783

type ExitRequestError struct{}

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

func exitCommand(client service.Client, args ...string) error {
	return ExitRequestError{}
}
784 785 786 787 788

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