command.go 8.7 KB
Newer Older
D
Derek Parker 已提交
1 2
// Package command implements functions for responding to user
// input and dispatching to appropriate backend commands.
D
Derek Parker 已提交
3 4 5
package command

import (
6
	"bufio"
D
Derek Parker 已提交
7
	"fmt"
8 9
	"io"
	"os"
E
epipho 已提交
10 11
	"regexp"
	"sort"
12 13
	"strings"

D
Derek Parker 已提交
14
	"github.com/derekparker/delve/proctl"
D
Derek Parker 已提交
15 16
)

17
type cmdfunc func(proc *proctl.DebuggedProcess, args ...string) error
D
Derek Parker 已提交
18

J
Jason Del Ponte 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
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
}

D
Derek Parker 已提交
35
type Commands struct {
J
Jason Del Ponte 已提交
36 37
	cmds    []command
	lastCmd cmdfunc
D
Derek Parker 已提交
38 39
}

40
// Returns a Commands struct with default commands defined.
D
Derek Parker 已提交
41
func DebugCommands() *Commands {
J
Jason Del Ponte 已提交
42 43 44
	c := &Commands{}

	c.cmds = []command{
J
Jason Del Ponte 已提交
45 46 47 48 49 50 51 52
		command{aliases: []string{"help"}, cmdFn: c.help, helpMsg: "Prints the help message."},
		command{aliases: []string{"break", "b"}, cmdFn: breakpoint, helpMsg: "Set break point at the entry point of a function, or at a specific file/line. Example: break foo.go:13"},
		command{aliases: []string{"continue", "c"}, cmdFn: cont, helpMsg: "Run until breakpoint or program termination."},
		command{aliases: []string{"step", "si"}, cmdFn: step, helpMsg: "Single step through program."},
		command{aliases: []string{"next", "n"}, cmdFn: next, helpMsg: "Step over to next source line."},
		command{aliases: []string{"threads"}, cmdFn: threads, helpMsg: "Print out info for every traced thread."},
		command{aliases: []string{"clear"}, cmdFn: clear, helpMsg: "Deletes breakpoint."},
		command{aliases: []string{"goroutines"}, cmdFn: goroutines, helpMsg: "Print out info for every goroutine."},
53
		command{aliases: []string{"breakpoints", "bp"}, cmdFn: breakpoints, helpMsg: "Print out info for active breakpoints."},
J
Jason Del Ponte 已提交
54
		command{aliases: []string{"print", "p"}, cmdFn: printVar, helpMsg: "Evaluate a variable."},
55
		command{aliases: []string{"info"}, cmdFn: info, helpMsg: "Provides info about args, funcs, locals, sources, or vars."},
J
Jason Del Ponte 已提交
56
		command{aliases: []string{"exit"}, cmdFn: nullCommand, helpMsg: "Exit the debugger."},
D
Derek Parker 已提交
57 58
	}

J
Jason Del Ponte 已提交
59
	return c
D
Derek Parker 已提交
60 61
}

D
Derek Parker 已提交
62 63
// Register custom commands. Expects cf to be a func of type cmdfunc,
// returning only an error.
J
Jason Del Ponte 已提交
64 65 66 67 68 69 70 71 72
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})
D
Derek Parker 已提交
73 74
}

75 76 77
// 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.
D
Derek Parker 已提交
78
func (c *Commands) Find(cmdstr string) cmdfunc {
J
Jason Del Ponte 已提交
79 80 81 82 83 84
	// If <enter> use last command, if there was one.
	if cmdstr == "" {
		if c.lastCmd != nil {
			return c.lastCmd
		}
		return nullCommand
D
Derek Parker 已提交
85 86
	}

J
Jason Del Ponte 已提交
87 88 89 90 91 92
	for _, v := range c.cmds {
		if v.match(cmdstr) {
			c.lastCmd = v.cmdFn
			return v.cmdFn
		}
	}
93

J
Jason Del Ponte 已提交
94
	return noCmdAvailable
D
Derek Parker 已提交
95 96
}

D
Derek Parker 已提交
97
func CommandFunc(fn func() error) cmdfunc {
98
	return func(p *proctl.DebuggedProcess, args ...string) error {
D
Derek Parker 已提交
99 100 101 102
		return fn()
	}
}

103
func noCmdAvailable(p *proctl.DebuggedProcess, ars ...string) error {
D
Derek Parker 已提交
104 105 106
	return fmt.Errorf("command not available")
}

107 108 109 110
func nullCommand(p *proctl.DebuggedProcess, ars ...string) error {
	return nil
}

J
Jason Del Ponte 已提交
111 112 113
func (c *Commands) help(p *proctl.DebuggedProcess, ars ...string) error {
	fmt.Println("The following commands are available:")
	for _, cmd := range c.cmds {
J
Jason Del Ponte 已提交
114
		fmt.Printf("\t%s - %s\n", strings.Join(cmd.aliases, "|"), cmd.helpMsg)
J
Jason Del Ponte 已提交
115
	}
D
Derek Parker 已提交
116 117
	return nil
}
118 119

func threads(p *proctl.DebuggedProcess, ars ...string) error {
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
	for _, th := range p.Threads {
		prefix := "  "
		if th == p.CurrentThread {
			prefix = "* "
		}
		pc, err := th.CurrentPC()
		if err != nil {
			return err
		}
		f, l, fn := th.Process.GoSymTable.PCToLine(pc)
		if fn != nil {
			fmt.Printf("%sThread %d at %#v %s:%d %s\n", prefix, th.Id, pc, f, l, fn.Name)
		} else {
			fmt.Printf("%sThread %d at %#v\n", prefix, th.Id, pc)
		}
	}
	return nil
137 138
}

139 140 141 142
func goroutines(p *proctl.DebuggedProcess, ars ...string) error {
	return p.PrintGoroutinesInfo()
}

143
func cont(p *proctl.DebuggedProcess, ars ...string) error {
144
	err := p.Continue()
145 146 147 148
	if err != nil {
		return err
	}

149 150 151 152 153
	return printcontext(p)
}

func step(p *proctl.DebuggedProcess, args ...string) error {
	err := p.Step()
154 155 156 157
	if err != nil {
		return err
	}

158
	return printcontext(p)
159 160
}

D
Derek Parker 已提交
161 162 163 164 165 166
func next(p *proctl.DebuggedProcess, args ...string) error {
	err := p.Next()
	if err != nil {
		return err
	}

167
	return printcontext(p)
D
Derek Parker 已提交
168 169
}

170
func clear(p *proctl.DebuggedProcess, args ...string) error {
171 172 173 174
	if len(args) == 0 {
		return fmt.Errorf("not enough arguments")
	}

175
	bp, err := p.ClearByLocation(args[0])
176 177 178 179
	if err != nil {
		return err
	}

180
	fmt.Printf("Breakpoint %d cleared at %#v for %s %s:%d\n", bp.ID, bp.Addr, bp.FunctionName, bp.File, bp.Line)
181 182 183 184

	return nil
}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
type ById []*proctl.BreakPoint

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(p *proctl.DebuggedProcess, args ...string) error {
	bps := make([]*proctl.BreakPoint, 0, len(p.BreakPoints)+4)

	for _, bp := range p.HWBreakPoints {
		if bp == nil {
			continue
		}
		bps = append(bps, bp)
	}

	for _, bp := range p.BreakPoints {
		if bp.Temp {
			continue
		}
		bps = append(bps, bp)
	}

	sort.Sort(ById(bps))
	for _, bp := range bps {
		fmt.Println(bp)
	}

	return nil
}

D
Derek Parker 已提交
216
func breakpoint(p *proctl.DebuggedProcess, args ...string) error {
217 218 219 220
	if len(args) == 0 {
		return fmt.Errorf("not enough arguments")
	}

221
	bp, err := p.BreakByLocation(args[0])
222 223 224 225
	if err != nil {
		return err
	}

226
	fmt.Printf("Breakpoint %d set at %#v for %s %s:%d\n", bp.ID, bp.Addr, bp.FunctionName, bp.File, bp.Line)
227

228 229
	return nil
}
230

D
Derek Parker 已提交
231
func printVar(p *proctl.DebuggedProcess, args ...string) error {
232
	if len(args) == 0 {
233
		return fmt.Errorf("not enough arguments")
234 235
	}

D
Derek Parker 已提交
236 237 238 239 240 241 242
	val, err := p.EvalSymbol(args[0])
	if err != nil {
		return err
	}

	fmt.Println(val.Value)
	return nil
E
epipho 已提交
243 244
}

E
epipho 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257
func filterVariables(vars []*proctl.Variable, filter *regexp.Regexp) []string {
	data := make([]string, 0, len(vars))
	for _, v := range vars {
		if v == nil {
			continue
		}
		if filter == nil || filter.Match([]byte(v.Name)) {
			data = append(data, fmt.Sprintf("%s = %s", v.Name, v.Value))
		}
	}
	return data
}

E
epipho 已提交
258 259
func info(p *proctl.DebuggedProcess, args ...string) error {
	if len(args) == 0 {
E
epipho 已提交
260
		return fmt.Errorf("not enough arguments. expected info type [regex].")
E
epipho 已提交
261 262 263 264 265 266 267 268 269 270 271
	}

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

E
epipho 已提交
272 273
	var data []string

E
epipho 已提交
274 275
	switch args[0] {
	case "sources":
E
epipho 已提交
276
		data = make([]string, 0, len(p.GoSymTable.Files))
E
epipho 已提交
277 278
		for f := range p.GoSymTable.Files {
			if filter == nil || filter.Match([]byte(f)) {
E
epipho 已提交
279
				data = append(data, f)
E
epipho 已提交
280 281 282
			}
		}

D
Derek Parker 已提交
283
	case "funcs":
E
epipho 已提交
284 285 286 287 288
		data = make([]string, 0, len(p.GoSymTable.Funcs))
		for _, f := range p.GoSymTable.Funcs {
			if f.Sym != nil && (filter == nil || filter.Match([]byte(f.Name))) {
				data = append(data, f.Name)
			}
E
epipho 已提交
289 290
		}

E
epipho 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304
	case "args":
		vars, err := p.CurrentThread.FunctionArguments()
		if err != nil {
			return nil
		}
		data = filterVariables(vars, filter)

	case "locals":
		vars, err := p.CurrentThread.LocalVariables()
		if err != nil {
			return nil
		}
		data = filterVariables(vars, filter)

305 306 307 308 309 310 311
	case "vars":
		vars, err := p.CurrentThread.PackageVariables()
		if err != nil {
			return nil
		}
		data = filterVariables(vars, filter)

E
epipho 已提交
312
	default:
313
		return fmt.Errorf("unsupported info type, must be args, funcs, locals, sources, or vars")
E
epipho 已提交
314 315 316 317 318 319
	}

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

	for _, d := range data {
E
epipho 已提交
320
		fmt.Println(d)
E
epipho 已提交
321 322 323
	}

	return nil
D
Derek Parker 已提交
324 325
}

326 327 328 329 330 331 332 333
func printcontext(p *proctl.DebuggedProcess) error {
	var context []string

	regs, err := p.Registers()
	if err != nil {
		return err
	}

334
	f, l, fn := p.GoSymTable.PCToLine(regs.PC())
335

336
	if fn != nil {
D
Derek Parker 已提交
337
		fmt.Printf("current loc: %s %s:%d\n", fn.Name, f, l)
338 339
		file, err := os.Open(f)
		if err != nil {
340 341
			return err
		}
342
		defer file.Close()
343

344 345 346 347
		buf := bufio.NewReader(file)
		for i := 1; i < l-5; i++ {
			_, err := buf.ReadString('\n')
			if err != nil && err != io.EOF {
D
Derek Parker 已提交
348
				return err
349
			}
350 351 352 353 354 355 356 357
		}

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

359 360 361
				if err == io.EOF {
					break
				}
D
Derek Parker 已提交
362 363
			}

D
Derek Parker 已提交
364
			arrow := "  "
365
			if i == l {
D
Derek Parker 已提交
366
				arrow = "=>"
367
			}
D
Derek Parker 已提交
368

D
Derek Parker 已提交
369
			context = append(context, fmt.Sprintf("\033[34m%s %d\033[0m: %s", arrow, i, line))
370 371 372 373
		}
	} else {
		fmt.Printf("Stopped at: 0x%x\n", regs.PC())
		context = append(context, "\033[34m=>\033[0m    no source available")
374 375
	}

D
Derek Parker 已提交
376
	fmt.Println(strings.Join(context, ""))
377 378 379

	return nil
}