command.go 7.8 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"
7
	"debug/gosym"
D
Derek Parker 已提交
8
	"fmt"
9 10
	"io"
	"os"
11
	"path/filepath"
E
epipho 已提交
12 13
	"regexp"
	"sort"
14 15 16
	"strconv"
	"strings"

D
Derek Parker 已提交
17
	"github.com/derekparker/delve/proctl"
D
Derek Parker 已提交
18 19
)

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

J
Jason Del Ponte 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
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 已提交
38
type Commands struct {
J
Jason Del Ponte 已提交
39 40
	cmds    []command
	lastCmd cmdfunc
D
Derek Parker 已提交
41 42
}

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

	c.cmds = []command{
J
Jason Del Ponte 已提交
48 49 50 51 52 53 54 55 56
		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."},
		command{aliases: []string{"print", "p"}, cmdFn: printVar, helpMsg: "Evaluate a variable."},
E
epipho 已提交
57
		command{aliases: []string{"info"}, cmdFn: info, helpMsg: "Provides list of source files with symbols."},
J
Jason Del Ponte 已提交
58
		command{aliases: []string{"exit"}, cmdFn: nullCommand, helpMsg: "Exit the debugger."},
D
Derek Parker 已提交
59 60
	}

J
Jason Del Ponte 已提交
61
	return c
D
Derek Parker 已提交
62 63
}

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

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

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

J
Jason Del Ponte 已提交
96
	return noCmdAvailable
D
Derek Parker 已提交
97 98
}

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

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

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

J
Jason Del Ponte 已提交
113 114 115
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 已提交
116
		fmt.Printf("\t%s - %s\n", strings.Join(cmd.aliases, "|"), cmd.helpMsg)
J
Jason Del Ponte 已提交
117
	}
D
Derek Parker 已提交
118 119
	return nil
}
120 121 122 123 124

func threads(p *proctl.DebuggedProcess, ars ...string) error {
	return p.PrintThreadInfo()
}

125 126 127 128
func goroutines(p *proctl.DebuggedProcess, ars ...string) error {
	return p.PrintGoroutinesInfo()
}

129
func cont(p *proctl.DebuggedProcess, ars ...string) error {
130
	err := p.Continue()
131 132 133 134
	if err != nil {
		return err
	}

135 136 137 138 139
	return printcontext(p)
}

func step(p *proctl.DebuggedProcess, args ...string) error {
	err := p.Step()
140 141 142 143
	if err != nil {
		return err
	}

144
	return printcontext(p)
145 146
}

D
Derek Parker 已提交
147 148 149 150 151 152
func next(p *proctl.DebuggedProcess, args ...string) error {
	err := p.Next()
	if err != nil {
		return err
	}

153
	return printcontext(p)
D
Derek Parker 已提交
154 155
}

156
func clear(p *proctl.DebuggedProcess, args ...string) error {
157 158 159 160
	if len(args) == 0 {
		return fmt.Errorf("not enough arguments")
	}

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 190
	var (
		fn    *gosym.Func
		pc    uint64
		fname = args[0]
	)

	if strings.ContainsRune(fname, ':') {
		fl := strings.Split(fname, ":")

		f, err := filepath.Abs(fl[0])
		if err != nil {
			return err
		}

		l, err := strconv.Atoi(fl[1])
		if err != nil {
			return err
		}

		pc, fn, err = p.GoSymTable.LineToPC(f, l)
		if err != nil {
			return err
		}
	} else {
		fn = p.GoSymTable.LookupFunc(fname)
		if fn == nil {
			return fmt.Errorf("No function named %s", fname)
		}

		pc = fn.Entry
191 192
	}

193
	bp, err := p.Clear(pc)
194 195 196 197 198 199 200 201 202
	if err != nil {
		return err
	}

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

	return nil
}

D
Derek Parker 已提交
203
func breakpoint(p *proctl.DebuggedProcess, args ...string) error {
204 205 206 207
	if len(args) == 0 {
		return fmt.Errorf("not enough arguments")
	}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	var (
		fn    *gosym.Func
		pc    uint64
		fname = args[0]
	)

	if strings.ContainsRune(fname, ':') {
		fl := strings.Split(fname, ":")

		f, err := filepath.Abs(fl[0])
		if err != nil {
			return err
		}

		l, err := strconv.Atoi(fl[1])
		if err != nil {
			return err
		}

		pc, fn, err = p.GoSymTable.LineToPC(f, l)
		if err != nil {
			return err
		}
	} else {
		fn = p.GoSymTable.LookupFunc(fname)
233 234 235
		if fn == nil {
			return fmt.Errorf("No function named %s", fname)
		}
236

237
		pc = fn.Entry
238 239 240 241 242 243 244 245 246
	}

	bp, err := p.Break(uintptr(pc))
	if err != nil {
		return err
	}

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

247 248
	return nil
}
249

D
Derek Parker 已提交
250
func printVar(p *proctl.DebuggedProcess, args ...string) error {
251
	if len(args) == 0 {
252
		return fmt.Errorf("not enough arguments")
253 254
	}

D
Derek Parker 已提交
255 256 257 258 259 260 261
	val, err := p.EvalSymbol(args[0])
	if err != nil {
		return err
	}

	fmt.Println(val.Value)
	return nil
E
epipho 已提交
262 263 264 265
}

func info(p *proctl.DebuggedProcess, args ...string) error {
	if len(args) == 0 {
E
epipho 已提交
266
		return fmt.Errorf("not enough arguments. expected info type [regex].")
E
epipho 已提交
267 268 269 270 271 272 273 274 275 276 277
	}

	// 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 已提交
278 279
	var data []string

E
epipho 已提交
280 281
	switch args[0] {
	case "sources":
E
epipho 已提交
282
		data = make([]string, 0, len(p.GoSymTable.Files))
E
epipho 已提交
283 284
		for f := range p.GoSymTable.Files {
			if filter == nil || filter.Match([]byte(f)) {
E
epipho 已提交
285
				data = append(data, f)
E
epipho 已提交
286 287 288
			}
		}

D
Derek Parker 已提交
289
	case "funcs":
E
epipho 已提交
290 291 292 293 294
		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 已提交
295 296 297
		}

	default:
E
epipho 已提交
298 299 300 301 302 303 304
		return fmt.Errorf("unsupported info type, must be sources or functions")
	}

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

	for _, d := range data {
E
epipho 已提交
305
		fmt.Println(d)
E
epipho 已提交
306 307 308
	}

	return nil
D
Derek Parker 已提交
309 310
}

311 312 313 314 315 316 317 318
func printcontext(p *proctl.DebuggedProcess) error {
	var context []string

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

319
	f, l, fn := p.GoSymTable.PCToLine(regs.PC())
320

321
	if fn != nil {
D
Derek Parker 已提交
322
		fmt.Printf("current loc: %s %s:%d\n", fn.Name, f, l)
323 324
		file, err := os.Open(f)
		if err != nil {
325 326
			return err
		}
327
		defer file.Close()
328

329 330 331 332
		buf := bufio.NewReader(file)
		for i := 1; i < l-5; i++ {
			_, err := buf.ReadString('\n')
			if err != nil && err != io.EOF {
D
Derek Parker 已提交
333
				return err
334
			}
335 336 337 338 339 340 341 342
		}

		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 已提交
343

344 345 346
				if err == io.EOF {
					break
				}
D
Derek Parker 已提交
347 348
			}

D
Derek Parker 已提交
349
			arrow := "  "
350
			if i == l {
D
Derek Parker 已提交
351
				arrow = "=>"
352
			}
D
Derek Parker 已提交
353

D
Derek Parker 已提交
354
			context = append(context, fmt.Sprintf("\033[34m%s %d\033[0m: %s", arrow, i, line))
355 356 357 358
		}
	} else {
		fmt.Printf("Stopped at: 0x%x\n", regs.PC())
		context = append(context, "\033[34m=>\033[0m    no source available")
359 360
	}

D
Derek Parker 已提交
361
	fmt.Println(strings.Join(context, ""))
362 363 364

	return nil
}