1
0
mirror of https://github.com/beego/bee.git synced 2024-11-15 03:20:54 +00:00
bee/vendor/github.com/derekparker/delve/service/debugger/debugger.go

1109 lines
30 KiB
Go
Raw Normal View History

2017-03-19 22:45:54 +00:00
package debugger
import (
2018-10-13 13:45:53 +00:00
"debug/dwarf"
2017-03-19 22:45:54 +00:00
"errors"
"fmt"
"go/parser"
2018-10-13 13:45:53 +00:00
"io/ioutil"
2017-03-19 22:45:54 +00:00
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
2018-10-13 13:45:53 +00:00
"github.com/derekparker/delve/pkg/goversion"
"github.com/derekparker/delve/pkg/logflags"
"github.com/derekparker/delve/pkg/proc"
"github.com/derekparker/delve/pkg/proc/core"
"github.com/derekparker/delve/pkg/proc/gdbserial"
"github.com/derekparker/delve/pkg/proc/native"
2017-03-19 22:45:54 +00:00
"github.com/derekparker/delve/service/api"
2018-10-13 13:45:53 +00:00
"github.com/sirupsen/logrus"
2017-03-19 22:45:54 +00:00
)
// Debugger service.
//
// Debugger provides a higher level of
// abstraction over proc.Process.
// It handles converting from internal types to
// the types expected by clients. It also handles
// functionality needed by clients, but not needed in
// lower lever packages such as proc.
type Debugger struct {
2018-10-13 13:45:53 +00:00
config *Config
// arguments to launch a new process.
processArgs []string
// TODO(DO NOT MERGE WITHOUT) rename to targetMutex
2017-03-19 22:45:54 +00:00
processMutex sync.Mutex
2018-10-13 13:45:53 +00:00
target proc.Process
log *logrus.Entry
running bool
runningMutex sync.Mutex
2017-03-19 22:45:54 +00:00
}
// Config provides the configuration to start a Debugger.
//
// Only one of ProcessArgs or AttachPid should be specified. If ProcessArgs is
// provided, a new process will be launched. Otherwise, the debugger will try
// to attach to an existing process with AttachPid.
type Config struct {
// WorkingDir is working directory of the new process. This field is used
// only when launching a new process.
WorkingDir string
// AttachPid is the PID of an existing process to which the debugger should
// attach.
AttachPid int
2018-10-13 13:45:53 +00:00
// CoreFile specifies the path to the core dump to open.
CoreFile string
// Backend specifies the debugger backend.
Backend string
// Foreground lets target process access stdin.
Foreground bool
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
// New creates a new Debugger. ProcessArgs specify the commandline arguments for the
// new process.
func New(config *Config, processArgs []string) (*Debugger, error) {
logger := logrus.New().WithFields(logrus.Fields{"layer": "debugger"})
logger.Logger.Level = logrus.DebugLevel
if !logflags.Debugger() {
logger.Logger.Out = ioutil.Discard
}
2017-03-19 22:45:54 +00:00
d := &Debugger{
2018-10-13 13:45:53 +00:00
config: config,
processArgs: processArgs,
log: logger,
2017-03-19 22:45:54 +00:00
}
// Create the process by either attaching or launching.
2018-10-13 13:45:53 +00:00
switch {
case d.config.AttachPid > 0:
d.log.Infof("attaching to pid %d", d.config.AttachPid)
path := ""
if len(d.processArgs) > 0 {
path = d.processArgs[0]
}
p, err := d.Attach(d.config.AttachPid, path)
2017-03-19 22:45:54 +00:00
if err != nil {
2018-10-13 13:45:53 +00:00
err = go11DecodeErrorCheck(err)
2017-03-19 22:45:54 +00:00
return nil, attachErrorMessage(d.config.AttachPid, err)
}
2018-10-13 13:45:53 +00:00
d.target = p
case d.config.CoreFile != "":
var p proc.Process
var err error
switch d.config.Backend {
case "rr":
d.log.Infof("opening trace %s", d.config.CoreFile)
p, err = gdbserial.Replay(d.config.CoreFile, false)
default:
d.log.Infof("opening core file %s (executable %s)", d.config.CoreFile, d.processArgs[0])
p, err = core.OpenCore(d.config.CoreFile, d.processArgs[0])
}
2017-03-19 22:45:54 +00:00
if err != nil {
2018-10-13 13:45:53 +00:00
err = go11DecodeErrorCheck(err)
return nil, err
}
d.target = p
default:
d.log.Infof("launching process with args: %v", d.processArgs)
p, err := d.Launch(d.processArgs, d.config.WorkingDir)
if err != nil {
if err != proc.ErrNotExecutable && err != proc.ErrUnsupportedLinuxArch && err != proc.ErrUnsupportedWindowsArch && err != proc.ErrUnsupportedDarwinArch {
err = go11DecodeErrorCheck(err)
2017-03-19 22:45:54 +00:00
err = fmt.Errorf("could not launch process: %s", err)
}
return nil, err
}
2018-10-13 13:45:53 +00:00
d.target = p
2017-03-19 22:45:54 +00:00
}
return d, nil
}
2018-10-13 13:45:53 +00:00
// Launch will start a process with the given args and working directory.
func (d *Debugger) Launch(processArgs []string, wd string) (proc.Process, error) {
switch d.config.Backend {
case "native":
return native.Launch(processArgs, wd, d.config.Foreground)
case "lldb":
return betterGdbserialLaunchError(gdbserial.LLDBLaunch(processArgs, wd, d.config.Foreground))
case "rr":
p, _, err := gdbserial.RecordAndReplay(processArgs, wd, false)
return p, err
case "default":
if runtime.GOOS == "darwin" {
return betterGdbserialLaunchError(gdbserial.LLDBLaunch(processArgs, wd, d.config.Foreground))
}
return native.Launch(processArgs, wd, d.config.Foreground)
default:
return nil, fmt.Errorf("unknown backend %q", d.config.Backend)
}
}
// ErrNoAttachPath is the error returned when the client tries to attach to
// a process on macOS using the lldb backend without specifying the path to
// the target's executable.
var ErrNoAttachPath = errors.New("must specify executable path on macOS")
// Attach will attach to the process specified by 'pid'.
func (d *Debugger) Attach(pid int, path string) (proc.Process, error) {
switch d.config.Backend {
case "native":
return native.Attach(pid)
case "lldb":
return betterGdbserialLaunchError(gdbserial.LLDBAttach(pid, path))
case "default":
if runtime.GOOS == "darwin" {
return betterGdbserialLaunchError(gdbserial.LLDBAttach(pid, path))
}
return native.Attach(pid)
default:
return nil, fmt.Errorf("unknown backend %q", d.config.Backend)
}
}
var errMacOSBackendUnavailable = errors.New("debugserver or lldb-server not found: install XCode's command line tools or lldb-server")
func betterGdbserialLaunchError(p proc.Process, err error) (proc.Process, error) {
if runtime.GOOS != "darwin" {
return p, err
}
if _, isUnavailable := err.(*gdbserial.ErrBackendUnavailable); !isUnavailable {
return p, err
}
return p, errMacOSBackendUnavailable
}
2017-03-19 22:45:54 +00:00
// ProcessPid returns the PID of the process
// the debugger is debugging.
func (d *Debugger) ProcessPid() int {
2018-10-13 13:45:53 +00:00
return d.target.Pid()
2017-03-19 22:45:54 +00:00
}
// LastModified returns the time that the process' executable was last
// modified.
func (d *Debugger) LastModified() time.Time {
2018-10-13 13:45:53 +00:00
return d.target.BinInfo().LastModified()
2017-03-19 22:45:54 +00:00
}
// Detach detaches from the target process.
// If `kill` is true we will kill the process after
// detaching.
func (d *Debugger) Detach(kill bool) error {
d.processMutex.Lock()
defer d.processMutex.Unlock()
return d.detach(kill)
}
func (d *Debugger) detach(kill bool) error {
2018-10-13 13:45:53 +00:00
if d.config.AttachPid == 0 {
kill = true
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
return d.target.Detach(kill)
2017-03-19 22:45:54 +00:00
}
// Restart will restart the target process, first killing
// and then exec'ing it again.
2018-10-13 13:45:53 +00:00
// If the target process is a recording it will restart it from the given
// position. If pos starts with 'c' it's a checkpoint ID, otherwise it's an
// event number. If resetArgs is true, newArgs will replace the process args.
func (d *Debugger) Restart(pos string, resetArgs bool, newArgs []string) ([]api.DiscardedBreakpoint, error) {
2017-03-19 22:45:54 +00:00
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
if recorded, _ := d.target.Recorded(); recorded {
return nil, d.target.Restart(pos)
}
if pos != "" {
return nil, proc.ErrNotRecorded
}
if valid, _ := d.target.Valid(); valid {
2017-03-19 22:45:54 +00:00
// Ensure the process is in a PTRACE_STOP.
if err := stopProcess(d.ProcessPid()); err != nil {
return nil, err
}
}
2018-10-13 13:45:53 +00:00
if err := d.detach(true); err != nil {
return nil, err
}
if resetArgs {
d.processArgs = append([]string{d.processArgs[0]}, newArgs...)
}
p, err := d.Launch(d.processArgs, d.config.WorkingDir)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, fmt.Errorf("could not launch process: %s", err)
}
discarded := []api.DiscardedBreakpoint{}
for _, oldBp := range d.breakpoints() {
if oldBp.ID < 0 {
continue
}
if len(oldBp.File) > 0 {
2018-10-13 13:45:53 +00:00
var err error
oldBp.Addr, err = proc.FindFileLocation(p, oldBp.File, oldBp.Line)
2017-03-19 22:45:54 +00:00
if err != nil {
2018-10-13 13:45:53 +00:00
discarded = append(discarded, api.DiscardedBreakpoint{Breakpoint: oldBp, Reason: err.Error()})
2017-03-19 22:45:54 +00:00
continue
}
}
newBp, err := p.SetBreakpoint(oldBp.Addr, proc.UserBreakpoint, nil)
if err != nil {
return nil, err
}
if err := copyBreakpointInfo(newBp, oldBp); err != nil {
return nil, err
}
}
2018-10-13 13:45:53 +00:00
d.target = p
2017-03-19 22:45:54 +00:00
return discarded, nil
}
// State returns the current state of the debugger.
2018-10-13 13:45:53 +00:00
func (d *Debugger) State(nowait bool) (*api.DebuggerState, error) {
if d.isRunning() && nowait {
return &api.DebuggerState{Running: true}, nil
}
2017-03-19 22:45:54 +00:00
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
return d.state(nil)
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
func (d *Debugger) state(retLoadCfg *proc.LoadConfig) (*api.DebuggerState, error) {
if _, err := d.target.Valid(); err != nil {
return nil, err
2017-03-19 22:45:54 +00:00
}
var (
state *api.DebuggerState
goroutine *api.Goroutine
)
2018-10-13 13:45:53 +00:00
if d.target.SelectedGoroutine() != nil {
goroutine = api.ConvertGoroutine(d.target.SelectedGoroutine())
}
exited := false
if _, err := d.target.Valid(); err != nil {
_, exited = err.(*proc.ErrProcessExited)
2017-03-19 22:45:54 +00:00
}
state = &api.DebuggerState{
SelectedGoroutine: goroutine,
2018-10-13 13:45:53 +00:00
Exited: exited,
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
for _, thread := range d.target.ThreadList() {
th := api.ConvertThread(thread)
if retLoadCfg != nil {
th.ReturnValues = convertVars(thread.Common().ReturnValues(*retLoadCfg))
}
2017-03-19 22:45:54 +00:00
state.Threads = append(state.Threads, th)
2018-10-13 13:45:53 +00:00
if thread.ThreadID() == d.target.CurrentThread().ThreadID() {
2017-03-19 22:45:54 +00:00
state.CurrentThread = th
}
}
2018-10-13 13:45:53 +00:00
state.NextInProgress = d.target.Breakpoints().HasInternalBreakpoints()
if recorded, _ := d.target.Recorded(); recorded {
state.When, _ = d.target.When()
2017-03-19 22:45:54 +00:00
}
return state, nil
}
// CreateBreakpoint creates a breakpoint.
func (d *Debugger) CreateBreakpoint(requestedBp *api.Breakpoint) (*api.Breakpoint, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
var (
createdBp *api.Breakpoint
addr uint64
err error
)
if requestedBp.Name != "" {
if err = api.ValidBreakpointName(requestedBp.Name); err != nil {
return nil, err
}
if d.findBreakpointByName(requestedBp.Name) != nil {
return nil, errors.New("breakpoint name already exists")
}
}
switch {
case len(requestedBp.File) > 0:
fileName := requestedBp.File
if runtime.GOOS == "windows" {
// Accept fileName which is case-insensitive and slash-insensitive match
fileNameNormalized := strings.ToLower(filepath.ToSlash(fileName))
2018-10-13 13:45:53 +00:00
for _, symFile := range d.target.BinInfo().Sources {
2017-03-19 22:45:54 +00:00
if fileNameNormalized == strings.ToLower(filepath.ToSlash(symFile)) {
fileName = symFile
break
}
}
}
2018-10-13 13:45:53 +00:00
addr, err = proc.FindFileLocation(d.target, fileName, requestedBp.Line)
2017-03-19 22:45:54 +00:00
case len(requestedBp.FunctionName) > 0:
if requestedBp.Line >= 0 {
2018-10-13 13:45:53 +00:00
addr, err = proc.FindFunctionLocation(d.target, requestedBp.FunctionName, false, requestedBp.Line)
2017-03-19 22:45:54 +00:00
} else {
2018-10-13 13:45:53 +00:00
addr, err = proc.FindFunctionLocation(d.target, requestedBp.FunctionName, true, 0)
2017-03-19 22:45:54 +00:00
}
default:
addr = requestedBp.Addr
}
if err != nil {
return nil, err
}
2018-10-13 13:45:53 +00:00
bp, err := d.target.SetBreakpoint(addr, proc.UserBreakpoint, nil)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
if err := copyBreakpointInfo(bp, requestedBp); err != nil {
2018-10-13 13:45:53 +00:00
if _, err1 := d.target.ClearBreakpoint(bp.Addr); err1 != nil {
2017-03-19 22:45:54 +00:00
err = fmt.Errorf("error while creating breakpoint: %v, additionally the breakpoint could not be properly rolled back: %v", err, err1)
}
return nil, err
}
createdBp = api.ConvertBreakpoint(bp)
2018-10-13 13:45:53 +00:00
d.log.Infof("created breakpoint: %#v", createdBp)
2017-03-19 22:45:54 +00:00
return createdBp, nil
}
2018-10-13 13:45:53 +00:00
// AmendBreakpoint will update the breakpoint with the matching ID.
2017-03-19 22:45:54 +00:00
func (d *Debugger) AmendBreakpoint(amend *api.Breakpoint) error {
d.processMutex.Lock()
defer d.processMutex.Unlock()
original := d.findBreakpoint(amend.ID)
if original == nil {
return fmt.Errorf("no breakpoint with ID %d", amend.ID)
}
if err := api.ValidBreakpointName(amend.Name); err != nil {
return err
}
return copyBreakpointInfo(original, amend)
}
2018-10-13 13:45:53 +00:00
// CancelNext will clear internal breakpoints, thus cancelling the 'next',
// 'step' or 'stepout' operation.
2017-03-19 22:45:54 +00:00
func (d *Debugger) CancelNext() error {
2018-10-13 13:45:53 +00:00
return d.target.ClearInternalBreakpoints()
2017-03-19 22:45:54 +00:00
}
func copyBreakpointInfo(bp *proc.Breakpoint, requested *api.Breakpoint) (err error) {
bp.Name = requested.Name
bp.Tracepoint = requested.Tracepoint
bp.Goroutine = requested.Goroutine
bp.Stacktrace = requested.Stacktrace
bp.Variables = requested.Variables
bp.LoadArgs = api.LoadConfigToProc(requested.LoadArgs)
bp.LoadLocals = api.LoadConfigToProc(requested.LoadLocals)
bp.Cond = nil
if requested.Cond != "" {
bp.Cond, err = parser.ParseExpr(requested.Cond)
}
return err
}
// ClearBreakpoint clears a breakpoint.
func (d *Debugger) ClearBreakpoint(requestedBp *api.Breakpoint) (*api.Breakpoint, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
var clearedBp *api.Breakpoint
2018-10-13 13:45:53 +00:00
bp, err := d.target.ClearBreakpoint(requestedBp.Addr)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, fmt.Errorf("Can't clear breakpoint @%x: %s", requestedBp.Addr, err)
}
clearedBp = api.ConvertBreakpoint(bp)
2018-10-13 13:45:53 +00:00
d.log.Infof("cleared breakpoint: %#v", clearedBp)
2017-03-19 22:45:54 +00:00
return clearedBp, err
}
// Breakpoints returns the list of current breakpoints.
func (d *Debugger) Breakpoints() []*api.Breakpoint {
d.processMutex.Lock()
defer d.processMutex.Unlock()
return d.breakpoints()
}
func (d *Debugger) breakpoints() []*api.Breakpoint {
bps := []*api.Breakpoint{}
2018-10-13 13:45:53 +00:00
for _, bp := range d.target.Breakpoints().M {
if bp.IsUser() {
bps = append(bps, api.ConvertBreakpoint(bp))
2017-03-19 22:45:54 +00:00
}
}
return bps
}
// FindBreakpoint returns the breakpoint specified by 'id'.
func (d *Debugger) FindBreakpoint(id int) *api.Breakpoint {
d.processMutex.Lock()
defer d.processMutex.Unlock()
bp := d.findBreakpoint(id)
if bp == nil {
return nil
}
return api.ConvertBreakpoint(bp)
}
func (d *Debugger) findBreakpoint(id int) *proc.Breakpoint {
2018-10-13 13:45:53 +00:00
for _, bp := range d.target.Breakpoints().M {
2017-03-19 22:45:54 +00:00
if bp.ID == id {
return bp
}
}
return nil
}
// FindBreakpointByName returns the breakpoint specified by 'name'
func (d *Debugger) FindBreakpointByName(name string) *api.Breakpoint {
d.processMutex.Lock()
defer d.processMutex.Unlock()
return d.findBreakpointByName(name)
}
func (d *Debugger) findBreakpointByName(name string) *api.Breakpoint {
for _, bp := range d.breakpoints() {
if bp.Name == name {
return bp
}
}
return nil
}
// Threads returns the threads of the target process.
func (d *Debugger) Threads() ([]*api.Thread, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
if _, err := d.target.Valid(); err != nil {
return nil, err
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
2017-03-19 22:45:54 +00:00
threads := []*api.Thread{}
2018-10-13 13:45:53 +00:00
for _, th := range d.target.ThreadList() {
2017-03-19 22:45:54 +00:00
threads = append(threads, api.ConvertThread(th))
}
return threads, nil
}
// FindThread returns the thread for the given 'id'.
func (d *Debugger) FindThread(id int) (*api.Thread, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
if _, err := d.target.Valid(); err != nil {
return nil, err
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
for _, th := range d.target.ThreadList() {
if th.ThreadID() == id {
2017-03-19 22:45:54 +00:00
return api.ConvertThread(th), nil
}
}
return nil, nil
}
2018-10-13 13:45:53 +00:00
func (d *Debugger) setRunning(running bool) {
d.runningMutex.Lock()
d.running = running
d.runningMutex.Unlock()
}
func (d *Debugger) isRunning() bool {
d.runningMutex.Lock()
defer d.runningMutex.Unlock()
return d.running
}
2017-03-19 22:45:54 +00:00
// Command handles commands which control the debugger lifecycle
func (d *Debugger) Command(command *api.DebuggerCommand) (*api.DebuggerState, error) {
var err error
if command.Name == api.Halt {
// RequestManualStop does not invoke any ptrace syscalls, so it's safe to
// access the process directly.
2018-10-13 13:45:53 +00:00
d.log.Debug("halting")
err = d.target.RequestManualStop()
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
withBreakpointInfo := true
2017-03-19 22:45:54 +00:00
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
d.setRunning(true)
defer d.setRunning(false)
2017-03-19 22:45:54 +00:00
switch command.Name {
case api.Continue:
2018-10-13 13:45:53 +00:00
d.log.Debug("continuing")
err = proc.Continue(d.target)
case api.Call:
d.log.Debugf("function call %s", command.Expr)
err = proc.CallFunction(d.target, command.Expr, api.LoadConfigToProc(command.ReturnInfoLoadConfig))
case api.Rewind:
d.log.Debug("rewinding")
if err := d.target.Direction(proc.Backward); err != nil {
2017-03-19 22:45:54 +00:00
return nil, err
}
2018-10-13 13:45:53 +00:00
defer func() {
d.target.Direction(proc.Forward)
}()
err = proc.Continue(d.target)
2017-03-19 22:45:54 +00:00
case api.Next:
2018-10-13 13:45:53 +00:00
d.log.Debug("nexting")
err = proc.Next(d.target)
2017-03-19 22:45:54 +00:00
case api.Step:
2018-10-13 13:45:53 +00:00
d.log.Debug("stepping")
err = proc.Step(d.target)
2017-03-19 22:45:54 +00:00
case api.StepInstruction:
2018-10-13 13:45:53 +00:00
d.log.Debug("single stepping")
err = d.target.StepInstruction()
2017-03-19 22:45:54 +00:00
case api.StepOut:
2018-10-13 13:45:53 +00:00
d.log.Debug("step out")
err = proc.StepOut(d.target)
2017-03-19 22:45:54 +00:00
case api.SwitchThread:
2018-10-13 13:45:53 +00:00
d.log.Debugf("switching to thread %d", command.ThreadID)
err = d.target.SwitchThread(command.ThreadID)
withBreakpointInfo = false
2017-03-19 22:45:54 +00:00
case api.SwitchGoroutine:
2018-10-13 13:45:53 +00:00
d.log.Debugf("switching to goroutine %d", command.GoroutineID)
err = d.target.SwitchGoroutine(command.GoroutineID)
withBreakpointInfo = false
2017-03-19 22:45:54 +00:00
case api.Halt:
// RequestManualStop already called
2018-10-13 13:45:53 +00:00
withBreakpointInfo = false
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
2017-03-19 22:45:54 +00:00
if err != nil {
2018-10-13 13:45:53 +00:00
if exitedErr, exited := err.(proc.ErrProcessExited); command.Name != api.SwitchGoroutine && command.Name != api.SwitchThread && exited {
state := &api.DebuggerState{}
state.Exited = true
state.ExitStatus = exitedErr.Status
state.Err = errors.New(exitedErr.Error())
return state, nil
}
2017-03-19 22:45:54 +00:00
return nil, err
}
2018-10-13 13:45:53 +00:00
state, stateErr := d.state(api.LoadConfigToProc(command.ReturnInfoLoadConfig))
if stateErr != nil {
return state, stateErr
}
if withBreakpointInfo {
err = d.collectBreakpointInformation(state)
}
return state, err
2017-03-19 22:45:54 +00:00
}
func (d *Debugger) collectBreakpointInformation(state *api.DebuggerState) error {
if state == nil {
return nil
}
for i := range state.Threads {
2018-10-13 13:45:53 +00:00
if state.Threads[i].Breakpoint == nil || state.Threads[i].BreakpointInfo != nil {
2017-03-19 22:45:54 +00:00
continue
}
bp := state.Threads[i].Breakpoint
bpi := &api.BreakpointInfo{}
state.Threads[i].BreakpointInfo = bpi
if bp.Goroutine {
2018-10-13 13:45:53 +00:00
g, err := proc.GetG(d.target.CurrentThread())
2017-03-19 22:45:54 +00:00
if err != nil {
return err
}
bpi.Goroutine = api.ConvertGoroutine(g)
}
if bp.Stacktrace > 0 {
2018-10-13 13:45:53 +00:00
rawlocs, err := proc.ThreadStacktrace(d.target.CurrentThread(), bp.Stacktrace)
2017-03-19 22:45:54 +00:00
if err != nil {
return err
}
bpi.Stacktrace, err = d.convertStacktrace(rawlocs, nil)
if err != nil {
return err
}
}
2018-10-13 13:45:53 +00:00
thread, found := d.target.FindThread(state.Threads[i].ID)
if !found {
return fmt.Errorf("could not find thread %d", state.Threads[i].ID)
}
if len(bp.Variables) == 0 && bp.LoadArgs == nil && bp.LoadLocals == nil {
// don't try to create goroutine scope if there is nothing to load
continue
}
s, err := proc.GoroutineScope(thread)
2017-03-19 22:45:54 +00:00
if err != nil {
return err
}
if len(bp.Variables) > 0 {
bpi.Variables = make([]api.Variable, len(bp.Variables))
}
for i := range bp.Variables {
2018-10-13 13:45:53 +00:00
v, err := s.EvalVariable(bp.Variables[i], proc.LoadConfig{FollowPointers: true, MaxVariableRecurse: 1, MaxStringLen: 64, MaxArrayValues: 64, MaxStructFields: -1})
2017-03-19 22:45:54 +00:00
if err != nil {
2018-10-13 13:45:53 +00:00
bpi.Variables[i] = api.Variable{Name: bp.Variables[i], Unreadable: fmt.Sprintf("eval error: %v", err)}
} else {
bpi.Variables[i] = *api.ConvertVar(v)
2017-03-19 22:45:54 +00:00
}
}
if bp.LoadArgs != nil {
if vars, err := s.FunctionArguments(*api.LoadConfigToProc(bp.LoadArgs)); err == nil {
bpi.Arguments = convertVars(vars)
}
}
if bp.LoadLocals != nil {
if locals, err := s.LocalVariables(*api.LoadConfigToProc(bp.LoadLocals)); err == nil {
bpi.Locals = convertVars(locals)
}
}
}
return nil
}
// Sources returns a list of the source files for target binary.
func (d *Debugger) Sources(filter string) ([]string, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
regex, err := regexp.Compile(filter)
if err != nil {
return nil, fmt.Errorf("invalid filter argument: %s", err.Error())
}
files := []string{}
2018-10-13 13:45:53 +00:00
for _, f := range d.target.BinInfo().Sources {
2017-03-19 22:45:54 +00:00
if regex.Match([]byte(f)) {
files = append(files, f)
}
}
return files, nil
}
// Functions returns a list of functions in the target process.
func (d *Debugger) Functions(filter string) ([]string, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
return regexFilterFuncs(filter, d.target.BinInfo().Functions)
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
// Types returns all type information in the binary.
2017-03-19 22:45:54 +00:00
func (d *Debugger) Types(filter string) ([]string, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
regex, err := regexp.Compile(filter)
if err != nil {
return nil, fmt.Errorf("invalid filter argument: %s", err.Error())
}
2018-10-13 13:45:53 +00:00
types, err := d.target.BinInfo().Types()
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
r := make([]string, 0, len(types))
for _, typ := range types {
if regex.Match([]byte(typ)) {
r = append(r, typ)
}
}
return r, nil
}
2018-10-13 13:45:53 +00:00
func regexFilterFuncs(filter string, allFuncs []proc.Function) ([]string, error) {
2017-03-19 22:45:54 +00:00
regex, err := regexp.Compile(filter)
if err != nil {
return nil, fmt.Errorf("invalid filter argument: %s", err.Error())
}
funcs := []string{}
for _, f := range allFuncs {
2018-10-13 13:45:53 +00:00
if regex.Match([]byte(f.Name)) {
2017-03-19 22:45:54 +00:00
funcs = append(funcs, f.Name)
}
}
return funcs, nil
}
// PackageVariables returns a list of package variables for the thread,
// optionally regexp filtered using regexp described in 'filter'.
func (d *Debugger) PackageVariables(threadID int, filter string, cfg proc.LoadConfig) ([]api.Variable, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
regex, err := regexp.Compile(filter)
if err != nil {
return nil, fmt.Errorf("invalid filter argument: %s", err.Error())
}
vars := []api.Variable{}
2018-10-13 13:45:53 +00:00
thread, found := d.target.FindThread(threadID)
2017-03-19 22:45:54 +00:00
if !found {
return nil, fmt.Errorf("couldn't find thread %d", threadID)
}
2018-10-13 13:45:53 +00:00
scope, err := proc.ThreadScope(thread)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
pv, err := scope.PackageVariables(cfg)
if err != nil {
return nil, err
}
for _, v := range pv {
if regex.Match([]byte(v.Name)) {
vars = append(vars, *api.ConvertVar(v))
}
}
return vars, err
}
// Registers returns string representation of the CPU registers.
func (d *Debugger) Registers(threadID int, floatingPoint bool) (api.Registers, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
thread, found := d.target.FindThread(threadID)
2017-03-19 22:45:54 +00:00
if !found {
return nil, fmt.Errorf("couldn't find thread %d", threadID)
}
regs, err := thread.Registers(floatingPoint)
if err != nil {
return nil, err
}
return api.ConvertRegisters(regs.Slice()), err
}
func convertVars(pv []*proc.Variable) []api.Variable {
2018-10-13 13:45:53 +00:00
if pv == nil {
return nil
}
2017-03-19 22:45:54 +00:00
vars := make([]api.Variable, 0, len(pv))
for _, v := range pv {
vars = append(vars, *api.ConvertVar(v))
}
return vars
}
// LocalVariables returns a list of the local variables.
func (d *Debugger) LocalVariables(scope api.EvalScope, cfg proc.LoadConfig) ([]api.Variable, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
s, err := proc.ConvertEvalScope(d.target, scope.GoroutineID, scope.Frame)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
pv, err := s.LocalVariables(cfg)
if err != nil {
return nil, err
}
return convertVars(pv), err
}
// FunctionArguments returns the arguments to the current function.
func (d *Debugger) FunctionArguments(scope api.EvalScope, cfg proc.LoadConfig) ([]api.Variable, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
s, err := proc.ConvertEvalScope(d.target, scope.GoroutineID, scope.Frame)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
pv, err := s.FunctionArguments(cfg)
if err != nil {
return nil, err
}
return convertVars(pv), nil
}
// EvalVariableInScope will attempt to evaluate the variable represented by 'symbol'
// in the scope provided.
func (d *Debugger) EvalVariableInScope(scope api.EvalScope, symbol string, cfg proc.LoadConfig) (*api.Variable, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
s, err := proc.ConvertEvalScope(d.target, scope.GoroutineID, scope.Frame)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
v, err := s.EvalVariable(symbol, cfg)
if err != nil {
return nil, err
}
return api.ConvertVar(v), err
}
// SetVariableInScope will set the value of the variable represented by
// 'symbol' to the value given, in the given scope.
func (d *Debugger) SetVariableInScope(scope api.EvalScope, symbol, value string) error {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
s, err := proc.ConvertEvalScope(d.target, scope.GoroutineID, scope.Frame)
2017-03-19 22:45:54 +00:00
if err != nil {
return err
}
return s.SetVariable(symbol, value)
}
// Goroutines will return a list of goroutines in the target process.
func (d *Debugger) Goroutines() ([]*api.Goroutine, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
goroutines := []*api.Goroutine{}
2018-10-13 13:45:53 +00:00
gs, err := proc.GoroutinesInfo(d.target)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
for _, g := range gs {
goroutines = append(goroutines, api.ConvertGoroutine(g))
}
return goroutines, err
}
// Stacktrace returns a list of Stackframes for the given goroutine. The
// length of the returned list will be min(stack_len, depth).
// If 'full' is true, then local vars, function args, etc will be returned as well.
2018-10-13 13:45:53 +00:00
func (d *Debugger) Stacktrace(goroutineID, depth int, readDefers bool, cfg *proc.LoadConfig) ([]api.Stackframe, error) {
2017-03-19 22:45:54 +00:00
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
if _, err := d.target.Valid(); err != nil {
return nil, err
}
2017-03-19 22:45:54 +00:00
var rawlocs []proc.Stackframe
2018-10-13 13:45:53 +00:00
g, err := proc.FindGoroutine(d.target, goroutineID)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
if g == nil {
2018-10-13 13:45:53 +00:00
rawlocs, err = proc.ThreadStacktrace(d.target.CurrentThread(), depth)
2017-03-19 22:45:54 +00:00
} else {
2018-10-13 13:45:53 +00:00
rawlocs, err = g.Stacktrace(depth, readDefers)
2017-03-19 22:45:54 +00:00
}
if err != nil {
return nil, err
}
return d.convertStacktrace(rawlocs, cfg)
}
func (d *Debugger) convertStacktrace(rawlocs []proc.Stackframe, cfg *proc.LoadConfig) ([]api.Stackframe, error) {
locations := make([]api.Stackframe, 0, len(rawlocs))
for i := range rawlocs {
2018-10-13 13:45:53 +00:00
frame := api.Stackframe{
Location: api.ConvertLocation(rawlocs[i].Call),
FrameOffset: rawlocs[i].FrameOffset(),
FramePointerOffset: rawlocs[i].FramePointerOffset(),
Defers: d.convertDefers(rawlocs[i].Defers),
Bottom: rawlocs[i].Bottom,
}
if rawlocs[i].Err != nil {
frame.Err = rawlocs[i].Err.Error()
}
if cfg != nil && rawlocs[i].Current.Fn != nil {
2017-03-19 22:45:54 +00:00
var err error
2018-10-13 13:45:53 +00:00
scope := proc.FrameToScope(d.target.BinInfo(), d.target.CurrentThread(), nil, rawlocs[i:]...)
2017-03-19 22:45:54 +00:00
locals, err := scope.LocalVariables(*cfg)
if err != nil {
return nil, err
}
arguments, err := scope.FunctionArguments(*cfg)
if err != nil {
return nil, err
}
frame.Locals = convertVars(locals)
frame.Arguments = convertVars(arguments)
}
locations = append(locations, frame)
}
return locations, nil
}
2018-10-13 13:45:53 +00:00
func (d *Debugger) convertDefers(defers []*proc.Defer) []api.Defer {
r := make([]api.Defer, len(defers))
for i := range defers {
ddf, ddl, ddfn := d.target.BinInfo().PCToLine(defers[i].DeferredPC)
drf, drl, drfn := d.target.BinInfo().PCToLine(defers[i].DeferPC)
r[i] = api.Defer{
DeferredLoc: api.ConvertLocation(proc.Location{
PC: defers[i].DeferredPC,
File: ddf,
Line: ddl,
Fn: ddfn,
}),
DeferLoc: api.ConvertLocation(proc.Location{
PC: defers[i].DeferPC,
File: drf,
Line: drl,
Fn: drfn,
}),
SP: defers[i].SP,
}
if defers[i].Unreadable != nil {
r[i].Unreadable = defers[i].Unreadable.Error()
}
}
return r
}
2017-03-19 22:45:54 +00:00
// FindLocation will find the location specified by 'locStr'.
func (d *Debugger) FindLocation(scope api.EvalScope, locStr string) ([]api.Location, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
if _, err := d.target.Valid(); err != nil {
return nil, err
}
2017-03-19 22:45:54 +00:00
loc, err := parseLocationSpec(locStr)
if err != nil {
return nil, err
}
2018-10-13 13:45:53 +00:00
s, _ := proc.ConvertEvalScope(d.target, scope.GoroutineID, scope.Frame)
2017-03-19 22:45:54 +00:00
locs, err := loc.Find(d, s, locStr)
for i := range locs {
2018-10-13 13:45:53 +00:00
file, line, fn := d.target.BinInfo().PCToLine(locs[i].PC)
2017-03-19 22:45:54 +00:00
locs[i].File = file
locs[i].Line = line
locs[i].Function = api.ConvertFunction(fn)
}
return locs, err
}
2018-10-13 13:45:53 +00:00
// Disassemble code between startPC and endPC
2017-03-19 22:45:54 +00:00
// if endPC == 0 it will find the function containing startPC and disassemble the whole function
func (d *Debugger) Disassemble(scope api.EvalScope, startPC, endPC uint64, flavour api.AssemblyFlavour) (api.AsmInstructions, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
2018-10-13 13:45:53 +00:00
if _, err := d.target.Valid(); err != nil {
return nil, err
}
2017-03-19 22:45:54 +00:00
if endPC == 0 {
2018-10-13 13:45:53 +00:00
_, _, fn := d.target.BinInfo().PCToLine(startPC)
2017-03-19 22:45:54 +00:00
if fn == nil {
return nil, fmt.Errorf("Address 0x%x does not belong to any function", startPC)
}
startPC = fn.Entry
endPC = fn.End
}
2018-10-13 13:45:53 +00:00
g, err := proc.FindGoroutine(d.target, scope.GoroutineID)
if err != nil {
return nil, err
2017-03-19 22:45:54 +00:00
}
2018-10-13 13:45:53 +00:00
insts, err := proc.Disassemble(d.target, g, startPC, endPC)
2017-03-19 22:45:54 +00:00
if err != nil {
return nil, err
}
disass := make(api.AsmInstructions, len(insts))
for i := range insts {
2018-10-13 13:45:53 +00:00
disass[i] = api.ConvertAsmInstruction(insts[i], insts[i].Text(proc.AssemblyFlavour(flavour), d.target.BinInfo()))
2017-03-19 22:45:54 +00:00
}
return disass, nil
}
2018-10-13 13:45:53 +00:00
// Recorded returns true if the target is a recording.
func (d *Debugger) Recorded() (recorded bool, tracedir string) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
return d.target.Recorded()
}
// Checkpoint will set a checkpoint specified by the locspec.
func (d *Debugger) Checkpoint(where string) (int, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
return d.target.Checkpoint(where)
}
// Checkpoints will return a list of checkpoints.
func (d *Debugger) Checkpoints() ([]api.Checkpoint, error) {
d.processMutex.Lock()
defer d.processMutex.Unlock()
cps, err := d.target.Checkpoints()
if err != nil {
return nil, err
}
r := make([]api.Checkpoint, len(cps))
for i := range cps {
r[i] = api.ConvertCheckpoint(cps[i])
}
return r, nil
}
// ClearCheckpoint will clear the checkpoint of the given ID.
func (d *Debugger) ClearCheckpoint(id int) error {
d.processMutex.Lock()
defer d.processMutex.Unlock()
return d.target.ClearCheckpoint(id)
}
func go11DecodeErrorCheck(err error) error {
if _, isdecodeerr := err.(dwarf.DecodeError); !isdecodeerr {
return err
}
gover, ok := goversion.Installed()
if !ok || !gover.AfterOrEqual(goversion.GoVersion{1, 11, -1, 0, 0, ""}) || goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
return err
}
return fmt.Errorf("executables built by Go 1.11 or later need Delve built by Go 1.11 or later")
}