command.go 24.3 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
	"io"
9
	"math"
D
Dan Mace 已提交
10 11 12 13 14
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
D
Derek Parker 已提交
15
	"text/tabwriter"
D
Dan Mace 已提交
16 17 18

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

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

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

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 {
D
Derek Parker 已提交
45 46 47
	cmds    []command
	lastCmd cmdfunc
	client  service.Client
D
Dan Mace 已提交
48 49 50 51 52 53 54 55
}

// 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."},
56
		{aliases: []string{"break", "b"}, cmdFn: breakpoint, helpMsg: "break <linespec> [-stack <n>|-goroutine|<variable name>]*"},
D
Derek Parker 已提交
57
		{aliases: []string{"trace", "t"}, cmdFn: tracepoint, helpMsg: "Set tracepoint, takes the same arguments as break."},
D
Derek Parker 已提交
58
		{aliases: []string{"restart", "r"}, cmdFn: restart, helpMsg: "Restart process."},
D
Dan Mace 已提交
59 60 61 62
		{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 已提交
63
		{aliases: []string{"thread", "tr"}, cmdFn: thread, helpMsg: "Switch to the specified thread."},
D
Dan Mace 已提交
64
		{aliases: []string{"clear"}, cmdFn: clear, helpMsg: "Deletes breakpoint."},
65
		{aliases: []string{"clearall"}, cmdFn: clearAll, helpMsg: "clearall [<linespec>]. Deletes all breakpoints. If <linespec> is provided, only matching breakpoints will be deleted."},
D
Dan Mace 已提交
66
		{aliases: []string{"goroutines"}, cmdFn: goroutines, helpMsg: "Print out info for every goroutine."},
67
		{aliases: []string{"goroutine"}, cmdFn: goroutine, helpMsg: "Sets current goroutine."},
D
Dan Mace 已提交
68
		{aliases: []string{"breakpoints", "bp"}, cmdFn: breakpoints, helpMsg: "Print out info for active breakpoints."},
69
		{aliases: []string{"print", "p"}, cmdFn: g0f0(printVar), helpMsg: "Evaluate a variable."},
70
		{aliases: []string{"set"}, cmdFn: g0f0(setVar), helpMsg: "Changes the value of a variable."},
D
Derek Parker 已提交
71 72
		{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."},
73 74
		{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 已提交
75 76
		{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 已提交
77
		{aliases: []string{"exit", "quit", "q"}, cmdFn: exitCommand, helpMsg: "Exit the debugger."},
78
		{aliases: []string{"list", "ls"}, cmdFn: listCommand, helpMsg: "list <linespec>.  Show source around current point or provided linespec."},
79
		{aliases: []string{"stack", "bt"}, cmdFn: stackCommand, helpMsg: "stack [<depth>] [-full]. Prints stack."},
80
		{aliases: []string{"frame"}, cmdFn: frame, helpMsg: "Sets current stack frame (0 is the top of the stack)"},
81
		{aliases: []string{"source"}, cmdFn: c.sourceCommand, helpMsg: "Executes a file containing a list of delve commands"},
D
Dan Mace 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	}

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

122 123 124 125 126 127 128 129 130
// 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 已提交
131
func CommandFunc(fn func() error) cmdfunc {
132
	return func(t *Term, args ...string) error {
D
Dan Mace 已提交
133 134 135 136
		return fn()
	}
}

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

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

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

I
Ilia Choly 已提交
159
type byThreadID []*api.Thread
I
Ilia Choly 已提交
160

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

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

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

226
func goroutines(t *Term, args ...string) error {
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
	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
		default:
			fmt.Errorf("wrong argument: '%s'", args[0])
		}
	default:
		return fmt.Errorf("too many arguments")
	}
246
	state, err := t.client.GetState()
247 248 249
	if err != nil {
		return err
	}
250
	gs, err := t.client.ListGoroutines()
D
Dan Mace 已提交
251 252 253
	if err != nil {
		return err
	}
I
Ilia Choly 已提交
254
	sort.Sort(byGoroutineID(gs))
D
Dan Mace 已提交
255 256
	fmt.Printf("[%d goroutines]\n", len(gs))
	for _, g := range gs {
257
		prefix := "  "
258
		if state.SelectedGoroutine != nil && g.ID == state.SelectedGoroutine.ID {
259 260
			prefix = "* "
		}
261
		fmt.Printf("%sGoroutine %s\n", prefix, formatGoroutine(g, fgl))
262 263 264 265
	}
	return nil
}

266
func goroutine(t *Term, args ...string) error {
267 268
	switch len(args) {
	case 0:
269
		return printscope(t)
270 271 272 273 274 275 276

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

277
		oldState, err := t.client.GetState()
278 279 280
		if err != nil {
			return err
		}
281
		newState, err := t.client.SwitchGoroutine(gid)
282 283 284 285 286 287 288 289
		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:
290
		return scopePrefix(t, "goroutine", args...)
291 292 293
	}
}

294 295
func frame(t *Term, args ...string) error {
	return scopePrefix(t, "frame", args...)
296 297
}

298
func scopePrefix(t *Term, cmdname string, pargs ...string) error {
299 300 301 302 303 304 305 306
	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 {
307 308
		outfn := filterSortAndOutput(func(t *Term, filter string) ([]string, error) {
			return fn(t, scope, filter)
309
		})
310
		return outfn(t, fnargs...)
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
	}

	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++
336 337
		case "list", "ls":
			frame, gid := scope.Frame, scope.GoroutineID
338
			locs, err := t.client.Stacktrace(gid, frame, false)
339 340 341 342 343 344 345
			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]
346
			return printfile(t, loc.File, loc.Line, true)
347 348 349 350 351
		case "stack", "bt":
			depth, full, err := parseStackArgs(fullargs[i+1:])
			if err != nil {
				return err
			}
352
			stack, err := t.client.Stacktrace(scope.GoroutineID, depth, full)
353 354 355 356 357
			if err != nil {
				return err
			}
			printStack(stack, "")
			return nil
358 359 360 361 362
		case "locals":
			return callFilterSortAndOutput(locals, fullargs[i+1:])
		case "args":
			return callFilterSortAndOutput(args, fullargs[i+1:])
		case "print", "p":
363
			return printVar(t, scope, fullargs[i+1:]...)
364 365 366 367 368 369 370 371
		default:
			return fmt.Errorf("unknown command %s", fullargs[i])
		}
	}

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

372 373
func printscope(t *Term) error {
	state, err := t.client.GetState()
374 375
	if err != nil {
		return err
D
Dan Mace 已提交
376
	}
377

378 379 380 381
	fmt.Printf("Thread %s\n", formatThread(state.CurrentThread))
	if state.SelectedGoroutine != nil {
		writeGoroutineLong(os.Stdout, state.SelectedGoroutine, "")
	}
D
Dan Mace 已提交
382 383 384
	return nil
}

385 386 387 388 389 390 391
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)
}

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
type formatGoroutineLoc int

const (
	fglRuntimeCurrent = formatGoroutineLoc(iota)
	fglUserCurrent
	fglGo
)

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

func formatGoroutine(g *api.Goroutine, fgl formatGoroutineLoc) string {
409 410 411
	if g == nil {
		return "<nil>"
	}
412 413 414 415 416 417 418 419 420 421 422 423
	var locname string
	var loc api.Location
	switch fgl {
	case fglRuntimeCurrent:
		locname = "Runtime"
		loc = g.Current
	case fglUserCurrent:
		locname = "User"
		loc = g.UserCurrent
	case fglGo:
		locname = "Go"
		loc = g.Go
A
aarzilli 已提交
424
	}
425 426 427 428 429 430 431 432 433
	return fmt.Sprintf("%d - %s: %s", g.ID, locname, formatLocation(loc))
}

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,
		prefix, formatLocation(g.Current),
		prefix, formatLocation(g.UserCurrent),
		prefix, formatLocation(g.Go))
A
aarzilli 已提交
434 435
}

436 437
func restart(t *Term, args ...string) error {
	if err := t.client.Restart(); err != nil {
D
Derek Parker 已提交
438 439
		return err
	}
440
	fmt.Println("Process restarted with PID", t.client.ProcessPid())
D
Derek Parker 已提交
441 442 443
	return nil
}

444 445
func cont(t *Term, args ...string) error {
	stateChan := t.client.Continue()
D
Derek Parker 已提交
446
	for state := range stateChan {
A
aarzilli 已提交
447 448 449
		if state.Err != nil {
			return state.Err
		}
450
		printcontext(t, state)
D
Dan Mace 已提交
451 452 453 454
	}
	return nil
}

455 456
func step(t *Term, args ...string) error {
	state, err := t.client.Step()
D
Dan Mace 已提交
457 458 459
	if err != nil {
		return err
	}
460
	printcontext(t, state)
D
Dan Mace 已提交
461 462 463
	return nil
}

464 465
func next(t *Term, args ...string) error {
	state, err := t.client.Next()
D
Dan Mace 已提交
466 467 468
	if err != nil {
		return err
	}
469
	printcontext(t, state)
D
Dan Mace 已提交
470 471 472
	return nil
}

473
func clear(t *Term, args ...string) error {
D
Dan Mace 已提交
474
	if len(args) == 0 {
D
Derek Parker 已提交
475
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
476 477 478 479 480
	}
	id, err := strconv.Atoi(args[0])
	if err != nil {
		return err
	}
481
	bp, err := t.client.ClearBreakpoint(id)
D
Dan Mace 已提交
482 483 484
	if err != nil {
		return err
	}
485
	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 已提交
486 487 488
	return nil
}

489 490
func clearAll(t *Term, args ...string) error {
	breakPoints, err := t.client.ListBreakpoints()
D
Dan Mace 已提交
491 492 493
	if err != nil {
		return err
	}
494 495 496 497 498 499 500 501 502 503 504 505 506

	var locPCs map[uint64]struct{}
	if len(args) > 0 {
		locs, err := t.client.FindLocation(api.EvalScope{-1, 0}, args[0])
		if err != nil {
			return err
		}
		locPCs = make(map[uint64]struct{})
		for _, loc := range locs {
			locPCs[loc.PC] = struct{}{}
		}
	}

D
Dan Mace 已提交
507
	for _, bp := range breakPoints {
508 509 510 511 512 513
		if locPCs != nil {
			if _, ok := locPCs[bp.Addr]; !ok {
				continue
			}
		}

514
		_, err := t.client.ClearBreakpoint(bp.ID)
D
Dan Mace 已提交
515
		if err != nil {
516
			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 已提交
517
		}
518
		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 已提交
519 520 521 522
	}
	return nil
}

D
Derek Parker 已提交
523
type ById []*api.Breakpoint
D
Dan Mace 已提交
524 525 526 527 528

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 }

529 530
func breakpoints(t *Term, args ...string) error {
	breakPoints, err := t.client.ListBreakpoints()
D
Dan Mace 已提交
531 532 533 534 535
	if err != nil {
		return err
	}
	sort.Sort(ById(breakPoints))
	for _, bp := range breakPoints {
A
aarzilli 已提交
536 537 538 539
		thing := "Breakpoint"
		if bp.Tracepoint {
			thing = "Tracepoint"
		}
540
		fmt.Printf("%s %d at %#v %s:%d (%d)\n", thing, bp.ID, bp.Addr, shortenFilePath(bp.File), bp.Line, bp.TotalHitCount)
A
aarzilli 已提交
541 542 543 544 545 546 547 548 549

		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 已提交
550 551
		for i := range bp.Variables {
			attrs = append(attrs, bp.Variables[i])
A
aarzilli 已提交
552 553 554 555
		}
		if len(attrs) > 0 {
			fmt.Printf("\t%s\n", strings.Join(attrs, " "))
		}
D
Dan Mace 已提交
556 557 558 559
	}
	return nil
}

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

A
aarzilli 已提交
566 567 568 569 570 571 572 573 574 575 576 577
	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 已提交
578
			requestedBp.Variables = append(requestedBp.Variables, args[i])
A
aarzilli 已提交
579 580 581 582
		}
	}

	requestedBp.Tracepoint = tracepoint
583
	locs, err := t.client.FindLocation(api.EvalScope{-1, 0}, args[0])
D
Dan Mace 已提交
584 585 586
	if err != nil {
		return err
	}
A
aarzilli 已提交
587 588 589 590
	thing := "Breakpoint"
	if tracepoint {
		thing = "Tracepoint"
	}
591 592 593
	for _, loc := range locs {
		requestedBp.Addr = loc.PC

594
		bp, err := t.client.CreateBreakpoint(requestedBp)
595 596 597 598
		if err != nil {
			return err
		}

599
		fmt.Printf("%s %d set at %#v for %s %s:%d\n", thing, bp.ID, bp.Addr, bp.FunctionName, shortenFilePath(bp.File), bp.Line)
600
	}
D
Dan Mace 已提交
601 602 603
	return nil
}

604 605
func breakpoint(t *Term, args ...string) error {
	return setBreakpoint(t, false, args...)
A
aarzilli 已提交
606 607
}

608 609
func tracepoint(t *Term, args ...string) error {
	return setBreakpoint(t, true, args...)
A
aarzilli 已提交
610 611
}

612
func g0f0(fn scopedCmdfunc) cmdfunc {
613 614
	return func(t *Term, args ...string) error {
		return fn(t, api.EvalScope{-1, 0}, args...)
615 616 617 618
	}
}

func g0f0filter(fn scopedFilteringFunc) filteringFunc {
619 620
	return func(t *Term, filter string) ([]string, error) {
		return fn(t, api.EvalScope{-1, 0}, filter)
621 622 623
	}
}

624
func printVar(t *Term, scope api.EvalScope, args ...string) error {
D
Dan Mace 已提交
625
	if len(args) == 0 {
D
Derek Parker 已提交
626
		return fmt.Errorf("not enough arguments")
D
Dan Mace 已提交
627
	}
628
	val, err := t.client.EvalVariable(scope, args[0])
D
Dan Mace 已提交
629 630 631 632 633 634 635
	if err != nil {
		return err
	}
	fmt.Println(val.Value)
	return nil
}

636
func setVar(t *Term, scope api.EvalScope, args ...string) error {
637 638 639 640
	if len(args) != 2 {
		return fmt.Errorf("wrong number of arguments")
	}

641
	return t.client.SetVariable(scope, args[0], args[1])
642 643
}

D
Derek Parker 已提交
644 645 646 647 648 649
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 已提交
650 651
	data := make([]string, 0, len(vars))
	for _, v := range vars {
D
Derek Parker 已提交
652
		if reg == nil || reg.Match([]byte(v.Name)) {
D
Dan Mace 已提交
653 654 655 656 657 658
			data = append(data, fmt.Sprintf("%s = %s", v.Name, v.Value))
		}
	}
	return data
}

659 660
func sources(t *Term, filter string) ([]string, error) {
	return t.client.ListSources(filter)
D
Derek Parker 已提交
661
}
D
Dan Mace 已提交
662

663 664
func funcs(t *Term, filter string) ([]string, error) {
	return t.client.ListFunctions(filter)
D
Derek Parker 已提交
665
}
D
Dan Mace 已提交
666

667 668
func args(t *Term, scope api.EvalScope, filter string) ([]string, error) {
	vars, err := t.client.ListFunctionArgs(scope)
D
Derek Parker 已提交
669 670 671 672 673
	if err != nil {
		return nil, err
	}
	return filterVariables(vars, filter), nil
}
D
Dan Mace 已提交
674

675 676
func locals(t *Term, scope api.EvalScope, filter string) ([]string, error) {
	locals, err := t.client.ListLocalVariables(scope)
D
Derek Parker 已提交
677 678 679 680 681
	if err != nil {
		return nil, err
	}
	return filterVariables(locals, filter), nil
}
D
Dan Mace 已提交
682

683 684
func vars(t *Term, filter string) ([]string, error) {
	vars, err := t.client.ListPackageVariables(filter)
D
Derek Parker 已提交
685 686 687 688 689
	if err != nil {
		return nil, err
	}
	return filterVariables(vars, filter), nil
}
D
Dan Mace 已提交
690

691 692
func regs(t *Term, args ...string) error {
	regs, err := t.client.ListRegisters()
D
Derek Parker 已提交
693 694 695 696 697 698
	if err != nil {
		return err
	}
	fmt.Println(regs)
	return nil
}
699

700
func filterSortAndOutput(fn filteringFunc) cmdfunc {
701
	return func(t *Term, args ...string) error {
D
Derek Parker 已提交
702 703 704 705 706 707
		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 已提交
708
		}
709
		data, err := fn(t, filter)
D
Dan Mace 已提交
710 711 712
		if err != nil {
			return err
		}
D
Derek Parker 已提交
713 714 715
		sort.Sort(sort.StringSlice(data))
		for _, d := range data {
			fmt.Println(d)
D
Dan Mace 已提交
716
		}
D
Derek Parker 已提交
717
		return nil
D
Dan Mace 已提交
718 719 720
	}
}

721
func stackCommand(t *Term, args ...string) error {
722 723 724 725 726 727 728 729
	var (
		err         error
		goroutineid = -1
	)
	depth, full, err := parseStackArgs(args)
	if err != nil {
		return err
	}
730
	stack, err := t.client.Stacktrace(goroutineid, depth, full)
731 732 733 734 735 736
	if err != nil {
		return err
	}
	printStack(stack, "")
	return nil
}
A
aarzilli 已提交
737

738 739 740 741 742
func parseStackArgs(args []string) (int, bool, error) {
	var (
		depth = 10
		full  = false
	)
743 744 745 746 747 748
	for i := range args {
		if args[i] == "-full" {
			full = true
		} else {
			n, err := strconv.Atoi(args[i])
			if err != nil {
749
				return 0, false, fmt.Errorf("depth must be a number")
750
			}
751
			depth = n
A
aarzilli 已提交
752 753
		}
	}
754
	return depth, full, nil
A
aarzilli 已提交
755 756
}

757
func listCommand(t *Term, args ...string) error {
758
	if len(args) == 0 {
759
		state, err := t.client.GetState()
760 761 762
		if err != nil {
			return err
		}
763
		printcontext(t, state)
764 765 766
		return nil
	}

767
	locs, err := t.client.FindLocation(api.EvalScope{-1, 0}, args[0])
768 769 770 771 772 773
	if err != nil {
		return err
	}
	if len(locs) > 1 {
		return debugger.AmbiguousLocationError{Location: args[0], CandidatesLocation: locs}
	}
774
	printfile(t, locs[0].File, locs[0].Line, false)
775 776 777
	return nil
}

778 779 780 781 782 783 784 785
func (cmds *Commands) sourceCommand(t *Term, args ...string) error {
	if len(args) != 1 {
		return fmt.Errorf("wrong number of arguments: source <filename>")
	}

	return cmds.executeFile(t, args[0])
}

786 787 788 789 790 791 792
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"
793
	s := strings.Repeat(" ", d+2+len(ind))
794

A
aarzilli 已提交
795 796 797 798 799
	for i := range stack {
		name := "(nil)"
		if stack[i].Function != nil {
			name = stack[i].Function.Name
		}
800 801 802 803 804 805 806 807 808
		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 已提交
809 810 811
	}
}

812
func printcontext(t *Term, state *api.DebuggerState) error {
D
Dan Mace 已提交
813 814 815 816 817 818
	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)
819
		t.Println("=>", "no source available")
D
Dan Mace 已提交
820 821
		return nil
	}
D
Derek Parker 已提交
822
	var fn *api.Function
D
Dan Mace 已提交
823
	if state.CurrentThread.Function != nil {
D
Derek Parker 已提交
824 825
		fn = state.CurrentThread.Function
	}
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

	if state.Breakpoint != nil {
		args := ""
		if state.Breakpoint.Tracepoint {
			var arg []string
			for _, ar := range state.CurrentThread.Function.Args {
				arg = append(arg, ar.Value)
			}
			args = strings.Join(arg, ", ")
		}

		if hitCount, ok := state.Breakpoint.HitCount[strconv.Itoa(state.SelectedGoroutine.ID)]; ok {
			fmt.Printf("> %s(%s) %s:%d (hits goroutine(%d):%d total:%d)\n",
				fn.Name,
				args,
				shortenFilePath(state.CurrentThread.File),
				state.CurrentThread.Line,
				state.SelectedGoroutine.ID,
				hitCount,
				state.Breakpoint.TotalHitCount)
		} else {
			fmt.Printf("> %s(%s) %s:%d (hits total:%d)\n",
				fn.Name,
				args,
				shortenFilePath(state.CurrentThread.File),
				state.CurrentThread.Line,
				state.Breakpoint.TotalHitCount)
D
Derek Parker 已提交
853 854
		}
	} else {
855
		fmt.Printf("> %s() %s:%d\n", fn.Name, shortenFilePath(state.CurrentThread.File), state.CurrentThread.Line)
D
Dan Mace 已提交
856 857
	}

A
aarzilli 已提交
858 859 860 861
	if state.BreakpointInfo != nil {
		bpi := state.BreakpointInfo

		if bpi.Goroutine != nil {
862
			writeGoroutineLong(os.Stdout, bpi.Goroutine, "\t")
A
aarzilli 已提交
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
		}

		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
	}
879
	return printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
880 881
}

882
func printfile(t *Term, filename string, line int, showArrow bool) error {
883
	file, err := os.Open(filename)
D
Dan Mace 已提交
884 885 886 887 888
	if err != nil {
		return err
	}
	defer file.Close()

889
	buf := bufio.NewScanner(file)
890
	l := line
D
Dan Mace 已提交
891
	for i := 1; i < l-5; i++ {
892 893
		if !buf.Scan() {
			return nil
D
Dan Mace 已提交
894 895 896
		}
	}

897 898 899 900 901 902
	s := l - 5
	if s < 1 {
		s = 1
	}

	for i := s; i <= l+5; i++ {
903 904
		if !buf.Scan() {
			return nil
D
Dan Mace 已提交
905 906
		}

907
		var prefix string
908
		if showArrow {
909
			prefix = "  "
910
			if i == l {
911
				prefix = "=>"
912
			}
D
Dan Mace 已提交
913 914
		}

915 916
		prefix = fmt.Sprintf("%s%4d:\t", prefix, i)
		t.Println(prefix, buf.Text())
D
Dan Mace 已提交
917 918 919
	}
	return nil
}
D
Derek Parker 已提交
920 921 922 923 924 925 926

type ExitRequestError struct{}

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

927
func exitCommand(t *Term, args ...string) error {
D
Derek Parker 已提交
928 929
	return ExitRequestError{}
}
930 931 932 933 934

func shortenFilePath(fullPath string) string {
	workingDir, _ := os.Getwd()
	return strings.Replace(fullPath, workingDir, ".", 1)
}
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963

func (cmds *Commands) executeFile(t *Term, name string) error {
	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)
		cmd := cmds.Find(cmdstr)
		err := cmd(t, args...)

		if err != nil {
			fmt.Printf("%s:%d: %v\n", name, lineno, err)
		}
	}

	return scanner.Err()
}