stack.go 7.0 KB
Newer Older
D
Derek Parker 已提交
1
package proc
2

3
import (
4
	"errors"
5
	"fmt"
D
Derek Parker 已提交
6

D
Derek Parker 已提交
7
	"github.com/derekparker/delve/pkg/dwarf/frame"
8
)
9

A
Alessandro Arzilli 已提交
10 11 12 13 14
// This code is partly adaped from runtime.gentraceback in
// $GOROOT/src/runtime/traceback.go

const runtimeStackBarrier = "runtime.stackBarrier"

D
Derek Parker 已提交
15
// NoReturnAddr is returned when return address
N
Nan Xiao 已提交
16
// could not be found during stack trace.
17
type NoReturnAddr struct {
18
	Fn string
19 20 21
}

func (nra NoReturnAddr) Error() string {
22
	return fmt.Sprintf("could not find return address for %s", nra.Fn)
23 24
}

D
Derek Parker 已提交
25
// Stackframe represents a frame in a system stack.
26
type Stackframe struct {
27
	// Address the function above this one on the call stack will return to.
28 29 30
	Current Location
	// Address of the call instruction for the function above on the call stack.
	Call Location
31
	// Start address of the stack frame.
32
	CFA int64
33 34
	// High address of the stack.
	StackHi uint64
35
	// Description of the stack frame.
36
	FDE *frame.FrameDescriptionEntry
37
	// Return address for this stack frame (as read from the stack frame itself).
38
	Ret uint64
A
Alessandro Arzilli 已提交
39 40
	// Address to the memory location containing the return address
	addrret uint64
41 42
	// Err is set if an error occoured during stacktrace
	Err error
43 44
}

D
Derek Parker 已提交
45
// Stacktrace returns the stack trace for thread.
D
Derek Parker 已提交
46
// Note the locations in the array are return addresses not call addresses.
47
func ThreadStacktrace(thread Thread, depth int) ([]Stackframe, error) {
48
	regs, err := thread.Registers(false)
49
	if err != nil {
D
Derek Parker 已提交
50
		return nil, err
51
	}
52
	it := newStackIterator(thread.BinInfo(), thread, regs.PC(), regs.SP(), regs.BP(), 0, nil, -1)
A
aarzilli 已提交
53
	return it.stacktrace(depth)
A
aarzilli 已提交
54 55
}

A
aarzilli 已提交
56
func (g *G) stackIterator() (*stackIterator, error) {
A
Alessandro Arzilli 已提交
57 58 59 60
	stkbar, err := g.stkbar()
	if err != nil {
		return nil, err
	}
61 62
	if g.Thread != nil {
		regs, err := g.Thread.Registers(false)
63 64 65
		if err != nil {
			return nil, err
		}
66
		return newStackIterator(g.variable.bi, g.Thread, regs.PC(), regs.SP(), regs.BP(), g.stackhi, stkbar, g.stkbarPos), nil
A
aarzilli 已提交
67
	}
68
	return newStackIterator(g.variable.bi, g.variable.mem, g.PC, g.SP, 0, g.stackhi, stkbar, g.stkbarPos), nil
A
aarzilli 已提交
69 70 71 72 73 74 75 76
}

// Stacktrace returns the stack trace for a goroutine.
// Note the locations in the array are return addresses not call addresses.
func (g *G) Stacktrace(depth int) ([]Stackframe, error) {
	it, err := g.stackIterator()
	if err != nil {
		return nil, err
A
aarzilli 已提交
77
	}
A
aarzilli 已提交
78
	return it.stacktrace(depth)
A
aarzilli 已提交
79 80
}

D
Derek Parker 已提交
81
// NullAddrError is an error for a null address.
82 83 84 85 86 87
type NullAddrError struct{}

func (n NullAddrError) Error() string {
	return "NULL address"
}

A
aarzilli 已提交
88
// stackIterator holds information
D
Derek Parker 已提交
89 90
// required to iterate and walk the program
// stack.
A
aarzilli 已提交
91
type stackIterator struct {
92 93 94 95
	pc, sp, bp uint64
	top        bool
	atend      bool
	frame      Stackframe
96
	bi         *BinaryInfo
97
	mem        MemoryReadWriter
98
	err        error
99

100
	stackhi        uint64
A
Alessandro Arzilli 已提交
101 102 103 104 105 106 107 108 109
	stackBarrierPC uint64
	stkbar         []savedLR
}

type savedLR struct {
	ptr uint64
	val uint64
}

110
func newStackIterator(bi *BinaryInfo, mem MemoryReadWriter, pc, sp, bp, stackhi uint64, stkbar []savedLR, stkbarPos int) *stackIterator {
111
	stackBarrierFunc := bi.goSymTable.LookupFunc(runtimeStackBarrier) // stack barriers were removed in Go 1.9
112 113 114
	var stackBarrierPC uint64
	if stackBarrierFunc != nil && stkbar != nil {
		stackBarrierPC = stackBarrierFunc.Entry
115
		fn := bi.goSymTable.PCToFunc(pc)
A
Alessandro Arzilli 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129
		if fn != nil && fn.Name == runtimeStackBarrier {
			// We caught the goroutine as it's executing the stack barrier, we must
			// determine whether or not g.stackPos has already been incremented or not.
			if len(stkbar) > 0 && stkbar[stkbarPos].ptr < sp {
				// runtime.stackBarrier has not incremented stkbarPos.
			} else if stkbarPos > 0 && stkbar[stkbarPos-1].ptr < sp {
				// runtime.stackBarrier has incremented stkbarPos.
				stkbarPos--
			} else {
				return &stackIterator{err: fmt.Errorf("failed to unwind through stackBarrier at SP %x", sp)}
			}
		}
		stkbar = stkbar[stkbarPos:]
	}
130
	return &stackIterator{pc: pc, sp: sp, bp: bp, top: true, bi: bi, mem: mem, err: nil, atend: false, stackhi: stackhi, stackBarrierPC: stackBarrierPC, stkbar: stkbar}
131 132
}

D
Derek Parker 已提交
133
// Next points the iterator to the next stack frame.
A
aarzilli 已提交
134
func (it *stackIterator) Next() bool {
135 136 137
	if it.err != nil || it.atend {
		return false
	}
138
	it.frame, it.err = it.frameInfo(it.pc, it.sp, it.bp, it.top)
139
	if it.err != nil {
140
		if _, nofde := it.err.(*frame.NoFDEForPCError); nofde && !it.top {
A
Alessandro Arzilli 已提交
141
			it.frame = Stackframe{Current: Location{PC: it.pc, File: "?", Line: -1}, Call: Location{PC: it.pc, File: "?", Line: -1}, CFA: 0, Ret: 0}
142 143 144 145
			it.atend = true
			it.err = nil
			return true
		}
146 147 148 149 150 151 152
		return false
	}

	if it.frame.Ret <= 0 {
		it.atend = true
		return true
	}
A
Alessandro Arzilli 已提交
153 154 155 156 157 158 159

	if it.stkbar != nil && it.frame.Ret == it.stackBarrierPC && it.frame.addrret == it.stkbar[0].ptr {
		// Skip stack barrier frames
		it.frame.Ret = it.stkbar[0].val
		it.stkbar = it.stkbar[1:]
	}

160
	// Look for "top of stack" functions.
161
	if it.frame.Current.Fn != nil && (it.frame.Current.Fn.Name == "runtime.goexit" || it.frame.Current.Fn.Name == "runtime.rt0_go" || it.frame.Current.Fn.Name == "runtime.mcall") {
162 163 164 165 166 167 168
		it.atend = true
		return true
	}

	it.top = false
	it.pc = it.frame.Ret
	it.sp = uint64(it.frame.CFA)
169
	it.bp, _ = readUintRaw(it.mem, uintptr(it.bp), int64(it.bi.Arch.PtrSize()))
170 171 172
	return true
}

D
Derek Parker 已提交
173
// Frame returns the frame the iterator is pointing at.
A
aarzilli 已提交
174
func (it *stackIterator) Frame() Stackframe {
175 176 177 178 179 180
	if it.err != nil {
		panic(it.err)
	}
	return it.frame
}

D
Derek Parker 已提交
181
// Err returns the error encountered during stack iteration.
A
aarzilli 已提交
182
func (it *stackIterator) Err() error {
183 184 185
	return it.err
}

186 187
func (it *stackIterator) frameInfo(pc, sp, bp uint64, top bool) (Stackframe, error) {
	fde, err := it.bi.frameEntries.FDEForPC(pc)
188 189 190 191 192
	if _, nofde := err.(*frame.NoFDEForPCError); nofde {
		if bp == 0 {
			return Stackframe{}, err
		}
		// When no FDE is available attempt to use BP instead
193 194
		retaddr := uintptr(int(bp) + it.bi.Arch.PtrSize())
		cfa := int64(retaddr) + int64(it.bi.Arch.PtrSize())
195
		return it.newStackframe(pc, cfa, retaddr, nil, top)
196
	}
197

198 199 200 201
	spoffset, retoffset := fde.ReturnAddressOffset(pc)
	cfa := int64(sp) + spoffset

	retaddr := uintptr(cfa + retoffset)
202
	return it.newStackframe(pc, cfa, retaddr, fde, top)
203 204
}

205
func (it *stackIterator) newStackframe(pc uint64, cfa int64, retaddr uintptr, fde *frame.FrameDescriptionEntry, top bool) (Stackframe, error) {
206 207 208
	if retaddr == 0 {
		return Stackframe{}, NullAddrError{}
	}
209
	f, l, fn := it.bi.PCToLine(pc)
210
	ret, err := readUintRaw(it.mem, retaddr, int64(it.bi.Arch.PtrSize()))
211
	if err != nil {
212
		it.err = err
213
	}
214
	r := Stackframe{Current: Location{PC: pc, File: f, Line: l, Fn: fn}, CFA: cfa, FDE: fde, Ret: ret, addrret: uint64(retaddr), StackHi: it.stackhi}
215
	if !top {
216
		r.Call.File, r.Call.Line, r.Call.Fn = it.bi.PCToLine(pc - 1)
217
		r.Call.PC = r.Current.PC
218 219 220 221
	} else {
		r.Call = r.Current
	}
	return r, nil
222 223
}

A
aarzilli 已提交
224
func (it *stackIterator) stacktrace(depth int) ([]Stackframe, error) {
225 226 227
	if depth < 0 {
		return nil, errors.New("negative maximum stack depth")
	}
228
	frames := make([]Stackframe, 0, depth+1)
229 230 231
	for it.Next() {
		frames = append(frames, it.Frame())
		if len(frames) >= depth+1 {
A
aarzilli 已提交
232 233
			break
		}
234 235
	}
	if err := it.Err(); err != nil {
236 237 238 239
		if len(frames) == 0 {
			return nil, err
		}
		frames = append(frames, Stackframe{Err: err})
240
	}
241
	return frames, nil
242
}