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

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

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

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

41
// Returns a Commands struct with default commands defined.
D
Derek Parker 已提交
42
func DebugCommands() *Commands {
J
Jason Del Ponte 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
	c := &Commands{}

	c.cmds = []command{
		command{aliases: []string{"help"}, cmdFn: c.help, helpMsg: "help - Prints the help message."},
		command{aliases: []string{"break", "b"}, cmdFn: breakpoint, helpMsg: "break|b - 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: "continue|c - Run until breakpoint or program termination."},
		command{aliases: []string{"step", "si"}, cmdFn: step, helpMsg: "step|si - Single step through program."},
		command{aliases: []string{"next", "n"}, cmdFn: next, helpMsg: "next|n - Step over to next source line."},
		command{aliases: []string{"threads"}, cmdFn: threads, helpMsg: "threads - Print out info for every traced thread."},
		command{aliases: []string{"clear"}, cmdFn: clear, helpMsg: "clear - Deletes breakpoint."},
		command{aliases: []string{"goroutines"}, cmdFn: goroutines, helpMsg: "goroutines - Print out info for every goroutine."},
		command{aliases: []string{"print", "p"}, cmdFn: printVar, helpMsg: "print|p $var - Evaluate a variable."},
		command{aliases: []string{"exit"}, cmdFn: nullCommand, helpMsg: "exit - Exit the debugger."},
D
Derek Parker 已提交
56 57
	}

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

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

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

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

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

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

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

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

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

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

122 123 124 125
func goroutines(p *proctl.DebuggedProcess, ars ...string) error {
	return p.PrintGoroutinesInfo()
}

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

132 133 134 135 136
	return printcontext(p)
}

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

141
	return printcontext(p)
142 143
}

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

150
	return printcontext(p)
D
Derek Parker 已提交
151 152
}

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

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
	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
188 189
	}

190
	bp, err := p.Clear(pc)
191 192 193 194 195 196 197 198 199
	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 已提交
200
func breakpoint(p *proctl.DebuggedProcess, args ...string) error {
201 202 203 204
	if len(args) == 0 {
		return fmt.Errorf("not enough arguments")
	}

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
	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)
230 231 232
		if fn == nil {
			return fmt.Errorf("No function named %s", fname)
		}
233

234
		pc = fn.Entry
235 236 237 238 239 240 241 242 243
	}

	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)

244 245
	return nil
}
246

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

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

	fmt.Println(val.Value)
	return nil
}

261 262 263 264 265 266 267 268
func printcontext(p *proctl.DebuggedProcess) error {
	var context []string

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

269
	f, l, fn := p.GoSymTable.PCToLine(regs.PC())
270

271 272 273 274
	if fn != nil {
		fmt.Printf("Stopped at: %s:%d\n", f, l)
		file, err := os.Open(f)
		if err != nil {
275 276
			return err
		}
277
		defer file.Close()
278

279 280 281 282
		buf := bufio.NewReader(file)
		for i := 1; i < l-5; i++ {
			_, err := buf.ReadString('\n')
			if err != nil && err != io.EOF {
D
Derek Parker 已提交
283
				return err
284
			}
285 286 287 288 289 290 291 292
		}

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

294 295 296
				if err == io.EOF {
					break
				}
D
Derek Parker 已提交
297 298
			}

299 300 301
			if i == l {
				line = "\033[34m=>\033[0m" + line
			}
D
Derek Parker 已提交
302

303 304 305 306 307
			context = append(context, fmt.Sprintf("\033[34m%d\033[0m: %s", i, line))
		}
	} else {
		fmt.Printf("Stopped at: 0x%x\n", regs.PC())
		context = append(context, "\033[34m=>\033[0m    no source available")
308 309
	}

D
Derek Parker 已提交
310
	fmt.Println(strings.Join(context, ""))
311 312 313

	return nil
}