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

3
import (
4
	"debug/dwarf"
5
	"errors"
6
	"fmt"
7
	"go/constant"
D
Derek Parker 已提交
8

9 10 11
	"github.com/go-delve/delve/pkg/dwarf/frame"
	"github.com/go-delve/delve/pkg/dwarf/op"
	"github.com/go-delve/delve/pkg/dwarf/reader"
12
)
13

J
Josh Soref 已提交
14
// This code is partly adapted from runtime.gentraceback in
A
Alessandro Arzilli 已提交
15 16
// $GOROOT/src/runtime/traceback.go

D
Derek Parker 已提交
17
// Stackframe represents a frame in a system stack.
A
aarzilli 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31
//
// 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.
32
type Stackframe struct {
A
aarzilli 已提交
33 34
	Current, Call Location

35 36
	// Frame registers.
	Regs op.DwarfRegisters
37
	// High address of the stack.
A
aarzilli 已提交
38
	stackHi uint64
39
	// Return address for this stack frame (as read from the stack frame itself).
40
	Ret uint64
A
Alessandro Arzilli 已提交
41 42
	// Address to the memory location containing the return address
	addrret uint64
J
Josh Soref 已提交
43
	// Err is set if an error occurred during stacktrace
44
	Err error
A
aarzilli 已提交
45 46
	// SystemStack is true if this frame belongs to a system stack.
	SystemStack bool
A
aarzilli 已提交
47 48
	// Inlined is true if this frame is actually an inlined call.
	Inlined bool
49 50
	// Bottom is true if this is the bottom of the stack
	Bottom bool
A
aarzilli 已提交
51 52 53 54 55 56 57 58 59 60 61

	// lastpc is a memory address guaranteed to belong to the last instruction
	// executed in this stack frame.
	// For the topmost stack frame this will be the same as Current.PC and
	// Call.PC, for other stack frames it will usually be Current.PC-1, but
	// could be different when inlined calls are involved in the stacktrace.
	// Note that this address isn't guaranteed to belong to the start of an
	// instruction and, for this reason, should not be propagated outside of
	// pkg/proc.
	// Use this value to determine active lexical scopes for the stackframe.
	lastpc uint64
62 63 64 65 66 67 68 69 70

	// 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
A
aarzilli 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
}

// 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 (frame *Stackframe) FrameOffset() int64 {
	if frame.SystemStack {
		return frame.Regs.CFA
	}
	return frame.Regs.CFA - int64(frame.stackHi)
}

// 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).
func (frame *Stackframe) FramePointerOffset() int64 {
	if frame.SystemStack {
		return int64(frame.Regs.BP())
	}
	return int64(frame.Regs.BP()) - int64(frame.stackHi)
91 92
}

93
// ThreadStacktrace returns the stack trace for thread.
D
Derek Parker 已提交
94
// Note the locations in the array are return addresses not call addresses.
95
func ThreadStacktrace(thread Thread, depth int) ([]Stackframe, error) {
A
aarzilli 已提交
96 97 98 99 100 101
	g, _ := GetG(thread)
	if g == nil {
		regs, err := thread.Registers(true)
		if err != nil {
			return nil, err
		}
102
		so := thread.BinInfo().PCToImage(regs.PC())
103
		it := newStackIterator(thread.BinInfo(), thread, thread.BinInfo().Arch.RegistersToDwarfRegisters(so.StaticBase, regs), 0, nil, -1, nil, 0)
A
aarzilli 已提交
104
		return it.stacktrace(depth)
105
	}
106
	return g.Stacktrace(depth, 0)
A
aarzilli 已提交
107 108
}

109
func (g *G) stackIterator(opts StacktraceOptions) (*stackIterator, error) {
A
Alessandro Arzilli 已提交
110 111 112 113
	stkbar, err := g.stkbar()
	if err != nil {
		return nil, err
	}
A
aarzilli 已提交
114

115
	if g.Thread != nil {
116
		regs, err := g.Thread.Registers(true)
117 118 119
		if err != nil {
			return nil, err
		}
120
		so := g.variable.bi.PCToImage(regs.PC())
121 122 123
		return newStackIterator(
			g.variable.bi, g.Thread,
			g.variable.bi.Arch.RegistersToDwarfRegisters(so.StaticBase, regs),
124
			g.stackhi, stkbar, g.stkbarPos, g, opts), nil
A
aarzilli 已提交
125
	}
126 127 128
	so := g.variable.bi.PCToImage(g.PC)
	return newStackIterator(
		g.variable.bi, g.variable.mem,
129
		g.variable.bi.Arch.AddrAndStackRegsToDwarfRegisters(so.StaticBase, g.PC, g.SP, g.BP, g.LR),
130
		g.stackhi, stkbar, g.stkbarPos, g, opts), nil
A
aarzilli 已提交
131 132
}

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
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
)

A
aarzilli 已提交
149 150
// Stacktrace returns the stack trace for a goroutine.
// Note the locations in the array are return addresses not call addresses.
151 152
func (g *G) Stacktrace(depth int, opts StacktraceOptions) ([]Stackframe, error) {
	it, err := g.stackIterator(opts)
A
aarzilli 已提交
153 154
	if err != nil {
		return nil, err
A
aarzilli 已提交
155
	}
156 157 158 159
	frames, err := it.stacktrace(depth)
	if err != nil {
		return nil, err
	}
160
	if opts&StacktraceReadDefers != 0 {
161 162 163
		g.readDefers(frames)
	}
	return frames, nil
A
aarzilli 已提交
164 165
}

D
Derek Parker 已提交
166
// NullAddrError is an error for a null address.
167 168 169 170 171 172
type NullAddrError struct{}

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

A
aarzilli 已提交
173
// stackIterator holds information
D
Derek Parker 已提交
174 175
// required to iterate and walk the program
// stack.
A
aarzilli 已提交
176
type stackIterator struct {
177 178 179 180 181 182 183
	pc    uint64
	top   bool
	atend bool
	frame Stackframe
	bi    *BinaryInfo
	mem   MemoryReadWriter
	err   error
184

185
	stackhi        uint64
A
aarzilli 已提交
186
	systemstack    bool
A
Alessandro Arzilli 已提交
187 188
	stackBarrierPC uint64
	stkbar         []savedLR
189

190 191
	// regs is the register set for the current frame
	regs op.DwarfRegisters
A
aarzilli 已提交
192

193 194 195
	g                  *G     // the goroutine being stacktraced, nil if we are stacktracing a goroutine-less thread
	g0_sched_sp        uint64 // value of g0.sched.sp (see comments around its use)
	g0_sched_sp_loaded bool   // g0_sched_sp was loaded from g0
196 197

	opts StacktraceOptions
A
Alessandro Arzilli 已提交
198 199 200 201 202 203 204
}

type savedLR struct {
	ptr uint64
	val uint64
}

205
func newStackIterator(bi *BinaryInfo, mem MemoryReadWriter, regs op.DwarfRegisters, stackhi uint64, stkbar []savedLR, stkbarPos int, g *G, opts StacktraceOptions) *stackIterator {
A
aarzilli 已提交
206
	stackBarrierFunc := bi.LookupFunc["runtime.stackBarrier"] // stack barriers were removed in Go 1.9
207 208 209
	var stackBarrierPC uint64
	if stackBarrierFunc != nil && stkbar != nil {
		stackBarrierPC = stackBarrierFunc.Entry
210
		fn := bi.PCToFunc(regs.PC())
A
aarzilli 已提交
211
		if fn != nil && fn.Name == "runtime.stackBarrier" {
A
Alessandro Arzilli 已提交
212 213
			// 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.
214
			if len(stkbar) > 0 && stkbar[stkbarPos].ptr < regs.SP() {
A
Alessandro Arzilli 已提交
215
				// runtime.stackBarrier has not incremented stkbarPos.
216
			} else if stkbarPos > 0 && stkbar[stkbarPos-1].ptr < regs.SP() {
A
Alessandro Arzilli 已提交
217 218 219
				// runtime.stackBarrier has incremented stkbarPos.
				stkbarPos--
			} else {
220
				return &stackIterator{err: fmt.Errorf("failed to unwind through stackBarrier at SP %x", regs.SP())}
A
Alessandro Arzilli 已提交
221 222 223 224
			}
		}
		stkbar = stkbar[stkbarPos:]
	}
A
aarzilli 已提交
225 226 227 228
	systemstack := true
	if g != nil {
		systemstack = g.SystemStack
	}
229
	return &stackIterator{pc: regs.PC(), regs: regs, top: true, bi: bi, mem: mem, err: nil, atend: false, stackhi: stackhi, stackBarrierPC: stackBarrierPC, stkbar: stkbar, systemstack: systemstack, g: g, opts: opts}
230 231
}

D
Derek Parker 已提交
232
// Next points the iterator to the next stack frame.
A
aarzilli 已提交
233
func (it *stackIterator) Next() bool {
234 235 236
	if it.err != nil || it.atend {
		return false
	}
237

238
	callFrameRegs, ret, retaddr := it.advanceRegs()
239
	it.frame = it.newStackframe(ret, retaddr)
240

A
Alessandro Arzilli 已提交
241 242 243 244 245 246
	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:]
	}

247
	if it.opts&StacktraceSimple == 0 {
248
		if it.bi.Arch.SwitchStack(it, &callFrameRegs) {
249 250
			return true
		}
251 252
	}

253 254 255 256 257
	if it.frame.Ret <= 0 {
		it.atend = true
		return true
	}

258 259
	it.top = false
	it.pc = it.frame.Ret
260
	it.regs = callFrameRegs
261 262 263
	return true
}

264 265 266 267 268 269
func (it *stackIterator) switchToGoroutineStack() {
	it.systemstack = false
	it.top = false
	it.pc = it.g.PC
	it.regs.Reg(it.regs.SPRegNum).Uint64Val = it.g.SP
	it.regs.Reg(it.regs.BPRegNum).Uint64Val = it.g.BP
270 271 272
	if _, ok := it.bi.Arch.(*ARM64); ok {
		it.regs.Reg(it.regs.LRRegNum).Uint64Val = it.g.LR
	}
273 274
}

D
Derek Parker 已提交
275
// Frame returns the frame the iterator is pointing at.
A
aarzilli 已提交
276
func (it *stackIterator) Frame() Stackframe {
277
	it.frame.Bottom = it.atend
278 279 280
	return it.frame
}

D
Derek Parker 已提交
281
// Err returns the error encountered during stack iteration.
A
aarzilli 已提交
282
func (it *stackIterator) Err() error {
283 284 285
	return it.err
}

286 287 288
// frameBase calculates the frame base pseudo-register for DWARF for fn and
// the current frame.
func (it *stackIterator) frameBase(fn *Function) int64 {
289 290 291
	rdr := fn.cu.image.dwarfReader
	rdr.Seek(fn.offset)
	e, err := rdr.Next()
292 293 294
	if err != nil {
		return 0
	}
295
	fb, _, _, _ := it.bi.Location(e, dwarf.AttrFrameBase, it.pc, it.regs)
296 297 298
	return fb
}

299
func (it *stackIterator) newStackframe(ret, retaddr uint64) Stackframe {
300
	if retaddr == 0 {
301 302
		it.err = NullAddrError{}
		return Stackframe{}
303
	}
304 305 306 307
	f, l, fn := it.bi.PCToLine(it.pc)
	if fn == nil {
		f = "?"
		l = -1
308 309
	} else {
		it.regs.FrameBase = it.frameBase(fn)
310
	}
A
aarzilli 已提交
311
	r := Stackframe{Current: Location{PC: it.pc, File: f, Line: l, Fn: fn}, Regs: it.regs, Ret: ret, addrret: retaddr, stackHi: it.stackhi, SystemStack: it.systemstack, lastpc: it.pc}
312 313 314 315 316 317 318 319
	r.Call = r.Current
	if !it.top && r.Current.Fn != nil && it.pc != r.Current.Fn.Entry {
		// if the return address is the entry point of the function that
		// contains it then this is some kind of fake return frame (for example
		// runtime.sigreturn) that didn't actually call the current frame,
		// attempting to get the location of the CALL instruction would just
		// obfuscate what's going on, since there is no CALL instruction.
		switch r.Current.Fn.Name {
A
aarzilli 已提交
320 321 322 323
		case "runtime.mstart", "runtime.systemstack_switch":
			// these frames are inserted by runtime.systemstack and there is no CALL
			// instruction to look for at pc - 1
		default:
324 325
			r.lastpc = it.pc - 1
			r.Call.File, r.Call.Line = r.Current.Fn.cu.lineInfo.PCToLine(r.Current.Fn.Entry, it.pc-1)
326
		}
327
	}
328
	return r
329 330
}

A
aarzilli 已提交
331
func (it *stackIterator) stacktrace(depth int) ([]Stackframe, error) {
332 333 334
	if depth < 0 {
		return nil, errors.New("negative maximum stack depth")
	}
335 336 337 338
	if it.opts&StacktraceG != 0 && it.g != nil {
		it.switchToGoroutineStack()
		it.top = true
	}
339
	frames := make([]Stackframe, 0, depth+1)
340
	for it.Next() {
A
aarzilli 已提交
341
		frames = it.appendInlineCalls(frames, it.Frame())
342
		if len(frames) >= depth+1 {
A
aarzilli 已提交
343 344
			break
		}
345 346
	}
	if err := it.Err(); err != nil {
347 348 349 350
		if len(frames) == 0 {
			return nil, err
		}
		frames = append(frames, Stackframe{Err: err})
351
	}
352
	return frames, nil
353
}
354

A
aarzilli 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367
func (it *stackIterator) appendInlineCalls(frames []Stackframe, frame Stackframe) []Stackframe {
	if frame.Call.Fn == nil {
		return append(frames, frame)
	}
	if frame.Call.Fn.cu.lineInfo == nil {
		return append(frames, frame)
	}

	callpc := frame.Call.PC
	if len(frames) > 0 {
		callpc--
	}

368 369 370
	image := frame.Call.Fn.cu.image

	irdr := reader.InlineStack(image.dwarf, frame.Call.Fn.offset, reader.ToRelAddr(callpc, image.StaticBase))
A
aarzilli 已提交
371
	for irdr.Next() {
372
		entry, offset := reader.LoadAbstractOrigin(irdr.Entry(), image.dwarfReader)
A
aarzilli 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

		fnname, okname := entry.Val(dwarf.AttrName).(string)
		fileidx, okfileidx := entry.Val(dwarf.AttrCallFile).(int64)
		line, okline := entry.Val(dwarf.AttrCallLine).(int64)

		if !okname || !okfileidx || !okline {
			break
		}
		if fileidx-1 < 0 || fileidx-1 >= int64(len(frame.Current.Fn.cu.lineInfo.FileNames)) {
			break
		}

		inlfn := &Function{Name: fnname, Entry: frame.Call.Fn.Entry, End: frame.Call.Fn.End, offset: offset, cu: frame.Call.Fn.cu}
		frames = append(frames, Stackframe{
			Current: frame.Current,
			Call: Location{
				frame.Call.PC,
				frame.Call.File,
				frame.Call.Line,
				inlfn,
			},
			Regs:        frame.Regs,
			stackHi:     frame.stackHi,
			Ret:         frame.Ret,
			addrret:     frame.addrret,
			Err:         frame.Err,
			SystemStack: frame.SystemStack,
			Inlined:     true,
			lastpc:      frame.lastpc,
		})

		frame.Call.File = frame.Current.Fn.cu.lineInfo.FileNames[fileidx-1].Path
		frame.Call.Line = int(line)
	}

	return append(frames, frame)
}

411 412 413
// advanceRegs calculates it.callFrameRegs using it.regs and the frame
// descriptor entry for the current stack frame.
// it.regs.CallFrameCFA is updated.
414
func (it *stackIterator) advanceRegs() (callFrameRegs op.DwarfRegisters, ret uint64, retaddr uint64) {
415 416
	fde, err := it.bi.frameEntries.FDEForPC(it.pc)
	var framectx *frame.FrameContext
417
	if _, nofde := err.(*frame.ErrNoFDEForPC); nofde {
A
aarzilli 已提交
418
		framectx = it.bi.Arch.FixFrameUnwindContext(nil, it.pc, it.bi)
419
	} else {
A
aarzilli 已提交
420
		framectx = it.bi.Arch.FixFrameUnwindContext(fde.EstablishFrame(it.pc), it.pc, it.bi)
421 422 423 424 425
	}

	cfareg, err := it.executeFrameRegRule(0, framectx.CFA, 0)
	if cfareg == nil {
		it.err = fmt.Errorf("CFA becomes undefined at PC %#x", it.pc)
426
		return op.DwarfRegisters{}, 0, 0
427 428 429
	}
	it.regs.CFA = int64(cfareg.Uint64Val)

430
	callimage := it.bi.PCToImage(it.pc)
431

432
	callFrameRegs = op.DwarfRegisters{StaticBase: callimage.StaticBase, ByteOrder: it.regs.ByteOrder, PCRegNum: it.regs.PCRegNum, SPRegNum: it.regs.SPRegNum, BPRegNum: it.regs.BPRegNum, LRRegNum: it.regs.LRRegNum}
433 434 435 436 437 438 439 440

	// According to the standard the compiler should be responsible for emitting
	// rules for the RSP register so that it can then be used to calculate CFA,
	// however neither Go nor GCC do this.
	// In the following line we copy GDB's behaviour by assuming this is
	// implicit.
	// See also the comment in dwarf2_frame_default_init in
	// $GDB_SOURCE/dwarf2-frame.c
441 442 443 444 445
	if _, ok := it.bi.Arch.(*ARM64); ok {
		callFrameRegs.AddReg(uint64(arm64DwarfSPRegNum), cfareg)
	} else {
		callFrameRegs.AddReg(uint64(amd64DwarfSPRegNum), cfareg)
	}
446 447 448

	for i, regRule := range framectx.Regs {
		reg, err := it.executeFrameRegRule(i, regRule, it.regs.CFA)
449
		callFrameRegs.AddReg(i, reg)
450 451 452 453 454 455 456 457 458 459 460 461 462
		if i == framectx.RetAddrReg {
			if reg == nil {
				if err == nil {
					err = fmt.Errorf("Undefined return address at %#x", it.pc)
				}
				it.err = err
			} else {
				ret = reg.Uint64Val
			}
			retaddr = uint64(it.regs.CFA + regRule.Offset)
		}
	}

463 464 465 466 467 468
	if _, ok := it.bi.Arch.(*ARM64); ok {
		if ret == 0 && it.regs.Regs[it.regs.LRRegNum] != nil {
			ret = it.regs.Regs[it.regs.LRRegNum].Uint64Val
		}
	}

469
	return callFrameRegs, ret, retaddr
470 471 472 473 474 475 476 477 478
}

func (it *stackIterator) executeFrameRegRule(regnum uint64, rule frame.DWRule, cfa int64) (*op.DwarfRegister, error) {
	switch rule.Rule {
	default:
		fallthrough
	case frame.RuleUndefined:
		return nil, nil
	case frame.RuleSameVal:
479 480 481
		if it.regs.Reg(regnum) == nil {
			return nil, nil
		}
A
aarzilli 已提交
482 483
		reg := *it.regs.Reg(regnum)
		return &reg, nil
484 485 486 487 488 489 490
	case frame.RuleOffset:
		return it.readRegisterAt(regnum, uint64(cfa+rule.Offset))
	case frame.RuleValOffset:
		return op.DwarfRegisterFromUint64(uint64(cfa + rule.Offset)), nil
	case frame.RuleRegister:
		return it.regs.Reg(rule.Reg), nil
	case frame.RuleExpression:
491
		v, _, err := op.ExecuteStackProgram(it.regs, rule.Expression)
492 493 494 495 496
		if err != nil {
			return nil, err
		}
		return it.readRegisterAt(regnum, uint64(v))
	case frame.RuleValExpression:
497
		v, _, err := op.ExecuteStackProgram(it.regs, rule.Expression)
498 499 500 501 502 503 504 505 506 507 508
		if err != nil {
			return nil, err
		}
		return op.DwarfRegisterFromUint64(uint64(v)), nil
	case frame.RuleArchitectural:
		return nil, errors.New("architectural frame rules are unsupported")
	case frame.RuleCFA:
		if it.regs.Reg(rule.Reg) == nil {
			return nil, nil
		}
		return op.DwarfRegisterFromUint64(uint64(int64(it.regs.Uint64Val(rule.Reg)) + rule.Offset)), nil
A
aarzilli 已提交
509 510 511
	case frame.RuleFramePointer:
		curReg := it.regs.Reg(rule.Reg)
		if curReg == nil {
512 513
			return nil, nil
		}
A
aarzilli 已提交
514 515 516
		if curReg.Uint64Val <= uint64(cfa) {
			return it.readRegisterAt(regnum, curReg.Uint64Val)
		}
517 518
		newReg := *curReg
		return &newReg, nil
519 520 521 522 523 524 525 526 527 528 529
	}
}

func (it *stackIterator) readRegisterAt(regnum uint64, addr uint64) (*op.DwarfRegister, error) {
	buf := make([]byte, it.bi.Arch.RegSize(regnum))
	_, err := it.mem.ReadMemory(buf, uintptr(addr))
	if err != nil {
		return nil, err
	}
	return op.DwarfRegisterFromBytes(buf), nil
}
530

531 532 533 534 535 536
func (it *stackIterator) loadG0SchedSP() {
	if it.g0_sched_sp_loaded {
		return
	}
	it.g0_sched_sp_loaded = true
	if it.g != nil {
537 538 539 540 541 542 543 544
		mvar, _ := it.g.variable.structMember("m")
		if mvar != nil {
			g0var, _ := mvar.structMember("g0")
			if g0var != nil {
				g0, _ := g0var.parseG()
				if g0 != nil {
					it.g0_sched_sp = g0.SP
				}
545 546 547 548 549
			}
		}
	}
}

550 551 552 553 554 555
// Defer represents one deferred call
type Defer struct {
	DeferredPC uint64 // Value of field _defer.fn.fn, the deferred function
	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)
	link       *Defer // Next deferred function
556
	argSz      int64
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

	variable   *Variable
	Unreadable error
}

// readDefers decorates the frames with the function deferred at each stack frame.
func (g *G) readDefers(frames []Stackframe) {
	curdefer := g.Defer()
	i := 0

	// scan simultaneously frames and the curdefer linked list, assigning
	// defers to their associated frames.
	for {
		if curdefer == nil || i >= len(frames) {
			return
		}
		if curdefer.Unreadable != nil {
			// Current defer is unreadable, stick it into the first available frame
			// (so that it can be reported to the user) and exit
			frames[i].Defers = append(frames[i].Defers, curdefer)
			return
		}
		if frames[i].Err != nil {
			return
		}

		if frames[i].TopmostDefer == nil {
			frames[i].TopmostDefer = curdefer
		}

		if frames[i].SystemStack || curdefer.SP >= uint64(frames[i].Regs.CFA) {
			// frames[i].Regs.CFA is the value that SP had before the function of
			// frames[i] was called.
			// This means that when curdefer.SP == frames[i].Regs.CFA then curdefer
			// was added by the previous frame.
			//
			// curdefer.SP < frames[i].Regs.CFA means curdefer was added by a
			// function further down the stack.
			//
			// SystemStack frames live on a different physical stack and can't be
			// compared with deferred frames.
			i++
		} else {
			frames[i].Defers = append(frames[i].Defers, curdefer)
			curdefer = curdefer.Next()
		}
	}
}

func (d *Defer) load() {
607
	d.variable.loadValue(LoadConfig{false, 1, 0, 0, -1, 0})
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
	if d.variable.Unreadable != nil {
		d.Unreadable = d.variable.Unreadable
		return
	}

	fnvar := d.variable.fieldVariable("fn").maybeDereference()
	if fnvar.Addr != 0 {
		fnvar = fnvar.loadFieldNamed("fn")
		if fnvar.Unreadable == nil {
			d.DeferredPC, _ = constant.Uint64Val(fnvar.Value)
		}
	}

	d.DeferPC, _ = constant.Uint64Val(d.variable.fieldVariable("pc").Value)
	d.SP, _ = constant.Uint64Val(d.variable.fieldVariable("sp").Value)
623
	d.argSz, _ = constant.Int64Val(d.variable.fieldVariable("siz").Value)
624 625 626 627 628 629 630

	linkvar := d.variable.fieldVariable("link").maybeDereference()
	if linkvar.Addr != 0 {
		d.link = &Defer{variable: linkvar}
	}
}

631
// errSPDecreased is used when (*Defer).Next detects a corrupted linked
632 633 634 635
// list, specifically when after followin a link pointer the value of SP
// decreases rather than increasing or staying the same (the defer list is a
// FIFO list, nodes further down the list have been added by function calls
// further down the call stack and therefore the SP should always increase).
636
var errSPDecreased = errors.New("corrupted defer list: SP decreased")
637 638 639 640 641 642 643 644

// Next returns the next defer in the linked list
func (d *Defer) Next() *Defer {
	if d.link == nil {
		return nil
	}
	d.link.load()
	if d.link.SP < d.SP {
645
		d.link.Unreadable = errSPDecreased
646 647 648
	}
	return d.link
}
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

// 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 (d *Defer) EvalScope(thread Thread) (*EvalScope, error) {
	scope, err := GoroutineScope(thread)
	if err != nil {
		return nil, fmt.Errorf("could not get scope: %v", err)
	}

	bi := thread.BinInfo()
	scope.PC = d.DeferredPC
	scope.File, scope.Line, scope.Fn = bi.PCToLine(d.DeferredPC)

	if scope.Fn == nil {
		return nil, fmt.Errorf("could not find function at %#x", d.DeferredPC)
	}

	// The arguments are stored immediately after the defer header struct, i.e.
	// addr+sizeof(_defer). Since CFA in go is always the address of the first
	// argument, that's what we use for the value of CFA.
	// For SP we use CFA minus the size of one pointer because that would be
	// the space occupied by pushing the return address on the stack during the
	// CALL.
	scope.Regs.CFA = (int64(d.variable.Addr) + d.variable.RealType.Common().ByteSize)
	scope.Regs.Regs[scope.Regs.SPRegNum].Uint64Val = uint64(scope.Regs.CFA - int64(bi.Arch.PtrSize()))

676 677 678
	rdr := scope.Fn.cu.image.dwarfReader
	rdr.Seek(scope.Fn.offset)
	e, err := rdr.Next()
679 680 681 682 683 684 685 686
	if err != nil {
		return nil, fmt.Errorf("could not read DWARF function entry: %v", err)
	}
	scope.Regs.FrameBase, _, _, _ = bi.Location(e, dwarf.AttrFrameBase, scope.PC, scope.Regs)
	scope.Mem = cacheMemory(scope.Mem, uintptr(scope.Regs.CFA), int(d.argSz))

	return scope, nil
}