fncall.go 16.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package proc

import (
	"debug/dwarf"
	"encoding/binary"
	"errors"
	"fmt"
	"go/ast"
	"go/constant"
	"go/parser"
	"reflect"
	"sort"

	"github.com/derekparker/delve/pkg/dwarf/godwarf"
	"github.com/derekparker/delve/pkg/dwarf/op"
	"github.com/derekparker/delve/pkg/dwarf/reader"
	"github.com/derekparker/delve/pkg/logflags"
	"github.com/sirupsen/logrus"
	"golang.org/x/arch/x86/x86asm"
)

// This file implements the function call injection introduced in go1.11.
//
// The protocol is described in $GOROOT/src/runtime/asm_amd64.s in the
// comments for function runtime·debugCallV1.
//
// There are two main entry points here. The first one is CallFunction which
// evaluates a function call expression, sets up the function call on the
// selected goroutine and resumes execution of the process.
//
// The second one is (*FunctionCallState).step() which is called every time
// the process stops at a breakpoint inside one of the debug injcetion
// functions.

const (
	debugCallFunctionNamePrefix1 = "debugCall"
	debugCallFunctionNamePrefix2 = "runtime.debugCall"
	debugCallFunctionName        = "runtime.debugCallV1"
)

var (
42 43 44 45 46 47 48 49 50 51 52
	errFuncCallUnsupported        = errors.New("function calls not supported by this version of Go")
	errFuncCallUnsupportedBackend = errors.New("backend does not support function calls")
	errFuncCallInProgress         = errors.New("cannot call function while another function call is already in progress")
	errNotACallExpr               = errors.New("not a function call")
	errNoGoroutine                = errors.New("no goroutine selected")
	errGoroutineNotRunning        = errors.New("selected goroutine not running")
	errNotEnoughStack             = errors.New("not enough stack space")
	errTooManyArguments           = errors.New("too many arguments")
	errNotEnoughArguments         = errors.New("not enough arguments")
	errNoAddrUnsupported          = errors.New("arguments to a function call must have an address")
	errNotAGoFunction             = errors.New("not a Go function")
53 54 55 56 57 58 59 60
)

type functionCallState struct {
	// inProgress is true if a function call is in progress
	inProgress bool
	// finished is true if the function call terminated
	finished bool
	// savedRegs contains the saved registers
61
	savedRegs Registers
62 63 64 65 66 67
	// expr contains an expression describing the current function call
	expr string
	// err contains a saved error
	err error
	// fn is the function that is being called
	fn *Function
68 69
	// closureAddr is the address of the closure being called
	closureAddr uint64
70 71 72 73 74 75 76 77 78 79 80 81 82 83
	// argmem contains the argument frame of this function call
	argmem []byte
	// retvars contains the return variables after the function call terminates without panic'ing
	retvars []*Variable
	// retLoadCfg is the load configuration used to load return values
	retLoadCfg *LoadConfig
	// panicvar is a variable used to store the value of the panic, if the
	// called function panics.
	panicvar *Variable
}

// CallFunction starts a debugger injected function call on the current thread of p.
// See runtime.debugCallV1 in $GOROOT/src/runtime/asm_amd64.s for a
// description of the protocol.
84
func CallFunction(p Process, expr string, retLoadCfg *LoadConfig, checkEscape bool) error {
85 86
	bi := p.BinInfo()
	if !p.Common().fncallEnabled {
87
		return errFuncCallUnsupportedBackend
88 89 90
	}
	fncall := &p.Common().fncallState
	if fncall.inProgress {
91
		return errFuncCallInProgress
92 93 94 95 96 97
	}

	*fncall = functionCallState{}

	dbgcallfn := bi.LookupFunc[debugCallFunctionName]
	if dbgcallfn == nil {
98
		return errFuncCallUnsupported
99 100 101 102 103
	}

	// check that the selected goroutine is running
	g := p.SelectedGoroutine()
	if g == nil {
104
		return errNoGoroutine
105 106
	}
	if g.Status != Grunning || g.Thread == nil {
107
		return errGoroutineNotRunning
108 109 110 111 112 113 114
	}

	// check that there are at least 256 bytes free on the stack
	regs, err := g.Thread.Registers(true)
	if err != nil {
		return err
	}
115
	regs = regs.Copy()
116
	if regs.SP()-256 <= g.stacklo {
117
		return errNotEnoughStack
118 119 120
	}
	_, err = regs.Get(int(x86asm.RAX))
	if err != nil {
121
		return errFuncCallUnsupportedBackend
122 123
	}

124
	fn, closureAddr, argvars, err := funcCallEvalExpr(p, expr)
125 126 127 128
	if err != nil {
		return err
	}

129
	argmem, err := funcCallArgFrame(fn, argvars, g, bi, checkEscape)
130 131 132 133 134 135 136 137 138 139 140 141 142
	if err != nil {
		return err
	}

	if err := callOP(bi, g.Thread, regs, dbgcallfn.Entry); err != nil {
		return err
	}
	// write the desired argument frame size at SP-(2*pointer_size) (the extra pointer is the saved PC)
	if err := writePointer(bi, g.Thread, regs.SP()-3*uint64(bi.Arch.PtrSize()), uint64(len(argmem))); err != nil {
		return err
	}

	fncall.inProgress = true
143
	fncall.savedRegs = regs
144 145
	fncall.expr = expr
	fncall.fn = fn
146
	fncall.closureAddr = closureAddr
147 148 149 150 151 152 153 154 155 156 157 158
	fncall.argmem = argmem
	fncall.retLoadCfg = retLoadCfg

	fncallLog("function call initiated %v frame size %d\n", fn, len(argmem))

	return Continue(p)
}

func fncallLog(fmtstr string, args ...interface{}) {
	if !logflags.FnCall() {
		return
	}
159
	logrus.WithFields(logrus.Fields{"layer": "proc", "kind": "fncall"}).Infof(fmtstr, args...)
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
}

// writePointer writes val as an architecture pointer at addr in mem.
func writePointer(bi *BinaryInfo, mem MemoryReadWriter, addr, val uint64) error {
	ptrbuf := make([]byte, bi.Arch.PtrSize())

	// TODO: use target architecture endianness instead of LittleEndian
	switch len(ptrbuf) {
	case 4:
		binary.LittleEndian.PutUint32(ptrbuf, uint32(val))
	case 8:
		binary.LittleEndian.PutUint64(ptrbuf, val)
	default:
		panic(fmt.Errorf("unsupported pointer size %d", len(ptrbuf)))
	}
	_, err := mem.WriteMemory(uintptr(addr), ptrbuf)
	return err
}

// callOP simulates a call instruction on the given thread:
// * pushes the current value of PC on the stack (adjusting SP)
// * changes the value of PC to callAddr
// Note: regs are NOT updated!
func callOP(bi *BinaryInfo, thread Thread, regs Registers, callAddr uint64) error {
	sp := regs.SP()
	// push PC on the stack
	sp -= uint64(bi.Arch.PtrSize())
	if err := thread.SetSP(sp); err != nil {
		return err
	}
	if err := writePointer(bi, thread, sp, regs.PC()); err != nil {
		return err
	}
	return thread.SetPC(callAddr)
}

// funcCallEvalExpr evaluates expr, which must be a function call, returns
// the function being called and its arguments.
198
func funcCallEvalExpr(p Process, expr string) (fn *Function, closureAddr uint64, argvars []*Variable, err error) {
199 200 201
	bi := p.BinInfo()
	scope, err := GoroutineScope(p.CurrentThread())
	if err != nil {
202
		return nil, 0, nil, err
203 204 205 206
	}

	t, err := parser.ParseExpr(expr)
	if err != nil {
207
		return nil, 0, nil, err
208 209 210
	}
	callexpr, iscall := t.(*ast.CallExpr)
	if !iscall {
211
		return nil, 0, nil, errNotACallExpr
212 213 214 215
	}

	fnvar, err := scope.evalAST(callexpr.Fun)
	if err != nil {
216
		return nil, 0, nil, err
217 218
	}
	if fnvar.Kind != reflect.Func {
219 220 221 222 223 224 225 226
		return nil, 0, nil, fmt.Errorf("expression %q is not a function", exprToString(callexpr.Fun))
	}
	fnvar.loadValue(LoadConfig{false, 0, 0, 0, 0})
	if fnvar.Unreadable != nil {
		return nil, 0, nil, fnvar.Unreadable
	}
	if fnvar.Base == 0 {
		return nil, 0, nil, errors.New("nil pointer dereference")
227 228 229
	}
	fn = bi.PCToFunc(uint64(fnvar.Base))
	if fn == nil {
230
		return nil, 0, nil, fmt.Errorf("could not find DIE for function %q", exprToString(callexpr.Fun))
231 232
	}
	if !fn.cu.isgo {
233
		return nil, 0, nil, errNotAGoFunction
234 235
	}

236 237 238 239 240
	argvars = make([]*Variable, 0, len(callexpr.Args)+1)
	if len(fnvar.Children) > 0 {
		// receiver argument
		argvars = append(argvars, &fnvar.Children[0])
	}
241
	for i := range callexpr.Args {
242
		argvar, err := scope.evalAST(callexpr.Args[i])
243
		if err != nil {
244
			return nil, 0, nil, err
245
		}
246 247
		argvar.Name = exprToString(callexpr.Args[i])
		argvars = append(argvars, argvar)
248 249
	}

250
	return fn, fnvar.funcvalAddr(), argvars, nil
251 252 253
}

type funcCallArg struct {
A
aarzilli 已提交
254 255 256 257
	name  string
	typ   godwarf.Type
	off   int64
	isret bool
258 259 260 261
}

// funcCallArgFrame checks type and pointer escaping for the arguments and
// returns the argument frame.
262
func funcCallArgFrame(fn *Function, actualArgs []*Variable, g *G, bi *BinaryInfo, checkEscape bool) (argmem []byte, err error) {
A
aarzilli 已提交
263 264 265 266 267
	argFrameSize, formalArgs, err := funcCallArgs(fn, bi, false)
	if err != nil {
		return nil, err
	}
	if len(actualArgs) > len(formalArgs) {
268
		return nil, errTooManyArguments
A
aarzilli 已提交
269 270
	}
	if len(actualArgs) < len(formalArgs) {
271
		return nil, errNotEnoughArguments
A
aarzilli 已提交
272 273 274 275 276 277 278 279 280
	}

	// constructs arguments frame
	argmem = make([]byte, argFrameSize)
	argmemWriter := &bufferMemoryReadWriter{argmem}
	for i := range formalArgs {
		formalArg := &formalArgs[i]
		actualArg := actualArgs[i]

281 282 283 284 285
		if checkEscape {
			//TODO(aarzilli): only apply the escapeCheck to leaking parameters.
			if err := escapeCheck(actualArg, formalArg.name, g); err != nil {
				return nil, fmt.Errorf("cannot use %s as argument %s in function %s: %v", actualArg.Name, formalArg.name, fn.Name, err)
			}
A
aarzilli 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
		}

		//TODO(aarzilli): autmoatic wrapping in interfaces for cases not handled
		// by convertToEface.

		formalArgVar := newVariable(formalArg.name, uintptr(formalArg.off+fakeAddress), formalArg.typ, bi, argmemWriter)
		if err := formalArgVar.setValue(actualArg, actualArg.Name); err != nil {
			return nil, err
		}
	}

	return argmem, nil
}

func funcCallArgs(fn *Function, bi *BinaryInfo, includeRet bool) (argFrameSize int64, formalArgs []funcCallArg, err error) {
301
	const CFA = 0x1000
302
	vrdr := reader.Variables(bi.dwarf, fn.offset, reader.ToRelAddr(fn.Entry, bi.staticBase), int(^uint(0)>>1), false)
303 304 305 306 307 308 309 310 311

	// typechecks arguments, calculates argument frame size
	for vrdr.Next() {
		e := vrdr.Entry()
		if e.Tag != dwarf.TagFormalParameter {
			continue
		}
		entry, argname, typ, err := readVarEntry(e, bi)
		if err != nil {
A
aarzilli 已提交
312
			return 0, nil, err
313 314
		}
		typ = resolveTypedef(typ)
315 316
		locprog, _, err := bi.locationExpr(entry, dwarf.AttrLocation, fn.Entry)
		if err != nil {
A
aarzilli 已提交
317
			return 0, nil, fmt.Errorf("could not get argument location of %s: %v", argname, err)
318 319 320
		}
		off, _, err := op.ExecuteStackProgram(op.DwarfRegisters{CFA: CFA, FrameBase: CFA}, locprog)
		if err != nil {
A
aarzilli 已提交
321
			return 0, nil, fmt.Errorf("unsupported location expression for argument %s: %v", argname, err)
322 323 324 325 326 327 328 329
		}

		off -= CFA

		if e := off + typ.Size(); e > argFrameSize {
			argFrameSize = e
		}

A
aarzilli 已提交
330 331
		if isret, _ := entry.Val(dwarf.AttrVarParam).(bool); !isret || includeRet {
			formalArgs = append(formalArgs, funcCallArg{name: argname, typ: typ, off: off, isret: isret})
332 333 334
		}
	}
	if err := vrdr.Err(); err != nil {
A
aarzilli 已提交
335
		return 0, nil, fmt.Errorf("DWARF read error: %v", err)
336 337 338 339 340 341
	}

	sort.Slice(formalArgs, func(i, j int) bool {
		return formalArgs[i].off < formalArgs[j].off
	})

A
aarzilli 已提交
342
	return argFrameSize, formalArgs, nil
343 344 345 346 347
}

func escapeCheck(v *Variable, name string, g *G) error {
	switch v.Kind {
	case reflect.Ptr:
348 349 350 351 352 353 354
		var w *Variable
		if len(v.Children) == 1 {
			// this branch is here to support pointers constructed with typecasts from ints or the '&' operator
			w = &v.Children[0]
		} else {
			w = v.maybeDereference()
		}
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
		return escapeCheckPointer(w.Addr, name, g)
	case reflect.Chan, reflect.String, reflect.Slice:
		return escapeCheckPointer(v.Base, name, g)
	case reflect.Map:
		sv := v.clone()
		sv.RealType = resolveTypedef(&(v.RealType.(*godwarf.MapType).TypedefType))
		sv = sv.maybeDereference()
		return escapeCheckPointer(sv.Addr, name, g)
	case reflect.Struct:
		t := v.RealType.(*godwarf.StructType)
		for _, field := range t.Field {
			fv, _ := v.toField(field)
			if err := escapeCheck(fv, fmt.Sprintf("%s.%s", name, field.Name), g); err != nil {
				return err
			}
		}
	case reflect.Array:
		for i := int64(0); i < v.Len; i++ {
			sv, _ := v.sliceAccess(int(i))
			if err := escapeCheck(sv, fmt.Sprintf("%s[%d]", name, i), g); err != nil {
				return err
			}
		}
	case reflect.Func:
379 380 381
		if err := escapeCheckPointer(uintptr(v.funcvalAddr()), name, g); err != nil {
			return err
		}
382 383 384 385 386 387 388
	}

	return nil
}

func escapeCheckPointer(addr uintptr, name string, g *G) error {
	if uint64(addr) >= g.stacklo && uint64(addr) < g.stackhi {
389
		return fmt.Errorf("stack object passed to escaping pointer: %s", name)
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
	}
	return nil
}

const (
	debugCallAXPrecheckFailed   = 8
	debugCallAXCompleteCall     = 0
	debugCallAXReadReturn       = 1
	debugCallAXReadPanic        = 2
	debugCallAXRestoreRegisters = 16
)

func (fncall *functionCallState) step(p Process) {
	bi := p.BinInfo()

	thread := p.CurrentThread()
	regs, err := thread.Registers(false)
	if err != nil {
		fncall.err = err
		fncall.finished = true
		fncall.inProgress = false
		return
	}
413
	regs = regs.Copy()
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

	rax, _ := regs.Get(int(x86asm.RAX))

	if logflags.FnCall() {
		loc, _ := thread.Location()
		var pc uint64
		var fnname string
		if loc != nil {
			pc = loc.PC
			if loc.Fn != nil {
				fnname = loc.Fn.Name
			}
		}
		fncallLog("function call interrupt rax=%#x (PC=%#x in %s)\n", rax, pc, fnname)
	}

	switch rax {
	case debugCallAXPrecheckFailed:
		// get error from top of the stack and return it to user
		errvar, err := readTopstackVariable(thread, regs, "string", loadFullValue)
		if err != nil {
			fncall.err = fmt.Errorf("could not get precheck error reason: %v", err)
			break
		}
		errvar.Name = "err"
		fncall.err = fmt.Errorf("%v", constant.StringVal(errvar.Value))

	case debugCallAXCompleteCall:
		// write arguments to the stack, call final function
		n, err := thread.WriteMemory(uintptr(regs.SP()), fncall.argmem)
		if err != nil {
			fncall.err = fmt.Errorf("could not write arguments: %v", err)
		}
		if n != len(fncall.argmem) {
			fncall.err = fmt.Errorf("short argument write: %d %d", n, len(fncall.argmem))
		}
450 451 452 453 454
		if fncall.closureAddr != 0 {
			// When calling a function pointer we must set the DX register to the
			// address of the function pointer itself.
			thread.SetDX(fncall.closureAddr)
		}
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
		callOP(bi, thread, regs, fncall.fn.Entry)

	case debugCallAXRestoreRegisters:
		// runtime requests that we restore the registers (all except pc and sp),
		// this is also the last step of the function call protocol.
		fncall.finished = true
		pc, sp := regs.PC(), regs.SP()
		if err := thread.RestoreRegisters(fncall.savedRegs); err != nil {
			fncall.err = fmt.Errorf("could not restore registers: %v", err)
		}
		if err := thread.SetPC(pc); err != nil {
			fncall.err = fmt.Errorf("could not restore PC: %v", err)
		}
		if err := thread.SetSP(sp); err != nil {
			fncall.err = fmt.Errorf("could not restore SP: %v", err)
		}
		if err := stepInstructionOut(p, thread, debugCallFunctionName, debugCallFunctionName); err != nil {
			fncall.err = fmt.Errorf("could not step out of %s: %v", debugCallFunctionName, err)
		}

	case debugCallAXReadReturn:
		// read return arguments from stack
		if fncall.retLoadCfg == nil || fncall.panicvar != nil {
			break
		}
		scope, err := ThreadScope(thread)
		if err != nil {
			fncall.err = fmt.Errorf("could not get return values: %v", err)
			break
		}

		// pretend we are still inside the function we called
		fakeFunctionEntryScope(scope, fncall.fn, int64(regs.SP()), regs.SP()-uint64(bi.Arch.PtrSize()))

		fncall.retvars, err = scope.Locals()
		if err != nil {
			fncall.err = fmt.Errorf("could not get return values: %v", err)
			break
		}
		fncall.retvars = filterVariables(fncall.retvars, func(v *Variable) bool {
			return (v.Flags & VariableReturnArgument) != 0
		})

		loadValues(fncall.retvars, *fncall.retLoadCfg)

	case debugCallAXReadPanic:
		// read panic value from stack
		if fncall.retLoadCfg == nil {
			return
		}
		fncall.panicvar, err = readTopstackVariable(thread, regs, "interface {}", *fncall.retLoadCfg)
		if err != nil {
			fncall.err = fmt.Errorf("could not get panic: %v", err)
			break
		}
		fncall.panicvar.Name = "~panic"
		fncall.panicvar.loadValue(*fncall.retLoadCfg)
		if fncall.panicvar.Unreadable != nil {
			fncall.err = fmt.Errorf("could not get panic: %v", fncall.panicvar.Unreadable)
			break
		}

	default:
		// Got an unknown AX value, this is probably bad but the safest thing
		// possible is to ignore it and hope it didn't matter.
		fncallLog("unknown value of AX %#x", rax)
	}
}

func readTopstackVariable(thread Thread, regs Registers, typename string, loadCfg LoadConfig) (*Variable, error) {
	bi := thread.BinInfo()
	scope, err := ThreadScope(thread)
	if err != nil {
		return nil, err
	}
	typ, err := bi.findType(typename)
	if err != nil {
		return nil, err
	}
	v := scope.newVariable("", uintptr(regs.SP()), typ, scope.Mem)
	v.loadValue(loadCfg)
	if v.Unreadable != nil {
		return nil, v.Unreadable
	}
	return v, nil
}

// fakeEntryScope alters scope to pretend that we are at the entry point of
// fn and CFA and SP are the ones passed as argument.
// This function is used to create a scope for a call frame that doesn't
// exist anymore, to read the return variables of an injected function call,
// or after a stepout command.
func fakeFunctionEntryScope(scope *EvalScope, fn *Function, cfa int64, sp uint64) error {
	scope.PC = fn.Entry
	scope.Fn = fn
	scope.File, scope.Line, _ = scope.BinInfo.PCToLine(fn.Entry)

	scope.Regs.CFA = cfa
	scope.Regs.Regs[scope.Regs.SPRegNum].Uint64Val = sp

	scope.BinInfo.dwarfReader.Seek(fn.offset)
	e, err := scope.BinInfo.dwarfReader.Next()
	if err != nil {
		return err
	}
	scope.Regs.FrameBase, _, _, _ = scope.BinInfo.Location(e, dwarf.AttrFrameBase, scope.PC, scope.Regs)
	return nil
}

func (fncall *functionCallState) returnValues() []*Variable {
	if fncall.panicvar != nil {
		return []*Variable{fncall.panicvar}
	}
	return fncall.retvars
}