command.go 14.4 KB
Newer Older
D
Dan Mace 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// 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"

	"github.com/derekparker/delve/service"
	"github.com/derekparker/delve/service/api"
)

type cmdfunc func(client service.Client, args ...string) error

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."},
A
aarzilli 已提交
49 50
		{aliases: []string{"break", "b"}, cmdFn: breakpoint, helpMsg: "break <address> [-stack <n>|-goroutine|<variable name>]*\nSet break point at the entry point of a function, or at a specific file/line.\nWhen the breakpoint is reached the value of the specified variables will be printed, if -stack is specified the stack trace of the current goroutine will be printed, if -goroutine is specified informations about the current goroutine will be printed. Example: break foo.go:13"},
		{aliases: []string{"trace"}, cmdFn: tracepoint, helpMsg: "Set tracepoint, takes the same arguments as break"},
D
Dan Mace 已提交
51 52 53 54 55 56 57 58 59 60
		{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."},
		{aliases: []string{"thread", "t"}, cmdFn: thread, helpMsg: "Switch to the specified thread."},
		{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."},
		{aliases: []string{"breakpoints", "bp"}, cmdFn: breakpoints, helpMsg: "Print out info for active breakpoints."},
		{aliases: []string{"print", "p"}, cmdFn: printVar, helpMsg: "Evaluate a variable."},
61
		{aliases: []string{"info"}, cmdFn: info, helpMsg: "Subcommands: args, funcs, locals, sources, vars, or regs."},
D
Dan Mace 已提交
62
		{aliases: []string{"exit"}, cmdFn: nullCommand, helpMsg: "Exit the debugger."},
A
aarzilli 已提交
63
		{aliases: []string{"stack"}, cmdFn: stackCommand, helpMsg: "stack [<depth> [<goroutine id>]]. Prints stack."},
D
Dan Mace 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
	}

	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.
// If it cannot find the command it will defualt to noCmdAvailable().
// 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
}

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 已提交
111
	return fmt.Errorf("command not available")
D
Dan Mace 已提交
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 138 139 140 141 142 143 144 145 146 147 148 149 150 151
}

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:")
	for _, cmd := range c.cmds {
		fmt.Printf("\t%s - %s\n", strings.Join(cmd.aliases, "|"), cmd.helpMsg)
	}
	return nil
}

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
	}
	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",
				prefix, th.ID, th.PC, th.File,
				th.Line, th.Function.Name)
		} else {
			fmt.Printf("%sThread %d at %s:%d\n", prefix, th.ID, th.File, th.Line)
		}
	}
	return nil
}

func thread(client service.Client, args ...string) error {
152 153 154
	if len(args) == 0 {
		return fmt.Errorf("you must specify a thread")
	}
D
Dan Mace 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	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 {
	gs, err := client.ListGoroutines()
	if err != nil {
		return err
	}
	fmt.Printf("[%d goroutines]\n", len(gs))
	for _, g := range gs {
A
aarzilli 已提交
190
		fmt.Printf("Goroutine %s\n", formatGoroutine(g))
D
Dan Mace 已提交
191 192 193 194
	}
	return nil
}

A
aarzilli 已提交
195 196 197 198 199 200 201 202
func formatGoroutine(g *api.Goroutine) string {
	fname := ""
	if g.Function != nil {
		fname = g.Function.Name
	}
	return fmt.Sprintf("%d - %s:%d %s (%#v)\n", g.ID, g.File, g.Line, fname, g.PC)
}

D
Dan Mace 已提交
203
func cont(client service.Client, args ...string) error {
A
aarzilli 已提交
204 205 206 207 208 209
	statech := client.Continue()
	for state := range statech {
		if state.Err != nil {
			return state.Err
		}
		printcontext(state)
D
Dan Mace 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	}
	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 已提交
234
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
235 236 237 238 239 240 241
	}

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

D
Derek Parker 已提交
242
	bp, err := client.ClearBreakpoint(id)
D
Dan Mace 已提交
243 244 245 246 247 248 249 250
	if err != nil {
		return err
	}
	fmt.Printf("Breakpoint %d cleared at %#v for %s %s:%d\n", bp.ID, bp.Addr, bp.FunctionName, bp.File, bp.Line)
	return nil
}

func clearAll(client service.Client, args ...string) error {
D
Derek Parker 已提交
251
	breakPoints, err := client.ListBreakpoints()
D
Dan Mace 已提交
252 253 254 255
	if err != nil {
		return err
	}
	for _, bp := range breakPoints {
D
Derek Parker 已提交
256
		_, err := client.ClearBreakpoint(bp.ID)
D
Dan Mace 已提交
257 258 259 260 261 262 263 264
		if err != nil {
			fmt.Printf("Couldn't delete breakpoint %d at %#v %s:%d: %s\n", bp.ID, bp.Addr, bp.File, bp.Line, err)
		}
		fmt.Printf("Breakpoint %d cleared at %#v for %s %s:%d\n", bp.ID, bp.Addr, bp.FunctionName, bp.File, bp.Line)
	}
	return nil
}

D
Derek Parker 已提交
265
type ById []*api.Breakpoint
D
Dan Mace 已提交
266 267 268 269 270 271

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 已提交
272
	breakPoints, err := client.ListBreakpoints()
D
Dan Mace 已提交
273 274 275 276 277
	if err != nil {
		return err
	}
	sort.Sort(ById(breakPoints))
	for _, bp := range breakPoints {
A
aarzilli 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
		thing := "Breakpoint"
		if bp.Tracepoint {
			thing = "Tracepoint"
		}
		fmt.Printf("%s %d at %#v %s:%d\n", thing, bp.ID, bp.Addr, bp.File, bp.Line)

		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")
		}
		for i := range bp.Symbols {
			attrs = append(attrs, bp.Symbols[i])
		}

		if len(attrs) > 0 {
			fmt.Printf("\t%s\n", strings.Join(attrs, " "))
		}
D
Dan Mace 已提交
299 300 301 302 303
	}

	return nil
}

A
aarzilli 已提交
304 305 306
func breakpointIntl(client service.Client, tracepoint bool, args ...string) error {
	if len(args) < 1 {
		return fmt.Errorf("address required, specify either a function name or <file:line>")
D
Dan Mace 已提交
307
	}
A
aarzilli 已提交
308

D
Derek Parker 已提交
309
	requestedBp := &api.Breakpoint{}
D
Dan Mace 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322
	tokens := strings.Split(args[0], ":")
	switch {
	case len(tokens) == 1:
		requestedBp.FunctionName = args[0]
	case len(tokens) == 2:
		file := tokens[0]
		line, err := strconv.Atoi(tokens[1])
		if err != nil {
			return err
		}
		requestedBp.File = file
		requestedBp.Line = line
	default:
D
Derek Parker 已提交
323
		return fmt.Errorf("invalid line reference")
D
Dan Mace 已提交
324 325
	}

A
aarzilli 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
	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:
			requestedBp.Symbols = append(requestedBp.Symbols, args[i])
		}
	}

	requestedBp.Tracepoint = tracepoint

D
Derek Parker 已提交
344
	bp, err := client.CreateBreakpoint(requestedBp)
D
Dan Mace 已提交
345 346 347 348
	if err != nil {
		return err
	}

A
aarzilli 已提交
349 350 351 352 353 354
	thing := "Breakpoint"
	if tracepoint {
		thing = "Tracepoint"
	}

	fmt.Printf("%s %d set at %#v for %s %s:%d\n", thing, bp.ID, bp.Addr, bp.FunctionName, bp.File, bp.Line)
D
Dan Mace 已提交
355 356 357
	return nil
}

A
aarzilli 已提交
358 359 360 361 362 363 364 365
func breakpoint(client service.Client, args ...string) error {
	return breakpointIntl(client, false, args...)
}

func tracepoint(client service.Client, args ...string) error {
	return breakpointIntl(client, true, args...)
}

D
Dan Mace 已提交
366 367
func printVar(client service.Client, args ...string) error {
	if len(args) == 0 {
D
Derek Parker 已提交
368
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
369 370
	}

371
	val, err := client.EvalVariable(args[0])
D
Dan Mace 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
	if err != nil {
		return err
	}

	fmt.Println(val.Value)
	return nil
}

func filterVariables(vars []api.Variable, filter *regexp.Regexp) []string {
	data := make([]string, 0, len(vars))
	for _, v := range vars {
		if filter == nil || filter.Match([]byte(v.Name)) {
			data = append(data, fmt.Sprintf("%s = %s", v.Name, v.Value))
		}
	}
	return data
}

func info(client service.Client, args ...string) error {
	if len(args) == 0 {
D
Derek Parker 已提交
392
		return fmt.Errorf("not enough arguments. expected info type [regex].")
D
Dan Mace 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	}

	// Allow for optional regex
	var filter *regexp.Regexp
	if len(args) >= 2 {
		var err error
		if filter, err = regexp.Compile(args[1]); err != nil {
			return fmt.Errorf("invalid filter argument: %s", err.Error())
		}
	}

	var data []string

	switch args[0] {
	case "sources":
		regex := ""
		if len(args) >= 2 && len(args[1]) > 0 {
			regex = args[1]
		}
		sources, err := client.ListSources(regex)
		if err != nil {
			return err
		}
		data = sources

	case "funcs":
		regex := ""
		if len(args) >= 2 && len(args[1]) > 0 {
			regex = args[1]
		}
		funcs, err := client.ListFunctions(regex)
		if err != nil {
			return err
		}
		data = funcs

429 430 431 432 433 434 435
	case "regs":
		regs, err := client.ListRegisters()
		if err != nil {
			return err
		}
		data = append(data, regs)

D
Dan Mace 已提交
436
	case "args":
437
		args, err := client.ListFunctionArgs()
D
Dan Mace 已提交
438 439 440
		if err != nil {
			return err
		}
441
		data = filterVariables(args, filter)
D
Dan Mace 已提交
442 443

	case "locals":
444
		locals, err := client.ListLocalVariables()
D
Dan Mace 已提交
445 446 447
		if err != nil {
			return err
		}
448
		data = filterVariables(locals, filter)
D
Dan Mace 已提交
449 450 451 452 453 454 455 456 457 458

	case "vars":
		regex := ""
		if len(args) >= 2 && len(args[1]) > 0 {
			regex = args[1]
		}
		vars, err := client.ListPackageVariables(regex)
		if err != nil {
			return err
		}
459
		data = filterVariables(vars, filter)
D
Dan Mace 已提交
460 461

	default:
A
aarzilli 已提交
462
		return fmt.Errorf("unsupported info type, must be args, funcs, locals, sources or vars")
D
Dan Mace 已提交
463 464 465 466 467 468 469 470 471 472 473
	}

	// sort and output data
	sort.Sort(sort.StringSlice(data))

	for _, d := range data {
		fmt.Println(d)
	}
	return nil
}

A
aarzilli 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
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 已提交
503 504 505 506 507
	printStack(stack, "")
	return nil
}

func printStack(stack []api.Location, ind string) {
A
aarzilli 已提交
508 509 510 511 512
	for i := range stack {
		name := "(nil)"
		if stack[i].Function != nil {
			name = stack[i].Function.Name
		}
A
aarzilli 已提交
513
		fmt.Printf("%s%d. %s %s:%d (%#v)\n", ind, i, name, stack[i].File, stack[i].Line, stack[i].PC)
A
aarzilli 已提交
514 515 516
	}
}

D
Dan Mace 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
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
	}

	var context []string

	fn := ""
	if state.CurrentThread.Function != nil {
		fn = state.CurrentThread.Function.Name
	}
	fmt.Printf("current loc: %s %s:%d\n", fn, state.CurrentThread.File, state.CurrentThread.Line)

A
aarzilli 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
	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
	}

D
Dan Mace 已提交
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
	file, err := os.Open(state.CurrentThread.File)
	if err != nil {
		return err
	}
	defer file.Close()

	buf := bufio.NewReader(file)
	l := state.CurrentThread.Line
	for i := 1; i < l-5; i++ {
		_, err := buf.ReadString('\n')
		if err != nil && err != io.EOF {
			return err
		}
	}

	for i := l - 5; i <= l+5; i++ {
		line, err := buf.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				return err
			}

			if err == io.EOF {
				break
			}
		}

		arrow := "  "
		if i == l {
			arrow = "=>"
		}

592 593 594 595 596 597 598
		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 已提交
599 600 601 602 603 604
	}

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

	return nil
}