proc

package
v0.0.0-...-96212cb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 28, 2022 License: MIT Imports: 47 Imported by: 1

Documentation

Overview

Package proc is a low-level package that provides methods to manipulate the process we are debugging.

proc implements all core functionality including:

  • creating / attaching to a process
  • process manipulation (step, next, continue, halt)
  • methods to explore the memory of the process

Index

Constants

View Source
const (
	// UnrecoveredPanic is the name given to the unrecovered panic breakpoint.
	UnrecoveredPanic = "unrecovered-panic"

	// FatalThrow is the name given to the breakpoint triggered when the target
	// process dies because of a fatal runtime error.
	FatalThrow = "runtime-fatal-throw"

	// HardcodedBreakpoint is the name given to hardcoded breakpoints (for
	// example: calls to runtime.Breakpoint)
	HardcodedBreakpoint = "hardcoded-breakpoint"

	NoLogicalID = -1000 // Logical breakpoint ID for breakpoints internal breakpoints.
)
View Source
const (
	// FloatIsNormal means the value is a normal float.
	FloatIsNormal floatSpecial = iota
	// FloatIsNaN means the float is a special NaN value.
	FloatIsNaN
	// FloatIsPosInf means the float is a special positive inifitiy value.
	FloatIsPosInf
	// FloatIsNegInf means the float is a special negative infinity value.
	FloatIsNegInf
)
View Source
const (
	// VariableEscaped is set for local variables that escaped to the heap
	//
	// The compiler performs escape analysis on local variables, the variables
	// that may outlive the stack frame are allocated on the heap instead and
	// only the address is recorded on the stack. These variables will be
	// marked with this flag.
	VariableEscaped variableFlags = (1 << iota)
	// VariableShadowed is set for local variables that are shadowed by a
	// variable with the same name in another scope
	VariableShadowed
	// VariableConstant means this variable is a constant value
	VariableConstant
	// VariableArgument means this variable is a function argument
	VariableArgument
	// VariableReturnArgument means this variable is a function return value
	VariableReturnArgument
	// VariableFakeAddress means the address of this variable is either fake
	// (i.e. the variable is partially or completely stored in a CPU register
	// and doesn't have a real address) or possibly no longer available (because
	// the variable is the return value of a function call and allocated on a
	// frame that no longer exists)
	VariableFakeAddress
	// VariableCPrt means the variable is a C pointer
	VariableCPtr
	// VariableCPURegister means this variable is a CPU register.
	VariableCPURegister
)
View Source
const (
	Gidle           uint64 = iota // 0
	Grunnable                     // 1 runnable and on a run queue
	Grunning                      // 2
	Gsyscall                      // 3
	Gwaiting                      // 4
	GmoribundUnused               // 5 currently unused, but hardcoded in gdb scripts
	Gdead                         // 6
	Genqueue                      // 7 Only the Gscanenqueue is used.
	Gcopystack                    // 8 in this state when newstack is moving the stack
)

G status, from: src/runtime/runtime2.go

View Source
const (
	FakeAddressBase = 0xbeef000000000000
)

Variables

View Source
var (
	// ErrCouldNotDetermineRelocation is an error returned when Delve could not determine the base address of a
	// position independent executable.
	ErrCouldNotDetermineRelocation = errors.New("could not determine the base address of a PIE")

	// ErrNoDebugInfoFound is returned when Delve cannot open the debug_info
	// section or find an external debug info file.
	ErrNoDebugInfoFound = errors.New("could not open debug info")
)
View Source
var (
	// ErrNotRecorded is returned when an action is requested that is
	// only possible on recorded (traced) programs.
	ErrNotRecorded = errors.New("not a recording")

	// ErrNoRuntimeAllG is returned when the runtime.allg list could
	// not be found.
	ErrNoRuntimeAllG = errors.New("could not find goroutine array")

	// ErrProcessDetached indicates that we detached from the target process.
	ErrProcessDetached = errors.New("detached from the process")
)
View Source
var ErrHWBreakUnsupported = errors.New("hardware breakpoints not implemented")
View Source
var (
	ErrMemoryMapNotSupported = errors.New("MemoryMap not supported")
)
View Source
var ErrUnknownRegister = errors.New("unknown register")

ErrUnknownRegister is returned when the value of an unknown register is requested.

View Source
var ErrUnreadableG = errors.New("could not read G struct")

Functions

func CreateCompositeMemory

func CreateCompositeMemory(mem MemoryReadWriter, arch *Arch, regs op.DwarfRegisters, pieces []op.Piece) (*compositeMemory, error)

CreateCompositeMemory created a new composite memory type using the provided MemoryReadWriter as the underlying memory buffer.

func DisableAsyncPreemptEnv

func DisableAsyncPreemptEnv() []string

DisableAsyncPreemptEnv returns a process environment (like os.Environ) where asyncpreemptoff is set to 1.

func EvalExpressionWithCalls

func EvalExpressionWithCalls(grp *TargetGroup, g *G, expr string, retLoadCfg LoadConfig, checkEscape bool) error

EvalExpressionWithCalls is like EvalExpression but allows function calls in 'expr'. Because this can only be done in the current goroutine, unlike EvalExpression, EvalExpressionWithCalls is not a method of EvalScope.

func FindDeferReturnCalls

func FindDeferReturnCalls(text []AsmInstruction) []uint64

func FindFileLocation

func FindFileLocation(p Process, filename string, lineno int) ([]uint64, error)

FindFileLocation returns the PC for a given file:line. Assumes that `file` is normalized to lower case and '/' on Windows.

func FindFunctionLocation

func FindFunctionLocation(p Process, funcName string, lineOffset int) ([]uint64, error)

FindFunctionLocation finds address of a function's line If lineOffset is passed FindFunctionLocation will return the address of that line

func FirstPCAfterPrologue

func FirstPCAfterPrologue(p Process, fn *Function, sameline bool) (uint64, error)

FirstPCAfterPrologue returns the address of the first instruction after the prologue for function fn. If sameline is set FirstPCAfterPrologue will always return an address associated with the same line as fn.Entry.

Types

type Ancestor

type Ancestor struct {
	ID         int64 // Goroutine ID
	Unreadable error
	// contains filtered or unexported fields
}

func Ancestors

func Ancestors(p *Target, g *G, n int) ([]Ancestor, error)

Ancestors returns the list of ancestors for g.

func (*Ancestor) Stack

func (a *Ancestor) Stack(n int) ([]Stackframe, error)

Stack returns the stack trace of ancestor 'a' as saved by the runtime.

type Arch

type Arch struct {
	Name string // architecture name

	PCRegNum      uint64
	SPRegNum      uint64
	BPRegNum      uint64
	ContextRegNum uint64 // register used to pass a closure context when calling a function pointer
	LRRegNum      uint64

	// RegistersToDwarfRegisters maps hardware registers to DWARF registers.
	RegistersToDwarfRegisters func(uint64, Registers) *op.DwarfRegisters

	// DwarfRegisterToString returns the name and value representation of the
	// given register, the register value can be nil in which case only the
	// register name will be returned.
	DwarfRegisterToString func(int, *op.DwarfRegister) (string, bool, string)

	RegisterNameToDwarf func(s string) (int, bool)
	RegnumToString      func(uint64) string
	// contains filtered or unexported fields
}

Arch represents a CPU architecture.

func AMD64Arch

func AMD64Arch(goos string) *Arch

AMD64Arch returns an initialized AMD64 struct.

func ARM64Arch

func ARM64Arch(goos string) *Arch

ARM64Arch returns an initialized ARM64 struct.

func I386Arch

func I386Arch(goos string) *Arch

I386Arch returns an initialized I386Arch struct.

func (*Arch) AltBreakpointInstruction

func (a *Arch) AltBreakpointInstruction() []byte

AltBreakpointInstruction returns an alternate encoding for the breakpoint instruction.

func (*Arch) BreakInstrMovesPC

func (a *Arch) BreakInstrMovesPC() bool

BreakInstrMovesPC is true if hitting the breakpoint instruction advances the instruction counter by the size of the breakpoint instruction.

func (*Arch) BreakpointInstruction

func (a *Arch) BreakpointInstruction() []byte

BreakpointInstruction is the instruction that will trigger a breakpoint trap for the given architecture.

func (*Arch) BreakpointSize

func (a *Arch) BreakpointSize() int

BreakpointSize is the size of the breakpoint instruction for the given architecture.

func (*Arch) DerefTLS

func (a *Arch) DerefTLS() bool

DerefTLS is true if the G struct stored in the TLS section is a pointer and the address must be dereferenced to find to actual G struct.

func (*Arch) MaxInstructionLength

func (a *Arch) MaxInstructionLength() int

MaxInstructionLength is the maximum size in bytes of an instruction.

func (*Arch) PtrSize

func (a *Arch) PtrSize() int

PtrSize returns the size of a pointer for the architecture.

type AsmInstruction

type AsmInstruction struct {
	Loc        Location
	DestLoc    *Location
	Bytes      []byte
	Breakpoint bool
	AtPC       bool

	Size int
	Kind AsmInstructionKind

	Inst archInst
}

AsmInstruction represents one assembly instruction.

func Disassemble

func Disassemble(mem MemoryReadWriter, regs Registers, breakpoints *BreakpointMap, bi *BinaryInfo, startAddr, endAddr uint64) ([]AsmInstruction, error)

Disassemble disassembles target memory between startAddr and endAddr, marking the current instruction being executed in goroutine g. If currentGoroutine is set and thread is stopped at a CALL instruction Disassemble will evaluate the argument of the CALL instruction using the thread's registers. Be aware that the Bytes field of each returned instruction is a slice of a larger array of size startAddr - endAddr.

func (*AsmInstruction) IsCall

func (instr *AsmInstruction) IsCall() bool

IsCall is true if instr is a call instruction.

func (*AsmInstruction) IsHardBreak

func (instr *AsmInstruction) IsHardBreak() bool

IsHardBreak is true if instr is a hardcoded breakpoint instruction.

func (*AsmInstruction) IsJmp

func (instr *AsmInstruction) IsJmp() bool

IsJmp is true if instr is an unconditional jump instruction.

func (*AsmInstruction) IsRet

func (instr *AsmInstruction) IsRet() bool

IsRet is true if instr is a return instruction.

func (*AsmInstruction) Text

func (inst *AsmInstruction) Text(flavour AssemblyFlavour, bi *BinaryInfo) string

Text will return the assembly instructions in human readable format according to the flavour specified.

type AsmInstructionKind

type AsmInstructionKind uint8
const (
	OtherInstruction AsmInstructionKind = iota
	CallInstruction
	RetInstruction
	JmpInstruction
	HardBreakInstruction
)

type AssemblyFlavour

type AssemblyFlavour int

AssemblyFlavour is the assembly syntax to display.

const (
	// GNUFlavour will display GNU assembly syntax.
	GNUFlavour AssemblyFlavour = iota
	// IntelFlavour will display Intel assembly syntax.
	IntelFlavour
	// GoFlavour will display Go assembly syntax.
	GoFlavour
)

type BinaryInfo

type BinaryInfo struct {
	// Architecture of this binary.
	Arch *Arch

	// GOOS operating system this binary is executing on.
	GOOS string

	// BuildID of this binary.
	BuildID string

	// Functions is a list of all DW_TAG_subprogram entries in debug_info, sorted by entry point
	Functions []Function
	// Sources is a list of all source files found in debug_line.
	Sources []string
	// LookupFunc maps function names to a description of the function.
	LookupFunc map[string]*Function

	// SymNames maps addr to a description *elf.Symbol of this addr.
	SymNames map[uint64]*elf.Symbol

	// Images is a list of loaded shared libraries (also known as
	// shared objects on linux or DLLs on windows).
	Images []*Image

	ElfDynamicSection ElfDynamicSection

	// PackageMap maps package names to package paths, needed to lookup types inside DWARF info.
	// On Go1.12 this mapping is determined by using the last element of a package path, for example:
	//   github.com/emad-elsaid/delve
	// will map to 'delve' because it ends in '/delve'.
	// Starting with Go1.13 debug_info will contain a special attribute
	// (godwarf.AttrGoPackageName) containing the canonical package name for
	// each package.
	// If multiple packages have the same name the map entry will have more
	// than one item in the slice.
	PackageMap map[string][]string
	// contains filtered or unexported fields
}

BinaryInfo holds information on the binaries being executed (this includes both the executable and also any loaded libraries).

func NewBinaryInfo

func NewBinaryInfo(goos, goarch string) *BinaryInfo

NewBinaryInfo returns an initialized but unloaded BinaryInfo struct.

func (*BinaryInfo) AddImage

func (bi *BinaryInfo) AddImage(path string, addr uint64) error

AddImage adds the specified image to bi, loading data asynchronously. Addr is the relocated entry point for the executable and staticBase (i.e. the relocation offset) for all other images. The first image added must be the executable file.

func (*BinaryInfo) AllPCsForFileLines

func (bi *BinaryInfo) AllPCsForFileLines(filename string, linenos []int) map[int][]uint64

AllPCsForFileLines returns a map providing all PC addresses for filename and each line in linenos

func (*BinaryInfo) Close

func (bi *BinaryInfo) Close() error

Close closes all internal readers.

func (*BinaryInfo) FindFunction

func (bi *BinaryInfo) FindFunction(funcName string) ([]*Function, error)

FindFunction returns the functions with name funcName.

func (*BinaryInfo) GStructOffset

func (bi *BinaryInfo) GStructOffset() uint64

GStructOffset returns the offset of the G struct in thread local storage.

func (*BinaryInfo) LastModified

func (bi *BinaryInfo) LastModified() time.Time

LastModified returns the last modified time of the binary.

func (*BinaryInfo) ListPackagesBuildInfo

func (bi *BinaryInfo) ListPackagesBuildInfo(includeFiles bool) []*PackageBuildInfo

ListPackagesBuildInfo returns the list of packages used by the program along with the directory where each package was compiled and optionally the list of files constituting the package.

func (*BinaryInfo) LoadBinaryInfo

func (bi *BinaryInfo) LoadBinaryInfo(path string, entryPoint uint64, debugInfoDirs []string) error

LoadBinaryInfo will load and store the information from the binary at 'path'.

func (*BinaryInfo) LoadImageFromData

func (bi *BinaryInfo) LoadImageFromData(dwdata *dwarf.Data, debugFrameBytes, debugLineBytes, debugLocBytes []byte)

LoadImageFromData creates a new Image, using the specified data, and adds it to bi. This is used for debugging BinaryInfo, you should use LoadBinary instead.

func (*BinaryInfo) Location

func (bi *BinaryInfo) Location(entry godwarf.Entry, attr dwarf.Attr, pc uint64, regs op.DwarfRegisters, mem MemoryReadWriter) (int64, []op.Piece, *locationExpr, error)

Location returns the location described by attribute attr of entry. This will either be an int64 address or a slice of Pieces for locations that don't correspond to a single memory address (registers, composite locations).

func (*BinaryInfo) LocationCovers

func (bi *BinaryInfo) LocationCovers(entry *dwarf.Entry, attr dwarf.Attr) ([][2]uint64, error)

LocationCovers returns the list of PC addresses that is covered by the location attribute 'attr' of entry 'entry'.

func (*BinaryInfo) LookupGenericFunc

func (bi *BinaryInfo) LookupGenericFunc() map[string][]*Function

LookupGenericFunc returns a map that allows searching for instantiations of generic function by specificying a function name without type parameters. For example the key "pkg.(*Receiver).Amethod" will find all instantiations of Amethod:

  • pkg.(*Receiver[.shape.int]).Amethod
  • pkg.(*Receiver[.shape.*uint8]).Amethod
  • etc.

func (*BinaryInfo) PCToFunc

func (bi *BinaryInfo) PCToFunc(pc uint64) *Function

PCToFunc returns the concrete function containing the given PC address. If the PC address belongs to an inlined call it will return the containing function.

func (*BinaryInfo) PCToImage

func (bi *BinaryInfo) PCToImage(pc uint64) *Image

PCToImage returns the image containing the given PC address.

func (*BinaryInfo) PCToLine

func (bi *BinaryInfo) PCToLine(pc uint64) (string, int, *Function)

PCToLine converts an instruction address to a file/line/function.

func (*BinaryInfo) Producer

func (bi *BinaryInfo) Producer() string

Producer returns the value of DW_AT_producer.

func (*BinaryInfo) Types

func (bi *BinaryInfo) Types() ([]string, error)

Types returns list of types present in the debugged program.

type Breaklet

type Breaklet struct {
	// Kind describes whether this is a stepping breakpoint (for next'ing or
	// stepping).
	Kind BreakpointKind

	LogicalID int // ID of the logical breakpoint that owns this physical breakpoint

	// Cond: if not nil the breakpoint will be triggered only if evaluating Cond returns true
	Cond ast.Expr

	// DeferReturns: when kind == NextDeferBreakpoint this breakpoint
	// will also check if the caller is runtime.gopanic or if the return
	// address is in the DeferReturns array.
	// Next uses NextDeferBreakpoints for the breakpoint it sets on the
	// deferred function, DeferReturns is populated with the
	// addresses of calls to runtime.deferreturn in the current
	// function. This ensures that the breakpoint on the deferred
	// function only triggers on panic or on the defer call to
	// the function, not when the function is called directly
	DeferReturns []uint64
	// contains filtered or unexported fields
}

Breaklet represents one of multiple breakpoints that can overlap on a single physical breakpoint.

type Breakpoint

type Breakpoint struct {
	// File & line information for printing.
	FunctionName string
	File         string
	Line         int

	Addr         uint64 // Address breakpoint is set for.
	OriginalData []byte // If software breakpoint, the data we replace with breakpoint instruction.

	WatchExpr    string
	WatchType    WatchType
	HWBreakIndex uint8 // hardware breakpoint index

	// Breaklets is the list of overlapping breakpoints on this physical breakpoint.
	// There can be at most one UserBreakpoint in this list but multiple internal breakpoints are allowed.
	Breaklets []*Breaklet

	// Breakpoint information
	Logical *LogicalBreakpoint
	// contains filtered or unexported fields
}

Breakpoint represents a physical breakpoint. Stores information on the break point including the byte of data that originally was stored at that address.

func (*Breakpoint) IsStepping

func (bp *Breakpoint) IsStepping() bool

IsStepping returns true if bp is an stepping breakpoint. User-set breakpoints can overlap with stepping breakpoints, in that case both IsUser and IsStepping will be true.

func (*Breakpoint) IsUser

func (bp *Breakpoint) IsUser() bool

IsUser returns true if bp is a user-set breakpoint. User-set breakpoints can overlap with stepping breakpoints, in that case both IsUser and IsStepping will be true.

func (*Breakpoint) LogicalID

func (bp *Breakpoint) LogicalID() int

func (*Breakpoint) String

func (bp *Breakpoint) String() string

func (*Breakpoint) UserBreaklet

func (bp *Breakpoint) UserBreaklet() *Breaklet

UserBreaklet returns the user breaklet for this breakpoint, or nil if none exist.

func (*Breakpoint) VerboseDescr

func (bp *Breakpoint) VerboseDescr() []string

VerboseDescr returns a string describing parts of the breakpoint struct that aren't otherwise user visible, for debugging purposes.

type BreakpointExistsError

type BreakpointExistsError struct {
	File string
	Line int
	Addr uint64
}

BreakpointExistsError is returned when trying to set a breakpoint at an address that already has a breakpoint set for it.

func (BreakpointExistsError) Error

func (bpe BreakpointExistsError) Error() string

type BreakpointKind

type BreakpointKind uint16

BreakpointKind determines the behavior of delve when the breakpoint is reached.

const (
	// UserBreakpoint is a user set breakpoint
	UserBreakpoint BreakpointKind = (1 << iota)
	// NextBreakpoint is a breakpoint set by Next, Continue
	// will stop on it and delete it
	NextBreakpoint
	// NextDeferBreakpoint is a breakpoint set by Next on the
	// first deferred function. In addition to checking their condition
	// breakpoints of this kind will also check that the function has been
	// called by runtime.gopanic or through runtime.deferreturn.
	NextDeferBreakpoint
	// StepBreakpoint is a breakpoint set by Step on a CALL instruction,
	// Continue will set a new breakpoint (of NextBreakpoint kind) on the
	// destination of CALL, delete this breakpoint and then continue again
	StepBreakpoint

	// WatchOutOfScopeBreakpoint is a breakpoint used to detect when a watched
	// stack variable goes out of scope.
	WatchOutOfScopeBreakpoint

	// StackResizeBreakpoint is a breakpoint used to detect stack resizes to
	// adjust the watchpoint of stack variables.
	StackResizeBreakpoint
)

type BreakpointMap

type BreakpointMap struct {
	M map[uint64]*Breakpoint

	// Logical is a map of logical breakpoints.
	Logical map[int]*LogicalBreakpoint

	// WatchOutOfScope is the list of watchpoints that went out of scope during
	// the last resume operation
	WatchOutOfScope []*Breakpoint
}

BreakpointMap represents an (address, breakpoint) map.

func NewBreakpointMap

func NewBreakpointMap() BreakpointMap

NewBreakpointMap creates a new BreakpointMap.

func (*BreakpointMap) HasHWBreakpoints

func (bpmap *BreakpointMap) HasHWBreakpoints() bool

HasHWBreakpoints returns true if there are hardware breakpoints.

func (*BreakpointMap) HasSteppingBreakpoints

func (bpmap *BreakpointMap) HasSteppingBreakpoints() bool

HasSteppingBreakpoints returns true if bpmap has at least one stepping breakpoint set.

type BreakpointState

type BreakpointState struct {
	*Breakpoint
	// Active is true if the condition of any breaklet is met.
	Active bool
	// Stepping is true if one of the active breaklets is a stepping
	// breakpoint.
	Stepping bool
	// SteppingInto is true if one of the active stepping breaklets has Kind ==
	// StepBreakpoint.
	SteppingInto bool
	// CondError contains any error encountered while evaluating the
	// breakpoint's condition.
	CondError error
}

BreakpointState describes the state of a breakpoint in a thread.

func (*BreakpointState) Clear

func (bpstate *BreakpointState) Clear()

Clear zeros the struct.

func (*BreakpointState) String

func (bpstate *BreakpointState) String() string

type Checkpoint

type Checkpoint struct {
	ID    int
	When  string
	Where string
}

Checkpoint is a checkpoint

type CommonThread

type CommonThread struct {
	CallReturn bool // returnValues are the return values of a call injection
	// contains filtered or unexported fields
}

CommonThread contains fields used by this package, common to all implementations of the Thread interface.

func (*CommonThread) ReturnValues

func (t *CommonThread) ReturnValues(cfg LoadConfig) []*Variable

ReturnValues reads the return values from the function executing on this thread using the provided LoadConfig.

type ContinueOnceContext

type ContinueOnceContext struct {
	ResumeChan chan<- struct{}
	StopMu     sync.Mutex
	// contains filtered or unexported fields
}

ContinueOnceContext is an object passed to ContinueOnce that the backend can use to communicate with the target layer.

func (*ContinueOnceContext) CheckAndClearManualStopRequest

func (cctx *ContinueOnceContext) CheckAndClearManualStopRequest() bool

CheckAndClearManualStopRequest will check for a manual stop and then clear that state.

func (*ContinueOnceContext) GetManualStopRequested

func (cctx *ContinueOnceContext) GetManualStopRequested() bool

type ContinueOnceFunc

type ContinueOnceFunc func([]ProcessInternal, *ContinueOnceContext) (trapthread Thread, stopReason StopReason, err error)

type Defer

type Defer struct {
	DwrapPC uint64 // PC of the deferred function or, in Go 1.17+ a wrapper to it
	DeferPC uint64 // PC address of instruction that added this defer
	SP      uint64 // Value of SP register when this function was deferred (this field gets adjusted when the stack is moved to match the new stack space)

	Unreadable error
	// contains filtered or unexported fields
}

Defer represents one deferred call

func (*Defer) DeferredFunc

func (d *Defer) DeferredFunc(p *Target) (file string, line int, fn *Function)

DeferredFunc returns the deferred function, on Go 1.17 and later unwraps any defer wrapper.

func (*Defer) EvalScope

func (d *Defer) EvalScope(t *Target, thread Thread) (*EvalScope, error)

EvalScope returns an EvalScope relative to the argument frame of this deferred call. The argument frame of a deferred call is stored in memory immediately after the deferred header.

func (*Defer) Next

func (d *Defer) Next() *Defer

Next returns the next defer in the linked list

type Direction

type Direction int8

Direction is the direction of execution for the target process.

const (
	// Forward direction executes the target normally.
	Forward Direction = 0
	// Backward direction executes the target in reverse.
	Backward Direction = 1
)

type DumpFlags

type DumpFlags uint16

DumpFlags is used to configure (*Target).Dump

const (
	DumpPlatformIndependent DumpFlags = 1 << iota // always use platform-independent notes format
)

type DumpState

type DumpState struct {
	Mutex sync.Mutex

	Dumping  bool
	AllDone  bool
	Canceled bool
	DoneChan chan struct{}

	ThreadsDone, ThreadsTotal int
	MemDone, MemTotal         uint64

	Err error
}

DumpState represents the current state of a core dump in progress.

type ElfDynamicSection

type ElfDynamicSection struct {
	Addr uint64 // relocated address of where the .dynamic section is mapped in memory
	Size uint64 // size of the .dynamic section of the executable
}

ElfDynamicSection describes the .dynamic section of an ELF executable.

type ErrCouldNotFindLine

type ErrCouldNotFindLine struct {
	// contains filtered or unexported fields
}

func (*ErrCouldNotFindLine) Error

func (err *ErrCouldNotFindLine) Error() string

type ErrFunctionNotFound

type ErrFunctionNotFound struct {
	FuncName string
}

ErrFunctionNotFound is returned when failing to find the function named 'FuncName' within the binary.

func (*ErrFunctionNotFound) Error

func (err *ErrFunctionNotFound) Error() string

type ErrNoGoroutine

type ErrNoGoroutine struct {
	// contains filtered or unexported fields
}

ErrNoGoroutine returned when a G could not be found for a specific thread.

func (ErrNoGoroutine) Error

func (ng ErrNoGoroutine) Error() string

type ErrNoSourceForPC

type ErrNoSourceForPC struct {
	// contains filtered or unexported fields
}

ErrNoSourceForPC is returned when the given address does not correspond with a source file location.

func (*ErrNoSourceForPC) Error

func (err *ErrNoSourceForPC) Error() string

type ErrProcessExited

type ErrProcessExited struct {
	Pid    int
	Status int
}

ErrProcessExited indicates that the process has exited and contains both process id and exit status.

func (ErrProcessExited) Error

func (pe ErrProcessExited) Error() string

type ErrUnsupportedArch

type ErrUnsupportedArch struct {
	// contains filtered or unexported fields
}

ErrUnsupportedArch is returned when attempting to debug a binary compiled for an unsupported architecture.

func (*ErrUnsupportedArch) Error

func (e *ErrUnsupportedArch) Error() string

type EvalScope

type EvalScope struct {
	Location
	Regs op.DwarfRegisters
	Mem  MemoryReadWriter // Target's memory

	BinInfo *BinaryInfo
	// contains filtered or unexported fields
}

EvalScope is the scope for variable evaluation. Contains the thread, current location (PC), and canonical frame address.

func ConvertEvalScope

func ConvertEvalScope(dbp *Target, gid, frame, deferCall int) (*EvalScope, error)

ConvertEvalScope returns a new EvalScope in the context of the specified goroutine ID and stack frame. If deferCall is > 0 the eval scope will be relative to the specified deferred call.

func FrameToScope

func FrameToScope(t *Target, thread MemoryReadWriter, g *G, frames ...Stackframe) *EvalScope

FrameToScope returns a new EvalScope for frames[0]. If frames has at least two elements all memory between frames[0].Regs.SP() and frames[1].Regs.CFA will be cached. Otherwise all memory between frames[0].Regs.SP() and frames[0].Regs.CFA will be cached.

func GoroutineScope

func GoroutineScope(t *Target, thread Thread) (*EvalScope, error)

GoroutineScope returns an EvalScope for the goroutine running on the given thread.

func ThreadScope

func ThreadScope(t *Target, thread Thread) (*EvalScope, error)

ThreadScope returns an EvalScope for the given thread.

func (*EvalScope) DwarfReader

func (scope *EvalScope) DwarfReader() *reader.Reader

DwarfReader returns the DwarfReader containing the Dwarf information for the target process.

func (*EvalScope) EvalExpression

func (scope *EvalScope) EvalExpression(expr string, cfg LoadConfig) (*Variable, error)

EvalExpression returns the value of the given expression.

func (*EvalScope) FunctionArguments

func (scope *EvalScope) FunctionArguments(cfg LoadConfig) ([]*Variable, error)

FunctionArguments returns the name, value, and type of all current function arguments.

func (*EvalScope) LocalVariables

func (scope *EvalScope) LocalVariables(cfg LoadConfig) ([]*Variable, error)

LocalVariables returns all local variables from the current function scope.

func (*EvalScope) Locals

func (scope *EvalScope) Locals(flags localsFlags) ([]*Variable, error)

Locals returns all variables in 'scope'.

func (*EvalScope) PackageVariables

func (scope *EvalScope) PackageVariables(cfg LoadConfig) ([]*Variable, error)

PackageVariables returns the name, value, and type of all package variables in the application.

func (*EvalScope) PtrSize

func (scope *EvalScope) PtrSize() int

PtrSize returns the size of a pointer.

func (*EvalScope) SetVariable

func (scope *EvalScope) SetVariable(name, value string) error

SetVariable sets the value of the named variable

type Function

type Function struct {
	Name       string
	Entry, End uint64 // same as DW_AT_lowpc and DW_AT_highpc

	// InlinedCalls lists all inlined calls to this function
	InlinedCalls []InlinedCall
	// contains filtered or unexported fields
}

Function describes a function in the target program.

func (*Function) BaseName

func (fn *Function) BaseName() string

BaseName returns the symbol name without the package or receiver name. Borrowed from $GOROOT/debug/gosym/symtab.go

func (*Function) NameWithoutTypeParams

func (fn *Function) NameWithoutTypeParams() string

NameWithoutTypeParams returns the function name without instantiation parameters

func (*Function) Optimized

func (fn *Function) Optimized() bool

Optimized returns true if the function was optimized by the compiler.

func (*Function) PackageName

func (fn *Function) PackageName() string

PackageName returns the package part of the symbol name, or the empty string if there is none. Borrowed from $GOROOT/debug/gosym/symtab.go

func (*Function) PrologueEndPC

func (fn *Function) PrologueEndPC() uint64

PrologueEndPC returns the PC just after the function prologue

func (*Function) ReceiverName

func (fn *Function) ReceiverName() string

ReceiverName returns the receiver type name of this symbol, or the empty string if there is none. Borrowed from $GOROOT/debug/gosym/symtab.go

type G

type G struct {
	ID      int    // Goroutine ID
	PC      uint64 // PC of goroutine when it was parked.
	SP      uint64 // SP of goroutine when it was parked.
	BP      uint64 // BP of goroutine when it was parked (go >= 1.7).
	LR      uint64 // LR of goroutine when it was parked.
	GoPC    uint64 // PC of 'go' statement that created this goroutine.
	StartPC uint64 // PC of the first function run on this goroutine.
	Status  uint64

	WaitSince  int64
	WaitReason int64

	SystemStack bool // SystemStack is true if this goroutine is currently executing on a system stack.

	// Information on goroutine location
	CurrentLoc Location

	// Thread that this goroutine is currently allocated to
	Thread Thread

	Unreadable error // could not read the G struct
	// contains filtered or unexported fields
}

G represents a runtime G (goroutine) structure (at least the fields that Delve is interested in).

func FindGoroutine

func FindGoroutine(dbp *Target, gid int) (*G, error)

FindGoroutine returns a G struct representing the goroutine specified by `gid`.

func GetG

func GetG(thread Thread) (*G, error)

GetG returns information on the G (goroutine) that is executing on this thread.

The G structure for a thread is stored in thread local storage. Here we simply calculate the address and read and parse the G struct.

We cannot simply use the allg linked list in order to find the M that represents the given OS thread and follow its G pointer because on Darwin mach ports are not universal, so our port for this thread would not map to the `id` attribute of the M structure. Also, when linked against libc, Go prefers the libc version of clone as opposed to the runtime version. This has the consequence of not setting M.id for any thread, regardless of OS.

In order to get around all this craziness, we read the address of the G structure for the current thread from the thread local storage area.

func GoroutinesInfo

func GoroutinesInfo(dbp *Target, start, count int) ([]*G, int, error)

GoroutinesInfo searches for goroutines starting at index 'start', and returns an array of up to 'count' (or all found elements, if 'count' is 0) G structures representing the information Delve care about from the internal runtime G structure. GoroutinesInfo also returns the next index to be used as 'start' argument while scanning for all available goroutines, or -1 if there was an error or if the index already reached the last possible value.

func (*G) Defer

func (g *G) Defer() *Defer

Defer returns the top-most defer of the goroutine.

func (*G) Go

func (g *G) Go() Location

Go returns the location of the 'go' statement that spawned this goroutine.

func (*G) Labels

func (g *G) Labels() map[string]string

func (*G) Stacktrace

func (g *G) Stacktrace(depth int, opts StacktraceOptions) ([]Stackframe, error)

Stacktrace returns the stack trace for a goroutine. Note the locations in the array are return addresses not call addresses.

func (*G) StartLoc

func (g *G) StartLoc(tgt *Target) Location

StartLoc returns the starting location of the goroutine.

func (*G) System

func (g *G) System(tgt *Target) bool

System returns true if g is a system goroutine. See isSystemGoroutine in $GOROOT/src/runtime/traceback.go.

func (*G) UserCurrent

func (g *G) UserCurrent() Location

UserCurrent returns the location the users code is at, or was at before entering a runtime function.

type Image

type Image struct {
	Path       string
	StaticBase uint64
	// contains filtered or unexported fields
}

Image represents a loaded library file (shared object on linux, DLL on windows).

func (*Image) Close

func (image *Image) Close() error

func (*Image) DwarfReader

func (so *Image) DwarfReader() *reader.Reader

DwarfReader returns a reader for the dwarf data

func (*Image) LoadError

func (image *Image) LoadError() error

LoadError returns any error incurred while loading this image.

func (*Image) Type

func (image *Image) Type(offset dwarf.Offset) (godwarf.Type, error)

Type returns the Dwarf type entry at `offset`.

type InlinedCall

type InlinedCall struct {
	LowPC, HighPC uint64 // Address range of the generated inlined instructions
	// contains filtered or unexported fields
}

InlinedCall represents a concrete inlined call to a function.

type InvalidAddressError

type InvalidAddressError struct {
	Address uint64
}

InvalidAddressError represents the result of attempting to set a breakpoint at an invalid address.

func (InvalidAddressError) Error

func (iae InvalidAddressError) Error() string

type IsNilErr

type IsNilErr struct {
	// contains filtered or unexported fields
}

IsNilErr is returned when a variable is nil.

func (*IsNilErr) Error

func (err *IsNilErr) Error() string

type KeepSteppingBreakpoints

type KeepSteppingBreakpoints uint8
const (
	HaltKeepsSteppingBreakpoints KeepSteppingBreakpoints = 1 << iota
	TracepointKeepsSteppingBreakpoints
)

type LaunchFlags

type LaunchFlags uint8
const (
	LaunchForeground LaunchFlags = 1 << iota
	LaunchDisableASLR
)

type LoadConfig

type LoadConfig struct {
	// FollowPointers requests pointers to be automatically dereferenced.
	FollowPointers bool
	// MaxVariableRecurse is how far to recurse when evaluating nested types.
	MaxVariableRecurse int
	// MaxStringLen is the maximum number of bytes read from a string
	MaxStringLen int
	// MaxArrayValues is the maximum number of elements read from an array, a slice or a map.
	MaxArrayValues int
	// MaxStructFields is the maximum number of fields read from a struct, -1 will read all fields.
	MaxStructFields int

	// MaxMapBuckets is the maximum number of map buckets to read before giving up.
	// A value of 0 will read as many buckets as necessary until the entire map
	// is read or MaxArrayValues is reached.
	//
	// Loading a map is an operation that issues O(num_buckets) operations.
	// Normally the number of buckets is proportional to the number of elements
	// in the map, since the runtime tries to keep the load factor of maps
	// between 40% and 80%.
	//
	// It is possible, however, to create very sparse maps either by:
	// a) adding lots of entries to a map and then deleting most of them, or
	// b) using the make(mapType, N) expression with a very large N
	//
	// When this happens delve will have to scan many empty buckets to find the
	// few entries in the map.
	// MaxMapBuckets can be set to avoid annoying slowdowns␣while reading
	// very sparse maps.
	//
	// Since there is no good way for a user of delve to specify the value of
	// MaxMapBuckets, this field is not actually exposed through the API.
	// Instead (*EvalScope).LocalVariables and  (*EvalScope).FunctionArguments
	// set this field automatically to MaxArrayValues * maxMapBucketsFactor.
	// Every other invocation uses the default value of 0, obtaining the old behavior.
	// In practice this means that debuggers using the ListLocalVars or
	// ListFunctionArgs API will not experience a massive slowdown when a very
	// sparse map is in scope, but evaluating a single variable will still work
	// correctly, even if the variable in question is a very sparse map.
	MaxMapBuckets int
}

LoadConfig controls how variables are loaded from the targets memory.

type Location

type Location struct {
	PC   uint64
	File string
	Line int
	Fn   *Function
}

Location represents the location of a thread. Holds information on the current instruction address, the source file:line, and the function.

type LogicalBreakpoint

type LogicalBreakpoint struct {
	LogicalID    int
	Name         string
	FunctionName string
	File         string
	Line         int
	Enabled      bool

	Tracepoint  bool // Tracepoint flag
	TraceReturn bool
	Goroutine   bool     // Retrieve goroutine information
	Stacktrace  int      // Number of stack frames to retrieve
	Variables   []string // Variables to evaluate
	LoadArgs    *LoadConfig
	LoadLocals  *LoadConfig

	HitCount      map[int]uint64 // Number of times a breakpoint has been reached in a certain goroutine
	TotalHitCount uint64         // Number of times a breakpoint has been reached
	HitCondPerG   bool           // Use per goroutine hitcount as HitCond operand, instead of total hitcount

	// HitCond: if not nil the breakpoint will be triggered only if the evaluated HitCond returns
	// true with the TotalHitCount.
	HitCond *struct {
		Op  token.Token
		Val int
	}

	// Cond: if not nil the breakpoint will be triggered only if evaluating Cond returns true
	Cond ast.Expr

	UserData interface{} // Any additional information about the breakpoint
}

LogicalBreakpoint represents a breakpoint set by a user. A logical breakpoint can be associated with zero or many physical breakpoints. Where a physical breakpoint is associated with a specific instruction address a logical breakpoint is associated with a source code location. Therefore a logical breakpoint can be associated with zero or many physical breakpoints. It will have one or more physical breakpoints when source code has been inlined (or in the case of type parametric code). It will have zero physical breakpoints when it represents a deferred breakpoint for code that will be loaded in the future.

type MemoryMapEntry

type MemoryMapEntry struct {
	Addr uint64
	Size uint64

	Read, Write, Exec bool

	Filename string
	Offset   uint64
}

MemoryMapEntry represent a memory mapping in the target process.

type MemoryReadWriter

type MemoryReadWriter interface {
	MemoryReader
	WriteMemory(addr uint64, data []byte) (written int, err error)
}

MemoryReadWriter is an interface for reading or writing to the targets memory. This allows us to read from the actual target memory or possibly a cache.

func CreateLoadedCachedMemory

func CreateLoadedCachedMemory(data []byte) MemoryReadWriter

func DereferenceMemory

func DereferenceMemory(mem MemoryReadWriter) MemoryReadWriter

DereferenceMemory returns a MemoryReadWriter that can read and write the memory pointed to by pointers in this memory. Normally mem and mem.Dereference are the same object, they are different only if this MemoryReadWriter is used to access memory outside of the normal address space of the inferior process (such as data contained in registers, or composite memory).

type MemoryReader

type MemoryReader interface {
	// ReadMemory is just like io.ReaderAt.ReadAt.
	ReadMemory(buf []byte, addr uint64) (n int, err error)
}

MemoryReader is like io.ReaderAt, but the offset is a uint64 so that it can address all of 64-bit memory. Redundant with memoryReadWriter but more easily suited to working with the standard io package.

type NewTargetConfig

type NewTargetConfig struct {
	Path                string     // path of the main executable
	DebugInfoDirs       []string   // Directories to search for split debug info
	DisableAsyncPreempt bool       // Go 1.14 asynchronous preemption should be disabled
	StopReason          StopReason // Initial stop reason
	CanDump             bool       // Can create core dumps (must implement ProcessInternal.MemoryMap)
	ContinueOnce        ContinueOnceFunc
}

NewTargetConfig contains the configuration for a new Target object,

type NoBreakpointError

type NoBreakpointError struct {
	Addr uint64
}

NoBreakpointError is returned when trying to clear a breakpoint that does not exist.

func (NoBreakpointError) Error

func (nbp NoBreakpointError) Error() string

type NullAddrError

type NullAddrError struct{}

NullAddrError is an error for a null address.

func (NullAddrError) Error

func (n NullAddrError) Error() string

type PackageBuildInfo

type PackageBuildInfo struct {
	ImportPath    string
	DirectoryPath string
	Files         map[string]struct{}
}

type Process

type Process interface {
	BinInfo() *BinaryInfo
	EntryPoint() (uint64, error)

	FindThread(threadID int) (Thread, bool)
	ThreadList() []Thread

	Breakpoints() *BreakpointMap

	// Memory returns a memory read/writer for this process's memory.
	Memory() MemoryReadWriter
}

Process represents the target of the debugger. This target could be a system process, core file, etc.

Implementations of Process are not required to be thread safe and users of Process should not assume they are. There is one exception to this rule: it is safe to call RequestManualStop concurrently with ContinueOnce.

type ProcessInternal

type ProcessInternal interface {
	Process
	// Valid returns true if this Process can be used. When it returns false it
	// also returns an error describing why the Process is invalid (either
	// ErrProcessExited or ErrProcessDetached).
	Valid() (bool, error)
	Detach(bool) error

	// RequestManualStop attempts to stop all the process' threads.
	RequestManualStop(cctx *ContinueOnceContext) error

	WriteBreakpoint(*Breakpoint) error
	EraseBreakpoint(*Breakpoint) error

	SupportsBPF() bool
	SetUProbe(string, int64, []ebpf.UProbeArgMap) error
	GetBufferedTracepoints() []ebpf.RawUProbeParams

	// DumpProcessNotes returns ELF core notes describing the process and its threads.
	// Implementing this method is optional.
	DumpProcessNotes(notes []elfwriter.Note, threadDone func()) (bool, []elfwriter.Note, error)
	// MemoryMap returns the memory map of the target process. This method must be implemented if CanDump is true.
	MemoryMap() ([]MemoryMapEntry, error)

	// StartCallInjection notifies the backend that we are about to inject a function call.
	StartCallInjection() (func(), error)
}

ProcessInternal holds a set of methods that need to be implemented by a Delve backend. Methods in the Process interface are safe to be called by clients of the 'proc' library, while all other methods are only called directly within 'proc'.

type RecordingManipulation

type RecordingManipulation interface {
	// Recorded returns true if the current process is a recording and the path
	// to the trace directory.
	Recorded() (recorded bool, tracedir string)
	// Direction changes execution direction.
	ChangeDirection(Direction) error
	// GetDirection returns the current direction of execution.
	GetDirection() Direction
	// When returns current recording position.
	When() (string, error)
	// Checkpoint sets a checkpoint at the current position.
	Checkpoint(where string) (id int, err error)
	// Checkpoints returns the list of currently set checkpoint.
	Checkpoints() ([]Checkpoint, error)
	// ClearCheckpoint removes a checkpoint.
	ClearCheckpoint(id int) error
}

RecordingManipulation is an interface for manipulating process recordings.

type RecordingManipulationInternal

type RecordingManipulationInternal interface {
	RecordingManipulation

	// Restart restarts the recording from the specified position, or from the
	// last checkpoint if pos == "".
	// If pos starts with 'c' it's a checkpoint ID, otherwise it's an event
	// number.
	// Returns the new current thread after the restart has completed.
	Restart(cctx *ContinueOnceContext, pos string) (Thread, error)
}

RecordingManipulationInternal is an interface that a Delve backend can implement if it is a recording.

type Register

type Register struct {
	Name string
	Reg  *op.DwarfRegister
}

Register represents a CPU register.

func AppendBytesRegister

func AppendBytesRegister(regs []Register, name string, value []byte) []Register

AppendBytesRegister will create a new Register struct with the name and value specified and append it to the `regs` slice.

func AppendUint64Register

func AppendUint64Register(regs []Register, name string, value uint64) []Register

AppendUint64Register will create a new Register struct with the name and value specified and append it to the `regs` slice.

type Registers

type Registers interface {
	PC() uint64
	SP() uint64
	BP() uint64
	LR() uint64
	TLS() uint64
	// GAddr returns the address of the G variable if it is known, 0 and false otherwise
	GAddr() (uint64, bool)
	Slice(floatingPoint bool) ([]Register, error)
	// Copy returns a copy of the registers that is guaranteed not to change
	// when the registers of the associated thread change.
	Copy() (Registers, error)
}

Registers is an interface for a generic register type. The interface encapsulates the generic values / actions we need independent of arch. The concrete register types will be different depending on OS/Arch.

type Stackframe

type Stackframe struct {
	Current, Call Location

	// Frame registers.
	Regs op.DwarfRegisters

	// Return address for this stack frame (as read from the stack frame itself).
	Ret uint64

	// Err is set if an error occurred during stacktrace
	Err error
	// SystemStack is true if this frame belongs to a system stack.
	SystemStack bool
	// Inlined is true if this frame is actually an inlined call.
	Inlined bool
	// Bottom is true if this is the bottom of the stack
	Bottom bool

	// TopmostDefer is the defer that would be at the top of the stack when a
	// panic unwind would get to this call frame, in other words it's the first
	// deferred function that will  be called if the runtime unwinds past this
	// call frame.
	TopmostDefer *Defer

	// Defers is the list of functions deferred by this stack frame (so far).
	Defers []*Defer
	// contains filtered or unexported fields
}

Stackframe represents a frame in a system stack.

Each stack frame has two locations Current and Call.

For the topmost stackframe Current and Call are the same location.

For stackframes after the first Current is the location corresponding to the return address and Call is the location of the CALL instruction that was last executed on the frame. Note however that Call.PC is always equal to Current.PC, because finding the correct value for Call.PC would require disassembling each function in the stacktrace.

For synthetic stackframes generated for inlined function calls Current.Fn is the function containing the inlining and Call.Fn in the inlined function.

func ThreadStacktrace

func ThreadStacktrace(thread Thread, depth int) ([]Stackframe, error)

ThreadStacktrace returns the stack trace for thread. Note the locations in the array are return addresses not call addresses.

func (*Stackframe) FrameOffset

func (frame *Stackframe) FrameOffset() int64

FrameOffset returns the address of the stack frame, absolute for system stack frames or as an offset from stackhi for goroutine stacks (a negative value).

func (*Stackframe) FramePointerOffset

func (frame *Stackframe) FramePointerOffset() int64

FramePointerOffset returns the value of the frame pointer, absolute for system stack frames or as an offset from stackhi for goroutine stacks (a negative value).

type StacktraceOptions

type StacktraceOptions uint16
const (
	// StacktraceReadDefers requests a stacktrace decorated with deferred calls
	// for each frame.
	StacktraceReadDefers StacktraceOptions = 1 << iota

	// StacktraceSimple requests a stacktrace where no stack switches will be
	// attempted.
	StacktraceSimple

	// StacktraceG requests a stacktrace starting with the register
	// values saved in the runtime.g structure.
	StacktraceG
)

type StopReason

type StopReason uint8

StopReason describes the reason why the target process is stopped. A process could be stopped for multiple simultaneous reasons, in which case only one will be reported.

const (
	StopUnknown             StopReason = iota
	StopLaunched                       // The process was just launched
	StopAttached                       // The debugger stopped the process after attaching
	StopExited                         // The target process terminated
	StopBreakpoint                     // The target process hit one or more software breakpoints
	StopHardcodedBreakpoint            // The target process hit a hardcoded breakpoint (for example runtime.Breakpoint())
	StopManual                         // A manual stop was requested
	StopNextFinished                   // The next/step/stepout/stepInstruction command terminated
	StopCallReturned                   // An injected call completed
	StopWatchpoint                     // The target process hit one or more watchpoints
)

func (StopReason) String

func (sr StopReason) String() string

String maps StopReason to string representation.

type Target

type Target struct {
	Process

	// StopReason describes the reason why the target process is stopped.
	// A process could be stopped for multiple simultaneous reasons, in which
	// case only one will be reported.
	StopReason StopReason

	// CanDump is true if core dumping is supported.
	CanDump bool
	// contains filtered or unexported fields
}

Target represents the process being debugged.

func NewTarget

func NewTarget(p ProcessInternal, pid int, currentThread Thread, cfg NewTargetConfig) (*Target, error)

NewTarget returns an initialized Target object. The p argument can optionally implement the RecordingManipulation interface.

func (*Target) ClearBreakpoint

func (t *Target) ClearBreakpoint(addr uint64) error

ClearBreakpoint clears the breakpoint at addr.

func (*Target) ClearCaches

func (t *Target) ClearCaches()

ClearCaches clears internal caches that should not survive a restart. This should be called anytime the target process executes instructions.

func (*Target) ClearSteppingBreakpoints

func (t *Target) ClearSteppingBreakpoints() error

ClearSteppingBreakpoints removes all stepping breakpoints from the map, calling clearBreakpoint on each one.

func (*Target) CurrentThread

func (t *Target) CurrentThread() Thread

CurrentThread returns the currently selected thread which will be used for next/step/stepout and for reading variables, unless a goroutine is selected.

func (*Target) Dump

func (t *Target) Dump(out elfwriter.WriteCloserSeeker, flags DumpFlags, state *DumpState)

Dump writes a core dump to out. State is updated as the core dump is written.

func (*Target) GetBufferedTracepoints

func (t *Target) GetBufferedTracepoints() []*UProbeTraceResult

func (*Target) IsCgo

func (t *Target) IsCgo() bool

IsCgo returns the value of runtime.iscgo

func (*Target) Pid

func (t *Target) Pid() int

Pid returns the pid of the target process.

func (*Target) SelectedGoroutine

func (t *Target) SelectedGoroutine() *G

SelectedGoroutine returns the currently selected goroutine.

func (*Target) SetBreakpoint

func (t *Target) SetBreakpoint(logicalID int, addr uint64, kind BreakpointKind, cond ast.Expr) (*Breakpoint, error)

SetBreakpoint sets a breakpoint at addr, and stores it in the process wide break point table.

func (*Target) SetEBPFTracepoint

func (t *Target) SetEBPFTracepoint(fnName string) error

SetEBPFTracepoint will attach a uprobe to the function specified by 'fnName'.

func (*Target) SetWatchpoint

func (t *Target) SetWatchpoint(logicalID int, scope *EvalScope, expr string, wtype WatchType, cond ast.Expr) (*Breakpoint, error)

SetWatchpoint sets a data breakpoint at addr and stores it in the process wide break point table.

func (*Target) SupportsFunctionCalls

func (t *Target) SupportsFunctionCalls() bool

SupportsFunctionCalls returns whether or not the backend supports calling functions during a debug session. Currently only non-recorded processes running on AMD64 support function calls.

func (*Target) SwitchGoroutine

func (p *Target) SwitchGoroutine(g *G) error

SwitchGoroutine will change the selected and active goroutine.

func (*Target) SwitchThread

func (p *Target) SwitchThread(tid int) error

SwitchThread will change the selected and active thread.

func (*Target) Valid

func (t *Target) Valid() (bool, error)

Valid returns true if this Process can be used. When it returns false it also returns an error describing why the Process is invalid (either ErrProcessExited or ErrProcessDetached).

type TargetGroup

type TargetGroup struct {
	Selected *Target

	RecordingManipulation

	// KeepSteppingBreakpoints determines whether certain stop reasons (e.g. manual halts)
	// will keep the stepping breakpoints instead of clearing them.
	KeepSteppingBreakpoints KeepSteppingBreakpoints

	LogicalBreakpoints map[int]*LogicalBreakpoint
	// contains filtered or unexported fields
}

TargetGroup reperesents a group of target processes being debugged that will be resumed and stopped simultaneously. New targets are automatically added to the group if exec catching is enabled and the backend supports it, otherwise the group will always contain a single target process.

func NewGroup

func NewGroup(t *Target) *TargetGroup

NewGroup creates a TargetGroup containing the specified Target.

func (*TargetGroup) ClearSteppingBreakpoints

func (grp *TargetGroup) ClearSteppingBreakpoints() error

ClearSteppingBreakpoints removes all stepping breakpoints.

func (*TargetGroup) Continue

func (grp *TargetGroup) Continue() error

Continue continues execution of the debugged processes. It will continue until it hits a breakpoint or is otherwise stopped.

func (*TargetGroup) Detach

func (grp *TargetGroup) Detach(kill bool) error

Detach detaches all targets in the group.

func (*TargetGroup) HasSteppingBreakpoints

func (grp *TargetGroup) HasSteppingBreakpoints() bool

HasSteppingBreakpoints returns true if any of the targets has stepping breakpoints set.

func (*TargetGroup) Next

func (grp *TargetGroup) Next() (err error)

Next resumes the processes in the group, continuing the selected target until the next source line.

func (*TargetGroup) RequestManualStop

func (t *TargetGroup) RequestManualStop() error

RequestManualStop attempts to stop all the processes' threads.

func (*TargetGroup) Restart

func (grp *TargetGroup) Restart(from string) error

Restart will start the process group over from the location specified by the "from" locspec. This is only useful for recorded targets. Restarting of a normal process happens at a higher level (debugger.Restart).

func (*TargetGroup) ResumeNotify

func (t *TargetGroup) ResumeNotify(ch chan<- struct{})

ResumeNotify specifies a channel that will be closed the next time Continue finishes resuming the targets.

func (*TargetGroup) Step

func (grp *TargetGroup) Step() (err error)

Step resumes the processes in the group, continuing the selected target until the next source line. Will step into functions.

func (*TargetGroup) StepInstruction

func (grp *TargetGroup) StepInstruction() (err error)

StepInstruction will continue the current thread for exactly one instruction. This method affects only the thread associated with the selected goroutine. All other threads will remain stopped.

func (*TargetGroup) StepOut

func (grp *TargetGroup) StepOut() error

StepOut resumes the processes in the group, continuing the selected target until until the current goroutine exits the function currently being executed or a deferred function is executed

func (*TargetGroup) TargetForThread

func (grp *TargetGroup) TargetForThread(thread Thread) *Target

TargetForThread returns the target containing the given thread.

func (*TargetGroup) Targets

func (grp *TargetGroup) Targets() []*Target

Targets returns a slice of targets in the group.

func (*TargetGroup) ThreadList

func (grp *TargetGroup) ThreadList() []Thread

ThreadList returns a list of all threads in all target processes.

func (*TargetGroup) Valid

func (grp *TargetGroup) Valid() (bool, error)

Valid returns true if any target in the target group is valid.

type Thread

type Thread interface {
	Location() (*Location, error)
	// Breakpoint will return the breakpoint that this thread is stopped at or
	// nil if the thread is not stopped at any breakpoint.
	Breakpoint() *BreakpointState
	ThreadID() int

	// Registers returns the CPU registers of this thread. The contents of the
	// variable returned may or may not change to reflect the new CPU status
	// when the thread is resumed or the registers are changed by calling
	// SetPC/SetSP/etc.
	// To insure that the the returned variable won't change call the Copy
	// method of Registers.
	Registers() (Registers, error)

	// RestoreRegisters restores saved registers
	RestoreRegisters(Registers) error
	BinInfo() *BinaryInfo
	// ProcessMemory returns the process memory.
	ProcessMemory() MemoryReadWriter
	StepInstruction() error
	// SetCurrentBreakpoint updates the current breakpoint of this thread, if adjustPC is true also checks for breakpoints that were just hit (this should only be passed true after a thread resume)
	SetCurrentBreakpoint(adjustPC bool) error
	// SoftExc returns true if this thread received a software exception during the last resume.
	SoftExc() bool
	// Common returns the CommonThread structure for this thread
	Common() *CommonThread

	// SetReg changes the value of the specified register. A minimal
	// implementation of this interface can support just setting the PC
	// register.
	SetReg(uint64, *op.DwarfRegister) error
}

Thread represents a thread.

type UProbeTraceResult

type UProbeTraceResult struct {
	FnAddr       int
	GoroutineID  int
	IsRet        bool
	InputParams  []*Variable
	ReturnParams []*Variable
}

type Variable

type Variable struct {
	Addr      uint64
	OnlyAddr  bool
	Name      string
	DwarfType godwarf.Type
	RealType  godwarf.Type
	Kind      reflect.Kind

	Value        constant.Value
	FloatSpecial floatSpecial

	Len int64
	Cap int64

	Flags variableFlags

	// Base address of arrays, Base address of the backing array for slices (0 for nil slices)
	// Base address of the backing byte array for strings
	// address of the struct backing chan and map variables
	// address of the function entry point for function variables (0 for nil function pointers)
	Base uint64

	Children []Variable

	Unreadable error

	LocationExpr *locationExpr // location expression
	DeclLine     int64         // line number of this variable's declaration
	// contains filtered or unexported fields
}

Variable represents a variable. It contains the address, name, type and other information parsed from both the Dwarf information and the memory of the debugged process. If OnlyAddr is true, the variables value has not been loaded.

func (*Variable) ConstDescr

func (v *Variable) ConstDescr() string

ConstDescr describes the value of v using constants.

func (*Variable) LoadResliced

func (v *Variable) LoadResliced(start int, cfg LoadConfig) (newV *Variable, err error)

LoadResliced returns a new array, slice or map that starts at index start and contains up to cfg.MaxArrayValues children.

func (*Variable) TypeString

func (v *Variable) TypeString() string

TypeString returns the string representation of the type of this variable.

type WatchType

type WatchType uint8

WatchType is the watchpoint type

const (
	WatchRead WatchType = 1 << iota
	WatchWrite
)

func (WatchType) Read

func (wtype WatchType) Read() bool

Read returns true if the hardware breakpoint should trigger on memory reads.

func (WatchType) Size

func (wtype WatchType) Size() int

Size returns the size in bytes of the hardware breakpoint.

func (WatchType) Write

func (wtype WatchType) Write() bool

Write returns true if the hardware breakpoint should trigger on memory writes.

Directories

Path Synopsis
internal
This package contains functions and data structures used by both the linux implementation of the native backend and the core backend to deal with structures used by the linux kernel.
This package contains functions and data structures used by both the linux implementation of the native backend and the core backend to deal with structures used by the linux kernel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL