github.com/cnboonhan/delve@v0.0.0-20230908061759-363f2388c2fb/pkg/proc/eval.go (about) 1 package proc 2 3 import ( 4 "bytes" 5 "debug/dwarf" 6 "errors" 7 "fmt" 8 "go/ast" 9 "go/constant" 10 "go/parser" 11 "go/printer" 12 "go/scanner" 13 "go/token" 14 "reflect" 15 "sort" 16 "strconv" 17 "strings" 18 19 "github.com/go-delve/delve/pkg/dwarf/godwarf" 20 "github.com/go-delve/delve/pkg/dwarf/op" 21 "github.com/go-delve/delve/pkg/dwarf/reader" 22 "github.com/go-delve/delve/pkg/goversion" 23 "github.com/go-delve/delve/pkg/logflags" 24 ) 25 26 var errOperationOnSpecialFloat = errors.New("operations on non-finite floats not implemented") 27 28 const goDictionaryName = ".dict" 29 30 // EvalScope is the scope for variable evaluation. Contains the thread, 31 // current location (PC), and canonical frame address. 32 type EvalScope struct { 33 Location 34 Regs op.DwarfRegisters 35 Mem MemoryReadWriter // Target's memory 36 g *G 37 threadID int 38 BinInfo *BinaryInfo 39 target *Target 40 loadCfg *LoadConfig 41 42 frameOffset int64 43 44 // When the following pointer is not nil this EvalScope was created 45 // by CallFunction and the expression evaluation is executing on a 46 // different goroutine from the debugger's main goroutine. 47 // Under this circumstance the expression evaluator can make function 48 // calls by setting up the runtime.debugCallV1 call and then writing a 49 // value to the continueRequest channel. 50 // When a value is written to continueRequest the debugger's main goroutine 51 // will call Continue, when the runtime in the target process sends us a 52 // request in the function call protocol the debugger's main goroutine will 53 // write a value to the continueCompleted channel. 54 // The goroutine executing the expression evaluation shall signal that the 55 // evaluation is complete by closing the continueRequest channel. 56 callCtx *callContext 57 58 dictAddr uint64 // dictionary address for instantiated generic functions 59 } 60 61 type localsFlags uint8 62 63 const ( 64 // If localsTrustArgOrder is set function arguments that don't have an 65 // address will have one assigned by looking at their position in the argument 66 // list. 67 localsTrustArgOrder localsFlags = 1 << iota 68 69 // If localsNoDeclLineCheck the declaration line isn't checked at 70 // all to determine if the variable is in scope. 71 localsNoDeclLineCheck 72 ) 73 74 // ConvertEvalScope returns a new EvalScope in the context of the 75 // specified goroutine ID and stack frame. 76 // If deferCall is > 0 the eval scope will be relative to the specified deferred call. 77 func ConvertEvalScope(dbp *Target, gid int64, frame, deferCall int) (*EvalScope, error) { 78 if _, err := dbp.Valid(); err != nil { 79 return nil, err 80 } 81 ct := dbp.CurrentThread() 82 threadID := ct.ThreadID() 83 g, err := FindGoroutine(dbp, gid) 84 if err != nil { 85 return nil, err 86 } 87 88 var opts StacktraceOptions 89 if deferCall > 0 { 90 opts = StacktraceReadDefers 91 } 92 93 var locs []Stackframe 94 if g != nil { 95 if g.Thread != nil { 96 threadID = g.Thread.ThreadID() 97 } 98 locs, err = GoroutineStacktrace(dbp, g, frame+1, opts) 99 } else { 100 locs, err = ThreadStacktrace(dbp, ct, frame+1) 101 } 102 if err != nil { 103 return nil, err 104 } 105 106 if frame >= len(locs) { 107 return nil, fmt.Errorf("Frame %d does not exist in goroutine %d", frame, gid) 108 } 109 110 if deferCall > 0 { 111 if deferCall-1 >= len(locs[frame].Defers) { 112 return nil, fmt.Errorf("Frame %d only has %d deferred calls", frame, len(locs[frame].Defers)) 113 } 114 115 d := locs[frame].Defers[deferCall-1] 116 if d.Unreadable != nil { 117 return nil, d.Unreadable 118 } 119 120 return d.EvalScope(dbp, ct) 121 } 122 123 return FrameToScope(dbp, dbp.Memory(), g, threadID, locs[frame:]...), nil 124 } 125 126 // FrameToScope returns a new EvalScope for frames[0]. 127 // If frames has at least two elements all memory between 128 // frames[0].Regs.SP() and frames[1].Regs.CFA will be cached. 129 // Otherwise all memory between frames[0].Regs.SP() and frames[0].Regs.CFA 130 // will be cached. 131 func FrameToScope(t *Target, thread MemoryReadWriter, g *G, threadID int, frames ...Stackframe) *EvalScope { 132 // Creates a cacheMem that will preload the entire stack frame the first 133 // time any local variable is read. 134 // Remember that the stack grows downward in memory. 135 minaddr := frames[0].Regs.SP() 136 var maxaddr uint64 137 if len(frames) > 1 && frames[0].SystemStack == frames[1].SystemStack { 138 maxaddr = uint64(frames[1].Regs.CFA) 139 } else { 140 maxaddr = uint64(frames[0].Regs.CFA) 141 } 142 if maxaddr > minaddr && maxaddr-minaddr < maxFramePrefetchSize { 143 thread = cacheMemory(thread, minaddr, int(maxaddr-minaddr)) 144 } 145 146 s := &EvalScope{Location: frames[0].Call, Regs: frames[0].Regs, Mem: thread, g: g, BinInfo: t.BinInfo(), target: t, frameOffset: frames[0].FrameOffset(), threadID: threadID} 147 s.PC = frames[0].lastpc 148 return s 149 } 150 151 // ThreadScope returns an EvalScope for the given thread. 152 func ThreadScope(t *Target, thread Thread) (*EvalScope, error) { 153 locations, err := ThreadStacktrace(t, thread, 1) 154 if err != nil { 155 return nil, err 156 } 157 if len(locations) < 1 { 158 return nil, errors.New("could not decode first frame") 159 } 160 return FrameToScope(t, thread.ProcessMemory(), nil, thread.ThreadID(), locations...), nil 161 } 162 163 // GoroutineScope returns an EvalScope for the goroutine running on the given thread. 164 func GoroutineScope(t *Target, thread Thread) (*EvalScope, error) { 165 locations, err := ThreadStacktrace(t, thread, 1) 166 if err != nil { 167 return nil, err 168 } 169 if len(locations) < 1 { 170 return nil, errors.New("could not decode first frame") 171 } 172 g, err := GetG(thread) 173 if err != nil { 174 return nil, err 175 } 176 threadID := 0 177 if g.Thread != nil { 178 threadID = g.Thread.ThreadID() 179 } 180 return FrameToScope(t, thread.ProcessMemory(), g, threadID, locations...), nil 181 } 182 183 // EvalExpression returns the value of the given expression. 184 func (scope *EvalScope) EvalExpression(expr string, cfg LoadConfig) (*Variable, error) { 185 if scope.callCtx != nil { 186 // makes sure that the other goroutine won't wait forever if we make a mistake 187 defer close(scope.callCtx.continueRequest) 188 } 189 t, err := parser.ParseExpr(expr) 190 if eqOff, isAs := isAssignment(err); scope.callCtx != nil && isAs { 191 lexpr := expr[:eqOff] 192 rexpr := expr[eqOff+1:] 193 err := scope.SetVariable(lexpr, rexpr) 194 scope.callCtx.doReturn(nil, err) 195 return nil, err 196 } 197 if err != nil { 198 scope.callCtx.doReturn(nil, err) 199 return nil, err 200 } 201 202 scope.loadCfg = &cfg 203 204 ev, err := scope.evalAST(t) 205 if err != nil { 206 scope.callCtx.doReturn(nil, err) 207 return nil, err 208 } 209 ev.loadValue(cfg) 210 if ev.Name == "" { 211 ev.Name = expr 212 } 213 scope.callCtx.doReturn(ev, nil) 214 return ev, nil 215 } 216 217 // ChanGoroutines returns the list of goroutines waiting to receive from or 218 // send to the channel. 219 func (scope *EvalScope) ChanGoroutines(expr string, start, count int) ([]int64, error) { 220 t, err := parser.ParseExpr(expr) 221 if err != nil { 222 return nil, err 223 } 224 v, err := scope.evalAST(t) 225 if err != nil { 226 return nil, err 227 } 228 if v.Kind != reflect.Chan { 229 return nil, nil 230 } 231 232 structMemberMulti := func(v *Variable, names ...string) *Variable { 233 for _, name := range names { 234 var err error 235 v, err = v.structMember(name) 236 if err != nil { 237 return nil 238 } 239 } 240 return v 241 } 242 243 waitqFirst := func(qname string) *Variable { 244 qvar := structMemberMulti(v, qname, "first") 245 if qvar == nil { 246 return nil 247 } 248 return qvar.maybeDereference() 249 } 250 251 var goids []int64 252 253 waitqToGoIDSlice := func(qvar *Variable) error { 254 if qvar == nil { 255 return nil 256 } 257 for { 258 if qvar.Addr == 0 { 259 return nil 260 } 261 if len(goids) > count { 262 return nil 263 } 264 goidVar := structMemberMulti(qvar, "g", "goid") 265 if goidVar == nil { 266 return nil 267 } 268 goidVar.loadValue(loadSingleValue) 269 if goidVar.Unreadable != nil { 270 return goidVar.Unreadable 271 } 272 goid, _ := constant.Int64Val(goidVar.Value) 273 if start > 0 { 274 start-- 275 } else { 276 goids = append(goids, goid) 277 } 278 279 nextVar, err := qvar.structMember("next") 280 if err != nil { 281 return err 282 } 283 qvar = nextVar.maybeDereference() 284 } 285 } 286 287 recvqVar := waitqFirst("recvq") 288 err = waitqToGoIDSlice(recvqVar) 289 if err != nil { 290 return nil, err 291 } 292 sendqVar := waitqFirst("sendq") 293 err = waitqToGoIDSlice(sendqVar) 294 if err != nil { 295 return nil, err 296 } 297 return goids, nil 298 } 299 300 func isAssignment(err error) (int, bool) { 301 el, isScannerErr := err.(scanner.ErrorList) 302 if isScannerErr && el[0].Msg == "expected '==', found '='" { 303 return el[0].Pos.Offset, true 304 } 305 return 0, false 306 } 307 308 // Locals returns all variables in 'scope'. 309 func (scope *EvalScope) Locals(flags localsFlags) ([]*Variable, error) { 310 if scope.Fn == nil { 311 return nil, errors.New("unable to find function context") 312 } 313 314 trustArgOrder := (flags&localsTrustArgOrder != 0) && scope.BinInfo.Producer() != "" && goversion.ProducerAfterOrEqual(scope.BinInfo.Producer(), 1, 12) && scope.Fn != nil && (scope.PC == scope.Fn.Entry) 315 316 dwarfTree, err := scope.image().getDwarfTree(scope.Fn.offset) 317 if err != nil { 318 return nil, err 319 } 320 321 variablesFlags := reader.VariablesOnlyVisible 322 if flags&localsNoDeclLineCheck != 0 { 323 variablesFlags = reader.VariablesNoDeclLineCheck 324 } 325 if scope.BinInfo.Producer() != "" && goversion.ProducerAfterOrEqual(scope.BinInfo.Producer(), 1, 15) { 326 variablesFlags |= reader.VariablesTrustDeclLine 327 } 328 329 varEntries := reader.Variables(dwarfTree, scope.PC, scope.Line, variablesFlags) 330 331 // look for dictionary entry 332 if scope.dictAddr == 0 { 333 for _, entry := range varEntries { 334 name, _ := entry.Val(dwarf.AttrName).(string) 335 if name == goDictionaryName { 336 dictVar, err := extractVarInfoFromEntry(scope.target, scope.BinInfo, scope.image(), scope.Regs, scope.Mem, entry.Tree, 0) 337 if err != nil { 338 logflags.DebuggerLogger().Errorf("could not load %s variable: %v", name, err) 339 } else if dictVar.Unreadable != nil { 340 logflags.DebuggerLogger().Errorf("could not load %s variable: %v", name, dictVar.Unreadable) 341 } else { 342 scope.dictAddr, err = readUintRaw(dictVar.mem, dictVar.Addr, int64(scope.BinInfo.Arch.PtrSize())) 343 if err != nil { 344 logflags.DebuggerLogger().Errorf("could not load %s variable: %v", name, err) 345 } 346 } 347 break 348 } 349 } 350 } 351 352 vars := make([]*Variable, 0, len(varEntries)) 353 depths := make([]int, 0, len(varEntries)) 354 for _, entry := range varEntries { 355 if name, _ := entry.Val(dwarf.AttrName).(string); name == goDictionaryName { 356 continue 357 } 358 val, err := extractVarInfoFromEntry(scope.target, scope.BinInfo, scope.image(), scope.Regs, scope.Mem, entry.Tree, scope.dictAddr) 359 if err != nil { 360 // skip variables that we can't parse yet 361 continue 362 } 363 if trustArgOrder && ((val.Unreadable != nil && val.Addr == 0) || val.Flags&VariableFakeAddress != 0) && entry.Tag == dwarf.TagFormalParameter { 364 addr := afterLastArgAddr(vars) 365 if addr == 0 { 366 addr = uint64(scope.Regs.CFA) 367 } 368 addr = uint64(alignAddr(int64(addr), val.DwarfType.Align())) 369 val = newVariable(val.Name, addr, val.DwarfType, scope.BinInfo, scope.Mem) 370 } 371 vars = append(vars, val) 372 depth := entry.Depth 373 if entry.Tag == dwarf.TagFormalParameter { 374 if depth <= 1 { 375 depth = 0 376 } 377 isret, _ := entry.Val(dwarf.AttrVarParam).(bool) 378 if isret { 379 val.Flags |= VariableReturnArgument 380 } else { 381 val.Flags |= VariableArgument 382 } 383 } 384 depths = append(depths, depth) 385 } 386 387 if len(vars) == 0 { 388 return vars, nil 389 } 390 391 sort.Stable(&variablesByDepthAndDeclLine{vars, depths}) 392 393 lvn := map[string]*Variable{} // lvn[n] is the last variable we saw named n 394 395 for i, v := range vars { 396 if name := v.Name; len(name) > 1 && name[0] == '&' { 397 locationExpr := v.LocationExpr 398 declLine := v.DeclLine 399 v = v.maybeDereference() 400 if v.Addr == 0 && v.Unreadable == nil { 401 v.Unreadable = fmt.Errorf("no address for escaped variable") 402 } 403 v.Name = name[1:] 404 v.Flags |= VariableEscaped 405 // See https://github.com/go-delve/delve/issues/2049 for details 406 if locationExpr != nil { 407 locationExpr.isEscaped = true 408 v.LocationExpr = locationExpr 409 } 410 v.DeclLine = declLine 411 vars[i] = v 412 } 413 if otherv := lvn[v.Name]; otherv != nil { 414 otherv.Flags |= VariableShadowed 415 } 416 lvn[v.Name] = v 417 } 418 419 return vars, nil 420 } 421 422 func afterLastArgAddr(vars []*Variable) uint64 { 423 for i := len(vars) - 1; i >= 0; i-- { 424 v := vars[i] 425 if (v.Flags&VariableArgument != 0) || (v.Flags&VariableReturnArgument != 0) { 426 return v.Addr + uint64(v.DwarfType.Size()) 427 } 428 } 429 return 0 430 } 431 432 // setValue writes the value of srcv to dstv. 433 // - If srcv is a numerical literal constant and srcv is of a compatible type 434 // the necessary type conversion is performed. 435 // - If srcv is nil and dstv is of a nil'able type then dstv is nilled. 436 // - If srcv is the empty string and dstv is a string then dstv is set to the 437 // empty string. 438 // - If dstv is an "interface {}" and srcv is either an interface (possibly 439 // non-empty) or a pointer shaped type (map, channel, pointer or struct 440 // containing a single pointer field) the type conversion to "interface {}" 441 // is performed. 442 // - If srcv and dstv have the same type and are both addressable then the 443 // contents of srcv are copied byte-by-byte into dstv 444 func (scope *EvalScope) setValue(dstv, srcv *Variable, srcExpr string) error { 445 srcv.loadValue(loadSingleValue) 446 447 typerr := srcv.isType(dstv.RealType, dstv.Kind) 448 if _, isTypeConvErr := typerr.(*typeConvErr); isTypeConvErr { 449 // attempt iface -> eface and ptr-shaped -> eface conversions. 450 return convertToEface(srcv, dstv) 451 } 452 if typerr != nil { 453 return typerr 454 } 455 456 if srcv.Unreadable != nil { 457 //lint:ignore ST1005 backwards compatibility 458 return fmt.Errorf("Expression %q is unreadable: %v", srcExpr, srcv.Unreadable) 459 } 460 461 // Numerical types 462 switch dstv.Kind { 463 case reflect.Float32, reflect.Float64: 464 f, _ := constant.Float64Val(srcv.Value) 465 return dstv.writeFloatRaw(f, dstv.RealType.Size()) 466 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 467 n, _ := constant.Int64Val(srcv.Value) 468 return dstv.writeUint(uint64(n), dstv.RealType.Size()) 469 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 470 n, _ := constant.Uint64Val(srcv.Value) 471 return dstv.writeUint(n, dstv.RealType.Size()) 472 case reflect.Bool: 473 return dstv.writeBool(constant.BoolVal(srcv.Value)) 474 case reflect.Complex64, reflect.Complex128: 475 real, _ := constant.Float64Val(constant.Real(srcv.Value)) 476 imag, _ := constant.Float64Val(constant.Imag(srcv.Value)) 477 return dstv.writeComplex(real, imag, dstv.RealType.Size()) 478 case reflect.Func: 479 if dstv.RealType.Size() == 0 { 480 if dstv.Name != "" { 481 return fmt.Errorf("can not assign to %s", dstv.Name) 482 } 483 return errors.New("can not assign to function expression") 484 } 485 } 486 487 // nilling nillable variables 488 if srcv == nilVariable { 489 return dstv.writeZero() 490 } 491 492 if srcv.Kind == reflect.String { 493 if err := allocString(scope, srcv); err != nil { 494 return err 495 } 496 return dstv.writeString(uint64(srcv.Len), uint64(srcv.Base)) 497 } 498 499 // slice assignment (this is not handled by the writeCopy below so that 500 // results of a reslice operation can be used here). 501 if srcv.Kind == reflect.Slice { 502 return dstv.writeSlice(srcv.Len, srcv.Cap, srcv.Base) 503 } 504 505 // allow any integer to be converted to any pointer 506 if t, isptr := dstv.RealType.(*godwarf.PtrType); isptr { 507 return dstv.writeUint(uint64(srcv.Children[0].Addr), int64(t.ByteSize)) 508 } 509 510 // byte-by-byte copying for everything else, but the source must be addressable 511 if srcv.Addr != 0 { 512 return dstv.writeCopy(srcv) 513 } 514 515 return fmt.Errorf("can not set variables of type %s (not implemented)", dstv.Kind.String()) 516 } 517 518 // SetVariable sets the value of the named variable 519 func (scope *EvalScope) SetVariable(name, value string) error { 520 t, err := parser.ParseExpr(name) 521 if err != nil { 522 return err 523 } 524 525 xv, err := scope.evalAST(t) 526 if err != nil { 527 return err 528 } 529 530 if xv.Addr == 0 { 531 //lint:ignore ST1005 backwards compatibility 532 return fmt.Errorf("Can not assign to %q", name) 533 } 534 535 if xv.Unreadable != nil { 536 //lint:ignore ST1005 backwards compatibility 537 return fmt.Errorf("Expression %q is unreadable: %v", name, xv.Unreadable) 538 } 539 540 t, err = parser.ParseExpr(value) 541 if err != nil { 542 return err 543 } 544 545 yv, err := scope.evalAST(t) 546 if err != nil { 547 return err 548 } 549 550 return scope.setValue(xv, yv, value) 551 } 552 553 // LocalVariables returns all local variables from the current function scope. 554 func (scope *EvalScope) LocalVariables(cfg LoadConfig) ([]*Variable, error) { 555 vars, err := scope.Locals(0) 556 if err != nil { 557 return nil, err 558 } 559 vars = filterVariables(vars, func(v *Variable) bool { 560 return (v.Flags & (VariableArgument | VariableReturnArgument)) == 0 561 }) 562 cfg.MaxMapBuckets = maxMapBucketsFactor * cfg.MaxArrayValues 563 loadValues(vars, cfg) 564 return vars, nil 565 } 566 567 // FunctionArguments returns the name, value, and type of all current function arguments. 568 func (scope *EvalScope) FunctionArguments(cfg LoadConfig) ([]*Variable, error) { 569 vars, err := scope.Locals(0) 570 if err != nil { 571 return nil, err 572 } 573 vars = filterVariables(vars, func(v *Variable) bool { 574 return (v.Flags & (VariableArgument | VariableReturnArgument)) != 0 575 }) 576 cfg.MaxMapBuckets = maxMapBucketsFactor * cfg.MaxArrayValues 577 loadValues(vars, cfg) 578 return vars, nil 579 } 580 581 func filterVariables(vars []*Variable, pred func(v *Variable) bool) []*Variable { 582 r := make([]*Variable, 0, len(vars)) 583 for i := range vars { 584 if pred(vars[i]) { 585 r = append(r, vars[i]) 586 } 587 } 588 return r 589 } 590 591 func regsReplaceStaticBase(regs op.DwarfRegisters, image *Image) op.DwarfRegisters { 592 regs.StaticBase = image.StaticBase 593 return regs 594 } 595 596 // PackageVariables returns the name, value, and type of all package variables in the application. 597 func (scope *EvalScope) PackageVariables(cfg LoadConfig) ([]*Variable, error) { 598 pkgvars := make([]packageVar, len(scope.BinInfo.packageVars)) 599 copy(pkgvars, scope.BinInfo.packageVars) 600 sort.Slice(pkgvars, func(i, j int) bool { 601 if pkgvars[i].cu.image.addr == pkgvars[j].cu.image.addr { 602 return pkgvars[i].offset < pkgvars[j].offset 603 } 604 return pkgvars[i].cu.image.addr < pkgvars[j].cu.image.addr 605 }) 606 vars := make([]*Variable, 0, len(scope.BinInfo.packageVars)) 607 for _, pkgvar := range pkgvars { 608 reader := pkgvar.cu.image.dwarfReader 609 reader.Seek(pkgvar.offset) 610 entry, err := reader.Next() 611 if err != nil { 612 return nil, err 613 } 614 615 // Ignore errors trying to extract values 616 val, err := extractVarInfoFromEntry(scope.target, scope.BinInfo, pkgvar.cu.image, regsReplaceStaticBase(scope.Regs, pkgvar.cu.image), scope.Mem, godwarf.EntryToTree(entry), 0) 617 if val != nil && val.Kind == reflect.Invalid { 618 continue 619 } 620 if err != nil { 621 continue 622 } 623 val.loadValue(cfg) 624 vars = append(vars, val) 625 } 626 627 return vars, nil 628 } 629 630 func (scope *EvalScope) findGlobal(pkgName, varName string) (*Variable, error) { 631 for _, pkgPath := range scope.BinInfo.PackageMap[pkgName] { 632 v, err := scope.findGlobalInternal(pkgPath + "." + varName) 633 if err != nil || v != nil { 634 return v, err 635 } 636 } 637 v, err := scope.findGlobalInternal(pkgName + "." + varName) 638 if err != nil || v != nil { 639 return v, err 640 } 641 return nil, fmt.Errorf("could not find symbol value for %s.%s", pkgName, varName) 642 } 643 644 func (scope *EvalScope) findGlobalInternal(name string) (*Variable, error) { 645 for _, pkgvar := range scope.BinInfo.packageVars { 646 if pkgvar.name == name || strings.HasSuffix(pkgvar.name, "/"+name) { 647 reader := pkgvar.cu.image.dwarfReader 648 reader.Seek(pkgvar.offset) 649 entry, err := reader.Next() 650 if err != nil { 651 return nil, err 652 } 653 return extractVarInfoFromEntry(scope.target, scope.BinInfo, pkgvar.cu.image, regsReplaceStaticBase(scope.Regs, pkgvar.cu.image), scope.Mem, godwarf.EntryToTree(entry), 0) 654 } 655 } 656 for _, fn := range scope.BinInfo.Functions { 657 if fn.Name == name || strings.HasSuffix(fn.Name, "/"+name) { 658 //TODO(aarzilli): convert function entry into a function type? 659 r := newVariable(fn.Name, fn.Entry, &godwarf.FuncType{}, scope.BinInfo, scope.Mem) 660 r.Value = constant.MakeString(fn.Name) 661 r.Base = fn.Entry 662 r.loaded = true 663 if fn.Entry == 0 { 664 r.Unreadable = fmt.Errorf("function %s is inlined", fn.Name) 665 } 666 return r, nil 667 } 668 } 669 for dwref, ctyp := range scope.BinInfo.consts { 670 for _, cval := range ctyp.values { 671 if cval.fullName == name || strings.HasSuffix(cval.fullName, "/"+name) { 672 t, err := scope.BinInfo.Images[dwref.imageIndex].Type(dwref.offset) 673 if err != nil { 674 return nil, err 675 } 676 v := newVariable(name, 0x0, t, scope.BinInfo, scope.Mem) 677 switch v.Kind { 678 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 679 v.Value = constant.MakeInt64(cval.value) 680 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 681 v.Value = constant.MakeUint64(uint64(cval.value)) 682 default: 683 return nil, fmt.Errorf("unsupported constant kind %v", v.Kind) 684 } 685 v.Flags |= VariableConstant 686 v.loaded = true 687 return v, nil 688 } 689 } 690 } 691 return nil, nil 692 } 693 694 // image returns the image containing the current function. 695 func (scope *EvalScope) image() *Image { 696 return scope.BinInfo.funcToImage(scope.Fn) 697 } 698 699 func (scope *EvalScope) evalAST(t ast.Expr) (*Variable, error) { 700 switch node := t.(type) { 701 case *ast.CallExpr: 702 return scope.evalTypeCastOrFuncCall(node) 703 704 case *ast.Ident: 705 return scope.evalIdent(node) 706 707 case *ast.ParenExpr: 708 // otherwise just eval recursively 709 return scope.evalAST(node.X) 710 711 case *ast.SelectorExpr: // <expression>.<identifier> 712 // try to interpret the selector as a package variable 713 if maybePkg, ok := node.X.(*ast.Ident); ok { 714 if maybePkg.Name == "runtime" && node.Sel.Name == "curg" { 715 if scope.g == nil { 716 typ, err := scope.BinInfo.findType("runtime.g") 717 if err != nil { 718 return nil, fmt.Errorf("could not find runtime.g: %v", err) 719 } 720 gvar := newVariable("curg", fakeAddressUnresolv, typ, scope.BinInfo, scope.Mem) 721 gvar.loaded = true 722 gvar.Flags = VariableFakeAddress 723 gvar.Children = append(gvar.Children, *newConstant(constant.MakeInt64(0), scope.Mem)) 724 gvar.Children[0].Name = "goid" 725 return gvar, nil 726 } 727 return scope.g.variable.clone(), nil 728 } else if maybePkg.Name == "runtime" && node.Sel.Name == "frameoff" { 729 return newConstant(constant.MakeInt64(scope.frameOffset), scope.Mem), nil 730 } else if maybePkg.Name == "runtime" && node.Sel.Name == "threadid" { 731 return newConstant(constant.MakeInt64(int64(scope.threadID)), scope.Mem), nil 732 } else if v, err := scope.findGlobal(maybePkg.Name, node.Sel.Name); err == nil { 733 return v, nil 734 } 735 } 736 // try to accept "package/path".varname syntax for package variables 737 if maybePkg, ok := node.X.(*ast.BasicLit); ok && maybePkg.Kind == token.STRING { 738 pkgpath, err := strconv.Unquote(maybePkg.Value) 739 if err == nil { 740 if v, err := scope.findGlobal(pkgpath, node.Sel.Name); err == nil { 741 return v, nil 742 } 743 } 744 } 745 // if it's not a package variable then it must be a struct member access 746 return scope.evalStructSelector(node) 747 748 case *ast.TypeAssertExpr: // <expression>.(<type>) 749 return scope.evalTypeAssert(node) 750 751 case *ast.IndexExpr: 752 return scope.evalIndex(node) 753 754 case *ast.SliceExpr: 755 if node.Slice3 { 756 return nil, fmt.Errorf("3-index slice expressions not supported") 757 } 758 return scope.evalReslice(node) 759 760 case *ast.StarExpr: 761 // pointer dereferencing *<expression> 762 return scope.evalPointerDeref(node) 763 764 case *ast.UnaryExpr: 765 // The unary operators we support are +, - and & (note that unary * is parsed as ast.StarExpr) 766 switch node.Op { 767 case token.AND: 768 return scope.evalAddrOf(node) 769 770 default: 771 return scope.evalUnary(node) 772 } 773 774 case *ast.BinaryExpr: 775 return scope.evalBinary(node) 776 777 case *ast.BasicLit: 778 return newConstant(constant.MakeFromLiteral(node.Value, node.Kind, 0), scope.Mem), nil 779 780 default: 781 return nil, fmt.Errorf("expression %T not implemented", t) 782 783 } 784 } 785 786 func exprToString(t ast.Expr) string { 787 var buf bytes.Buffer 788 printer.Fprint(&buf, token.NewFileSet(), t) 789 return buf.String() 790 } 791 792 func removeParen(n ast.Expr) ast.Expr { 793 for { 794 p, ok := n.(*ast.ParenExpr) 795 if !ok { 796 break 797 } 798 n = p.X 799 } 800 return n 801 } 802 803 // evalTypeCastOrFuncCall evaluates a type cast or a function call 804 func (scope *EvalScope) evalTypeCastOrFuncCall(node *ast.CallExpr) (*Variable, error) { 805 if len(node.Args) != 1 { 806 // Things that have more or less than one argument are always function calls. 807 return evalFunctionCall(scope, node) 808 } 809 810 ambiguous := func() (*Variable, error) { 811 // Ambiguous, could be a function call or a type cast, if node.Fun can be 812 // evaluated then try to treat it as a function call, otherwise try the 813 // type cast. 814 _, err0 := scope.evalAST(node.Fun) 815 if err0 == nil { 816 return evalFunctionCall(scope, node) 817 } 818 v, err := scope.evalTypeCast(node) 819 if err == reader.ErrTypeNotFound { 820 return nil, fmt.Errorf("could not evaluate function or type %s: %v", exprToString(node.Fun), err0) 821 } 822 return v, err 823 } 824 825 fnnode := node.Fun 826 for { 827 fnnode = removeParen(fnnode) 828 n, _ := fnnode.(*ast.StarExpr) 829 if n == nil { 830 break 831 } 832 fnnode = n.X 833 } 834 835 switch n := fnnode.(type) { 836 case *ast.BasicLit: 837 // It can only be a ("type string")(x) type cast 838 return scope.evalTypeCast(node) 839 case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType: 840 return scope.evalTypeCast(node) 841 case *ast.SelectorExpr: 842 if _, isident := n.X.(*ast.Ident); isident { 843 return ambiguous() 844 } 845 return evalFunctionCall(scope, node) 846 case *ast.Ident: 847 if supportedBuiltins[n.Name] { 848 return evalFunctionCall(scope, node) 849 } 850 return ambiguous() 851 case *ast.IndexExpr: 852 // Ambiguous, could be a parametric type 853 switch n.X.(type) { 854 case *ast.Ident, *ast.SelectorExpr: 855 // Do the type-cast first since evaluating node.Fun could be expensive. 856 v, err := scope.evalTypeCast(node) 857 if err == nil || err != reader.ErrTypeNotFound { 858 return v, err 859 } 860 return evalFunctionCall(scope, node) 861 default: 862 return evalFunctionCall(scope, node) 863 } 864 case *astIndexListExpr: 865 return scope.evalTypeCast(node) 866 default: 867 // All other expressions must be function calls 868 return evalFunctionCall(scope, node) 869 } 870 } 871 872 // Eval type cast expressions 873 func (scope *EvalScope) evalTypeCast(node *ast.CallExpr) (*Variable, error) { 874 argv, err := scope.evalAST(node.Args[0]) 875 if err != nil { 876 return nil, err 877 } 878 879 fnnode := node.Fun 880 881 // remove all enclosing parenthesis from the type name 882 fnnode = removeParen(fnnode) 883 884 targetTypeStr := exprToString(removeParen(node.Fun)) 885 styp, err := scope.BinInfo.findTypeExpr(fnnode) 886 if err != nil { 887 switch targetTypeStr { 888 case "[]byte", "[]uint8": 889 styp = fakeSliceType(fakeBasicType("uint", 8)) 890 case "[]int32", "[]rune": 891 styp = fakeSliceType(fakeBasicType("int", 32)) 892 default: 893 return nil, err 894 } 895 } 896 typ := resolveTypedef(styp) 897 898 converr := fmt.Errorf("can not convert %q to %s", exprToString(node.Args[0]), typ.String()) 899 900 // compatible underlying types 901 if typeCastCompatibleTypes(argv.RealType, typ) { 902 if ptyp, isptr := typ.(*godwarf.PtrType); argv.Kind == reflect.Ptr && argv.loaded && len(argv.Children) > 0 && isptr { 903 cv := argv.Children[0] 904 argv.Children[0] = *newVariable(cv.Name, cv.Addr, ptyp.Type, cv.bi, cv.mem) 905 argv.Children[0].OnlyAddr = true 906 } 907 argv.RealType = typ 908 argv.DwarfType = styp 909 return argv, nil 910 } 911 912 v := newVariable("", 0, styp, scope.BinInfo, scope.Mem) 913 v.loaded = true 914 915 switch ttyp := typ.(type) { 916 case *godwarf.PtrType: 917 switch argv.Kind { 918 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 919 // ok 920 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 921 // ok 922 default: 923 return nil, converr 924 } 925 926 argv.loadValue(loadSingleValue) 927 if argv.Unreadable != nil { 928 return nil, argv.Unreadable 929 } 930 931 n, _ := constant.Int64Val(argv.Value) 932 933 mem := scope.Mem 934 if scope.target != nil { 935 if mem2 := scope.target.findFakeMemory(uint64(n)); mem2 != nil { 936 mem = mem2 937 } 938 } 939 940 v.Children = []Variable{*(newVariable("", uint64(n), ttyp.Type, scope.BinInfo, mem))} 941 v.Children[0].OnlyAddr = true 942 return v, nil 943 944 case *godwarf.UintType: 945 argv.loadValue(loadSingleValue) 946 if argv.Unreadable != nil { 947 return nil, argv.Unreadable 948 } 949 switch argv.Kind { 950 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 951 n, _ := constant.Int64Val(argv.Value) 952 v.Value = constant.MakeUint64(convertInt(uint64(n), false, ttyp.Size())) 953 return v, nil 954 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 955 n, _ := constant.Uint64Val(argv.Value) 956 v.Value = constant.MakeUint64(convertInt(n, false, ttyp.Size())) 957 return v, nil 958 case reflect.Float32, reflect.Float64: 959 x, _ := constant.Float64Val(argv.Value) 960 v.Value = constant.MakeUint64(uint64(x)) 961 return v, nil 962 case reflect.Ptr: 963 v.Value = constant.MakeUint64(uint64(argv.Children[0].Addr)) 964 return v, nil 965 } 966 case *godwarf.IntType: 967 argv.loadValue(loadSingleValue) 968 if argv.Unreadable != nil { 969 return nil, argv.Unreadable 970 } 971 switch argv.Kind { 972 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 973 n, _ := constant.Int64Val(argv.Value) 974 v.Value = constant.MakeInt64(int64(convertInt(uint64(n), true, ttyp.Size()))) 975 return v, nil 976 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 977 n, _ := constant.Uint64Val(argv.Value) 978 v.Value = constant.MakeInt64(int64(convertInt(n, true, ttyp.Size()))) 979 return v, nil 980 case reflect.Float32, reflect.Float64: 981 x, _ := constant.Float64Val(argv.Value) 982 v.Value = constant.MakeInt64(int64(x)) 983 return v, nil 984 } 985 case *godwarf.FloatType: 986 argv.loadValue(loadSingleValue) 987 if argv.Unreadable != nil { 988 return nil, argv.Unreadable 989 } 990 switch argv.Kind { 991 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 992 fallthrough 993 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 994 fallthrough 995 case reflect.Float32, reflect.Float64: 996 v.Value = argv.Value 997 return v, nil 998 } 999 case *godwarf.ComplexType: 1000 argv.loadValue(loadSingleValue) 1001 if argv.Unreadable != nil { 1002 return nil, argv.Unreadable 1003 } 1004 switch argv.Kind { 1005 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 1006 fallthrough 1007 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 1008 fallthrough 1009 case reflect.Float32, reflect.Float64: 1010 v.Value = argv.Value 1011 return v, nil 1012 } 1013 } 1014 1015 cfg := loadFullValue 1016 if scope.loadCfg != nil { 1017 cfg = *scope.loadCfg 1018 } 1019 argv.loadValue(cfg) 1020 if argv.Unreadable != nil { 1021 return nil, argv.Unreadable 1022 } 1023 1024 switch ttyp := typ.(type) { 1025 case *godwarf.SliceType: 1026 switch ttyp.ElemType.Common().ReflectKind { 1027 case reflect.Uint8: 1028 if argv.Kind != reflect.String { 1029 return nil, converr 1030 } 1031 for i, ch := range []byte(constant.StringVal(argv.Value)) { 1032 e := newVariable("", argv.Addr+uint64(i), typ.(*godwarf.SliceType).ElemType, scope.BinInfo, argv.mem) 1033 e.loaded = true 1034 e.Value = constant.MakeInt64(int64(ch)) 1035 v.Children = append(v.Children, *e) 1036 } 1037 v.Len = int64(len(v.Children)) 1038 v.Cap = v.Len 1039 return v, nil 1040 1041 case reflect.Int32: 1042 if argv.Kind != reflect.String { 1043 return nil, converr 1044 } 1045 for i, ch := range constant.StringVal(argv.Value) { 1046 e := newVariable("", argv.Addr+uint64(i), typ.(*godwarf.SliceType).ElemType, scope.BinInfo, argv.mem) 1047 e.loaded = true 1048 e.Value = constant.MakeInt64(int64(ch)) 1049 v.Children = append(v.Children, *e) 1050 } 1051 v.Len = int64(len(v.Children)) 1052 v.Cap = v.Len 1053 return v, nil 1054 } 1055 1056 case *godwarf.StringType: 1057 switch argv.Kind { 1058 case reflect.String: 1059 s := constant.StringVal(argv.Value) 1060 v.Value = constant.MakeString(s) 1061 v.Len = int64(len(s)) 1062 return v, nil 1063 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: 1064 b, _ := constant.Int64Val(argv.Value) 1065 s := string(rune(b)) 1066 v.Value = constant.MakeString(s) 1067 v.Len = int64(len(s)) 1068 return v, nil 1069 case reflect.Slice, reflect.Array: 1070 var elem godwarf.Type 1071 if argv.Kind == reflect.Slice { 1072 elem = argv.RealType.(*godwarf.SliceType).ElemType 1073 } else { 1074 elem = argv.RealType.(*godwarf.ArrayType).Type 1075 } 1076 switch elemType := elem.(type) { 1077 case *godwarf.UintType: 1078 if elemType.Name != "uint8" && elemType.Name != "byte" { 1079 return nil, converr 1080 } 1081 bytes := make([]byte, len(argv.Children)) 1082 for i := range argv.Children { 1083 n, _ := constant.Int64Val(argv.Children[i].Value) 1084 bytes[i] = byte(n) 1085 } 1086 v.Value = constant.MakeString(string(bytes)) 1087 1088 case *godwarf.IntType: 1089 if elemType.Name != "int32" && elemType.Name != "rune" { 1090 return nil, converr 1091 } 1092 runes := make([]rune, len(argv.Children)) 1093 for i := range argv.Children { 1094 n, _ := constant.Int64Val(argv.Children[i].Value) 1095 runes[i] = rune(n) 1096 } 1097 v.Value = constant.MakeString(string(runes)) 1098 1099 default: 1100 return nil, converr 1101 } 1102 v.Len = int64(len(constant.StringVal(v.Value))) 1103 return v, nil 1104 } 1105 } 1106 1107 return nil, converr 1108 } 1109 1110 // typeCastCompatibleTypes returns true if typ1 and typ2 are compatible for 1111 // a type cast where only the type of the variable is changed. 1112 func typeCastCompatibleTypes(typ1, typ2 godwarf.Type) bool { 1113 if typ1 == nil || typ2 == nil || typ1.Common().Size() != typ2.Common().Size() || typ1.Common().Align() != typ2.Common().Align() { 1114 return false 1115 } 1116 1117 if typ1.String() == typ2.String() { 1118 return true 1119 } 1120 1121 switch ttyp1 := typ1.(type) { 1122 case *godwarf.PtrType: 1123 if ttyp2, ok := typ2.(*godwarf.PtrType); ok { 1124 _, isvoid1 := ttyp1.Type.(*godwarf.VoidType) 1125 _, isvoid2 := ttyp2.Type.(*godwarf.VoidType) 1126 if isvoid1 || isvoid2 { 1127 return true 1128 } 1129 // pointer types are compatible if their element types are compatible 1130 return typeCastCompatibleTypes(resolveTypedef(ttyp1.Type), resolveTypedef(ttyp2.Type)) 1131 } 1132 case *godwarf.StringType: 1133 if _, ok := typ2.(*godwarf.StringType); ok { 1134 return true 1135 } 1136 case *godwarf.StructType: 1137 if ttyp2, ok := typ2.(*godwarf.StructType); ok { 1138 // struct types are compatible if they have the same fields 1139 if len(ttyp1.Field) != len(ttyp2.Field) { 1140 return false 1141 } 1142 for i := range ttyp1.Field { 1143 if *ttyp1.Field[i] != *ttyp2.Field[i] { 1144 return false 1145 } 1146 } 1147 return true 1148 } 1149 case *godwarf.ComplexType: 1150 if _, ok := typ2.(*godwarf.ComplexType); ok { 1151 // size and alignment already checked above 1152 return true 1153 } 1154 case *godwarf.FloatType: 1155 if _, ok := typ2.(*godwarf.FloatType); ok { 1156 // size and alignment already checked above 1157 return true 1158 } 1159 case *godwarf.IntType: 1160 if _, ok := typ2.(*godwarf.IntType); ok { 1161 // size and alignment already checked above 1162 return true 1163 } 1164 case *godwarf.UintType: 1165 if _, ok := typ2.(*godwarf.UintType); ok { 1166 // size and alignment already checked above 1167 return true 1168 } 1169 case *godwarf.BoolType: 1170 if _, ok := typ2.(*godwarf.BoolType); ok { 1171 // size and alignment already checked above 1172 return true 1173 } 1174 } 1175 1176 return false 1177 } 1178 1179 func convertInt(n uint64, signed bool, size int64) uint64 { 1180 bits := uint64(size) * 8 1181 mask := uint64((1 << bits) - 1) 1182 r := n & mask 1183 if signed && (r>>(bits-1)) != 0 { 1184 // sign extension 1185 r |= ^uint64(0) &^ mask 1186 } 1187 return r 1188 } 1189 1190 var supportedBuiltins = map[string]bool{"cap": true, "len": true, "complex": true, "imag": true, "real": true} 1191 1192 func (scope *EvalScope) evalBuiltinCall(node *ast.CallExpr) (*Variable, error) { 1193 fnnode, ok := node.Fun.(*ast.Ident) 1194 if !ok { 1195 return nil, nil 1196 } 1197 1198 callBuiltinWithArgs := func(builtin func([]*Variable, []ast.Expr) (*Variable, error)) (*Variable, error) { 1199 args := make([]*Variable, len(node.Args)) 1200 1201 for i := range node.Args { 1202 v, err := scope.evalAST(node.Args[i]) 1203 if err != nil { 1204 return nil, err 1205 } 1206 args[i] = v 1207 } 1208 1209 return builtin(args, node.Args) 1210 } 1211 1212 switch fnnode.Name { 1213 case "cap": 1214 return callBuiltinWithArgs(capBuiltin) 1215 case "len": 1216 return callBuiltinWithArgs(lenBuiltin) 1217 case "complex": 1218 return callBuiltinWithArgs(complexBuiltin) 1219 case "imag": 1220 return callBuiltinWithArgs(imagBuiltin) 1221 case "real": 1222 return callBuiltinWithArgs(realBuiltin) 1223 } 1224 1225 return nil, nil 1226 } 1227 1228 func capBuiltin(args []*Variable, nodeargs []ast.Expr) (*Variable, error) { 1229 if len(args) != 1 { 1230 return nil, fmt.Errorf("wrong number of arguments to cap: %d", len(args)) 1231 } 1232 1233 arg := args[0] 1234 invalidArgErr := fmt.Errorf("invalid argument %s (type %s) for cap", exprToString(nodeargs[0]), arg.TypeString()) 1235 1236 switch arg.Kind { 1237 case reflect.Ptr: 1238 arg = arg.maybeDereference() 1239 if arg.Kind != reflect.Array { 1240 return nil, invalidArgErr 1241 } 1242 fallthrough 1243 case reflect.Array: 1244 return newConstant(constant.MakeInt64(arg.Len), arg.mem), nil 1245 case reflect.Slice: 1246 return newConstant(constant.MakeInt64(arg.Cap), arg.mem), nil 1247 case reflect.Chan: 1248 arg.loadValue(loadFullValue) 1249 if arg.Unreadable != nil { 1250 return nil, arg.Unreadable 1251 } 1252 if arg.Base == 0 { 1253 return newConstant(constant.MakeInt64(0), arg.mem), nil 1254 } 1255 return newConstant(arg.Children[1].Value, arg.mem), nil 1256 default: 1257 return nil, invalidArgErr 1258 } 1259 } 1260 1261 func lenBuiltin(args []*Variable, nodeargs []ast.Expr) (*Variable, error) { 1262 if len(args) != 1 { 1263 return nil, fmt.Errorf("wrong number of arguments to len: %d", len(args)) 1264 } 1265 arg := args[0] 1266 invalidArgErr := fmt.Errorf("invalid argument %s (type %s) for len", exprToString(nodeargs[0]), arg.TypeString()) 1267 1268 switch arg.Kind { 1269 case reflect.Ptr: 1270 arg = arg.maybeDereference() 1271 if arg.Kind != reflect.Array { 1272 return nil, invalidArgErr 1273 } 1274 fallthrough 1275 case reflect.Array, reflect.Slice, reflect.String: 1276 if arg.Unreadable != nil { 1277 return nil, arg.Unreadable 1278 } 1279 return newConstant(constant.MakeInt64(arg.Len), arg.mem), nil 1280 case reflect.Chan: 1281 arg.loadValue(loadFullValue) 1282 if arg.Unreadable != nil { 1283 return nil, arg.Unreadable 1284 } 1285 if arg.Base == 0 { 1286 return newConstant(constant.MakeInt64(0), arg.mem), nil 1287 } 1288 return newConstant(arg.Children[0].Value, arg.mem), nil 1289 case reflect.Map: 1290 it := arg.mapIterator() 1291 if arg.Unreadable != nil { 1292 return nil, arg.Unreadable 1293 } 1294 if it == nil { 1295 return newConstant(constant.MakeInt64(0), arg.mem), nil 1296 } 1297 return newConstant(constant.MakeInt64(arg.Len), arg.mem), nil 1298 default: 1299 return nil, invalidArgErr 1300 } 1301 } 1302 1303 func complexBuiltin(args []*Variable, nodeargs []ast.Expr) (*Variable, error) { 1304 if len(args) != 2 { 1305 return nil, fmt.Errorf("wrong number of arguments to complex: %d", len(args)) 1306 } 1307 1308 realev := args[0] 1309 imagev := args[1] 1310 1311 realev.loadValue(loadSingleValue) 1312 imagev.loadValue(loadSingleValue) 1313 1314 if realev.Unreadable != nil { 1315 return nil, realev.Unreadable 1316 } 1317 1318 if imagev.Unreadable != nil { 1319 return nil, imagev.Unreadable 1320 } 1321 1322 if realev.Value == nil || ((realev.Value.Kind() != constant.Int) && (realev.Value.Kind() != constant.Float)) { 1323 return nil, fmt.Errorf("invalid argument 1 %s (type %s) to complex", exprToString(nodeargs[0]), realev.TypeString()) 1324 } 1325 1326 if imagev.Value == nil || ((imagev.Value.Kind() != constant.Int) && (imagev.Value.Kind() != constant.Float)) { 1327 return nil, fmt.Errorf("invalid argument 2 %s (type %s) to complex", exprToString(nodeargs[1]), imagev.TypeString()) 1328 } 1329 1330 sz := int64(0) 1331 if realev.RealType != nil { 1332 sz = realev.RealType.(*godwarf.FloatType).Size() 1333 } 1334 if imagev.RealType != nil { 1335 isz := imagev.RealType.(*godwarf.FloatType).Size() 1336 if isz > sz { 1337 sz = isz 1338 } 1339 } 1340 1341 if sz == 0 { 1342 sz = 128 1343 } 1344 1345 typ := fakeBasicType("complex", int(sz)) 1346 1347 r := realev.newVariable("", 0, typ, nil) 1348 r.Value = constant.BinaryOp(realev.Value, token.ADD, constant.MakeImag(imagev.Value)) 1349 return r, nil 1350 } 1351 1352 func imagBuiltin(args []*Variable, nodeargs []ast.Expr) (*Variable, error) { 1353 if len(args) != 1 { 1354 return nil, fmt.Errorf("wrong number of arguments to imag: %d", len(args)) 1355 } 1356 1357 arg := args[0] 1358 arg.loadValue(loadSingleValue) 1359 1360 if arg.Unreadable != nil { 1361 return nil, arg.Unreadable 1362 } 1363 1364 if arg.Kind != reflect.Complex64 && arg.Kind != reflect.Complex128 { 1365 return nil, fmt.Errorf("invalid argument %s (type %s) to imag", exprToString(nodeargs[0]), arg.TypeString()) 1366 } 1367 1368 return newConstant(constant.Imag(arg.Value), arg.mem), nil 1369 } 1370 1371 func realBuiltin(args []*Variable, nodeargs []ast.Expr) (*Variable, error) { 1372 if len(args) != 1 { 1373 return nil, fmt.Errorf("wrong number of arguments to real: %d", len(args)) 1374 } 1375 1376 arg := args[0] 1377 arg.loadValue(loadSingleValue) 1378 1379 if arg.Unreadable != nil { 1380 return nil, arg.Unreadable 1381 } 1382 1383 if arg.Value == nil || ((arg.Value.Kind() != constant.Int) && (arg.Value.Kind() != constant.Float) && (arg.Value.Kind() != constant.Complex)) { 1384 return nil, fmt.Errorf("invalid argument %s (type %s) to real", exprToString(nodeargs[0]), arg.TypeString()) 1385 } 1386 1387 return newConstant(constant.Real(arg.Value), arg.mem), nil 1388 } 1389 1390 // Evaluates identifier expressions 1391 func (scope *EvalScope) evalIdent(node *ast.Ident) (*Variable, error) { 1392 switch node.Name { 1393 case "true", "false": 1394 return newConstant(constant.MakeBool(node.Name == "true"), scope.Mem), nil 1395 case "nil": 1396 return nilVariable, nil 1397 } 1398 1399 vars, err := scope.Locals(0) 1400 if err != nil { 1401 return nil, err 1402 } 1403 for i := range vars { 1404 if vars[i].Name == node.Name && vars[i].Flags&VariableShadowed == 0 { 1405 return vars[i], nil 1406 } 1407 } 1408 1409 // if it's not a local variable then it could be a package variable w/o explicit package name 1410 if scope.Fn != nil { 1411 if v, err := scope.findGlobal(scope.Fn.PackageName(), node.Name); err == nil { 1412 v.Name = node.Name 1413 return v, nil 1414 } 1415 } 1416 1417 // not a local variable, nor a global variable, try a CPU register 1418 if s := validRegisterName(node.Name); s != "" { 1419 if regnum, ok := scope.BinInfo.Arch.RegisterNameToDwarf(s); ok { 1420 if reg := scope.Regs.Reg(uint64(regnum)); reg != nil { 1421 reg.FillBytes() 1422 1423 var typ godwarf.Type 1424 if len(reg.Bytes) <= 8 { 1425 typ = fakeBasicType("uint", 64) 1426 } else { 1427 typ, err = scope.BinInfo.findType("string") 1428 if err != nil { 1429 return nil, err 1430 } 1431 } 1432 1433 v := newVariable(node.Name, 0, typ, scope.BinInfo, scope.Mem) 1434 if v.Kind == reflect.String { 1435 v.Len = int64(len(reg.Bytes) * 2) 1436 v.Base = fakeAddressUnresolv 1437 } 1438 v.Addr = fakeAddressUnresolv 1439 v.Flags = VariableCPURegister 1440 v.reg = reg 1441 return v, nil 1442 } 1443 } 1444 } 1445 1446 return nil, fmt.Errorf("could not find symbol value for %s", node.Name) 1447 } 1448 1449 // Evaluates expressions <subexpr>.<field name> where subexpr is not a package name 1450 func (scope *EvalScope) evalStructSelector(node *ast.SelectorExpr) (*Variable, error) { 1451 xv, err := scope.evalAST(node.X) 1452 if err != nil { 1453 return nil, err 1454 } 1455 1456 // Prevent abuse, attempting to call "nil.member" directly. 1457 if xv.Addr == 0 && xv.Name == "nil" { 1458 return nil, fmt.Errorf("%s (type %s) is not a struct", xv.Name, xv.TypeString()) 1459 } 1460 // Prevent abuse, attempting to call "\"fake\".member" directly. 1461 if xv.Addr == 0 && xv.Name == "" && xv.DwarfType == nil && xv.RealType == nil { 1462 return nil, fmt.Errorf("%s (type %s) is not a struct", xv.Value, xv.TypeString()) 1463 } 1464 // Special type conversions for CPU register variables (REGNAME.int8, etc) 1465 if xv.Flags&VariableCPURegister != 0 && !xv.loaded { 1466 return xv.registerVariableTypeConv(node.Sel.Name) 1467 } 1468 1469 rv, err := xv.findMethod(node.Sel.Name) 1470 if err != nil { 1471 return nil, err 1472 } 1473 if rv != nil { 1474 return rv, nil 1475 } 1476 return xv.structMember(node.Sel.Name) 1477 } 1478 1479 // Evaluates expressions <subexpr>.(<type>) 1480 func (scope *EvalScope) evalTypeAssert(node *ast.TypeAssertExpr) (*Variable, error) { 1481 xv, err := scope.evalAST(node.X) 1482 if err != nil { 1483 return nil, err 1484 } 1485 if xv.Kind != reflect.Interface { 1486 return nil, fmt.Errorf("expression %q not an interface", exprToString(node.X)) 1487 } 1488 xv.loadInterface(0, false, loadFullValue) 1489 if xv.Unreadable != nil { 1490 return nil, xv.Unreadable 1491 } 1492 if xv.Children[0].Unreadable != nil { 1493 return nil, xv.Children[0].Unreadable 1494 } 1495 if xv.Children[0].Addr == 0 { 1496 return nil, fmt.Errorf("interface conversion: %s is nil, not %s", xv.DwarfType.String(), exprToString(node.Type)) 1497 } 1498 // Accept .(data) as a type assertion that always succeeds, so that users 1499 // can access the data field of an interface without actually having to 1500 // type the concrete type. 1501 if idtyp, isident := node.Type.(*ast.Ident); !isident || idtyp.Name != "data" { 1502 typ, err := scope.BinInfo.findTypeExpr(node.Type) 1503 if err != nil { 1504 return nil, err 1505 } 1506 if xv.Children[0].DwarfType.Common().Name != typ.Common().Name { 1507 return nil, fmt.Errorf("interface conversion: %s is %s, not %s", xv.DwarfType.Common().Name, xv.Children[0].TypeString(), typ.Common().Name) 1508 } 1509 } 1510 // loadInterface will set OnlyAddr for the data member since here we are 1511 // passing false to loadData, however returning the variable with OnlyAddr 1512 // set here would be wrong since, once the expression evaluation 1513 // terminates, the value of this variable will be loaded. 1514 xv.Children[0].OnlyAddr = false 1515 return &xv.Children[0], nil 1516 } 1517 1518 // Evaluates expressions <subexpr>[<subexpr>] (subscript access to arrays, slices and maps) 1519 func (scope *EvalScope) evalIndex(node *ast.IndexExpr) (*Variable, error) { 1520 xev, err := scope.evalAST(node.X) 1521 if err != nil { 1522 return nil, err 1523 } 1524 if xev.Unreadable != nil { 1525 return nil, xev.Unreadable 1526 } 1527 1528 if xev.Flags&VariableCPtr == 0 { 1529 xev = xev.maybeDereference() 1530 } 1531 1532 idxev, err := scope.evalAST(node.Index) 1533 if err != nil { 1534 return nil, err 1535 } 1536 1537 cantindex := fmt.Errorf("expression %q (%s) does not support indexing", exprToString(node.X), xev.TypeString()) 1538 1539 switch xev.Kind { 1540 case reflect.Ptr: 1541 if xev == nilVariable { 1542 return nil, cantindex 1543 } 1544 if xev.Flags&VariableCPtr == 0 { 1545 _, isarrptr := xev.RealType.(*godwarf.PtrType).Type.(*godwarf.ArrayType) 1546 if !isarrptr { 1547 return nil, cantindex 1548 } 1549 xev = xev.maybeDereference() 1550 } 1551 fallthrough 1552 1553 case reflect.Slice, reflect.Array, reflect.String: 1554 if xev.Base == 0 { 1555 return nil, fmt.Errorf("can not index %q", exprToString(node.X)) 1556 } 1557 n, err := idxev.asInt() 1558 if err != nil { 1559 return nil, err 1560 } 1561 return xev.sliceAccess(int(n)) 1562 1563 case reflect.Map: 1564 idxev.loadValue(loadFullValue) 1565 if idxev.Unreadable != nil { 1566 return nil, idxev.Unreadable 1567 } 1568 return xev.mapAccess(idxev) 1569 default: 1570 return nil, cantindex 1571 } 1572 } 1573 1574 // Evaluates expressions <subexpr>[<subexpr>:<subexpr>] 1575 // HACK: slicing a map expression with [0:0] will return the whole map 1576 func (scope *EvalScope) evalReslice(node *ast.SliceExpr) (*Variable, error) { 1577 xev, err := scope.evalAST(node.X) 1578 if err != nil { 1579 return nil, err 1580 } 1581 if xev.Unreadable != nil { 1582 return nil, xev.Unreadable 1583 } 1584 1585 var low, high int64 1586 1587 if node.Low != nil { 1588 lowv, err := scope.evalAST(node.Low) 1589 if err != nil { 1590 return nil, err 1591 } 1592 low, err = lowv.asInt() 1593 if err != nil { 1594 return nil, fmt.Errorf("can not convert %q to int: %v", exprToString(node.Low), err) 1595 } 1596 } 1597 1598 if node.High == nil { 1599 high = xev.Len 1600 } else { 1601 highv, err := scope.evalAST(node.High) 1602 if err != nil { 1603 return nil, err 1604 } 1605 high, err = highv.asInt() 1606 if err != nil { 1607 return nil, fmt.Errorf("can not convert %q to int: %v", exprToString(node.High), err) 1608 } 1609 } 1610 1611 switch xev.Kind { 1612 case reflect.Slice, reflect.Array, reflect.String: 1613 if xev.Base == 0 { 1614 return nil, fmt.Errorf("can not slice %q", exprToString(node.X)) 1615 } 1616 return xev.reslice(low, high) 1617 case reflect.Map: 1618 if node.High != nil { 1619 return nil, fmt.Errorf("second slice argument must be empty for maps") 1620 } 1621 xev.mapSkip += int(low) 1622 xev.mapIterator() // reads map length 1623 if int64(xev.mapSkip) >= xev.Len { 1624 return nil, fmt.Errorf("map index out of bounds") 1625 } 1626 return xev, nil 1627 case reflect.Ptr: 1628 if xev.Flags&VariableCPtr != 0 { 1629 return xev.reslice(low, high) 1630 } 1631 fallthrough 1632 default: 1633 return nil, fmt.Errorf("can not slice %q (type %s)", exprToString(node.X), xev.TypeString()) 1634 } 1635 } 1636 1637 // Evaluates a pointer dereference expression: *<subexpr> 1638 func (scope *EvalScope) evalPointerDeref(node *ast.StarExpr) (*Variable, error) { 1639 xev, err := scope.evalAST(node.X) 1640 if err != nil { 1641 return nil, err 1642 } 1643 1644 if xev.Kind != reflect.Ptr { 1645 return nil, fmt.Errorf("expression %q (%s) can not be dereferenced", exprToString(node.X), xev.TypeString()) 1646 } 1647 1648 if xev == nilVariable { 1649 return nil, fmt.Errorf("nil can not be dereferenced") 1650 } 1651 1652 if len(xev.Children) == 1 { 1653 // this branch is here to support pointers constructed with typecasts from ints 1654 xev.Children[0].OnlyAddr = false 1655 return &(xev.Children[0]), nil 1656 } 1657 xev.loadPtr() 1658 if xev.Unreadable != nil { 1659 val, ok := constant.Uint64Val(xev.Value) 1660 if ok && val == 0 { 1661 return nil, fmt.Errorf("couldn't read pointer: %w", xev.Unreadable) 1662 } 1663 } 1664 rv := &xev.Children[0] 1665 if rv.Addr == 0 { 1666 return nil, fmt.Errorf("nil pointer dereference") 1667 } 1668 return rv, nil 1669 } 1670 1671 // Evaluates expressions &<subexpr> 1672 func (scope *EvalScope) evalAddrOf(node *ast.UnaryExpr) (*Variable, error) { 1673 xev, err := scope.evalAST(node.X) 1674 if err != nil { 1675 return nil, err 1676 } 1677 if xev.Addr == 0 || xev.DwarfType == nil { 1678 return nil, fmt.Errorf("can not take address of %q", exprToString(node.X)) 1679 } 1680 1681 return xev.pointerToVariable(), nil 1682 } 1683 1684 func (v *Variable) pointerToVariable() *Variable { 1685 v.OnlyAddr = true 1686 1687 typename := "*" + v.DwarfType.Common().Name 1688 rv := v.newVariable("", 0, &godwarf.PtrType{CommonType: godwarf.CommonType{ByteSize: int64(v.bi.Arch.PtrSize()), Name: typename}, Type: v.DwarfType}, v.mem) 1689 rv.Children = []Variable{*v} 1690 rv.loaded = true 1691 1692 return rv 1693 } 1694 1695 func constantUnaryOp(op token.Token, y constant.Value) (r constant.Value, err error) { 1696 defer func() { 1697 if ierr := recover(); ierr != nil { 1698 err = fmt.Errorf("%v", ierr) 1699 } 1700 }() 1701 r = constant.UnaryOp(op, y, 0) 1702 return 1703 } 1704 1705 func constantBinaryOp(op token.Token, x, y constant.Value) (r constant.Value, err error) { 1706 defer func() { 1707 if ierr := recover(); ierr != nil { 1708 err = fmt.Errorf("%v", ierr) 1709 } 1710 }() 1711 switch op { 1712 case token.SHL, token.SHR: 1713 n, _ := constant.Uint64Val(y) 1714 r = constant.Shift(x, op, uint(n)) 1715 default: 1716 r = constant.BinaryOp(x, op, y) 1717 } 1718 return 1719 } 1720 1721 func constantCompare(op token.Token, x, y constant.Value) (r bool, err error) { 1722 defer func() { 1723 if ierr := recover(); ierr != nil { 1724 err = fmt.Errorf("%v", ierr) 1725 } 1726 }() 1727 r = constant.Compare(x, op, y) 1728 return 1729 } 1730 1731 // Evaluates expressions: -<subexpr> and +<subexpr> 1732 func (scope *EvalScope) evalUnary(node *ast.UnaryExpr) (*Variable, error) { 1733 xv, err := scope.evalAST(node.X) 1734 if err != nil { 1735 return nil, err 1736 } 1737 1738 xv.loadValue(loadSingleValue) 1739 if xv.Unreadable != nil { 1740 return nil, xv.Unreadable 1741 } 1742 if xv.FloatSpecial != 0 { 1743 return nil, errOperationOnSpecialFloat 1744 } 1745 if xv.Value == nil { 1746 return nil, fmt.Errorf("operator %s can not be applied to %q", node.Op.String(), exprToString(node.X)) 1747 } 1748 rc, err := constantUnaryOp(node.Op, xv.Value) 1749 if err != nil { 1750 return nil, err 1751 } 1752 if xv.DwarfType != nil { 1753 r := xv.newVariable("", 0, xv.DwarfType, scope.Mem) 1754 r.Value = rc 1755 return r, nil 1756 } 1757 return newConstant(rc, xv.mem), nil 1758 } 1759 1760 func negotiateType(op token.Token, xv, yv *Variable) (godwarf.Type, error) { 1761 if xv == nilVariable { 1762 return nil, negotiateTypeNil(op, yv) 1763 } 1764 1765 if yv == nilVariable { 1766 return nil, negotiateTypeNil(op, xv) 1767 } 1768 1769 if op == token.SHR || op == token.SHL { 1770 if xv.Value == nil || xv.Value.Kind() != constant.Int { 1771 return nil, fmt.Errorf("shift of type %s", xv.Kind) 1772 } 1773 1774 switch yv.Kind { 1775 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 1776 // ok 1777 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 1778 if constant.Sign(yv.Value) < 0 { 1779 return nil, fmt.Errorf("shift count must not be negative") 1780 } 1781 default: 1782 return nil, fmt.Errorf("shift count type %s, must be unsigned integer", yv.Kind.String()) 1783 } 1784 1785 return xv.DwarfType, nil 1786 } 1787 1788 if xv.DwarfType == nil && yv.DwarfType == nil { 1789 return nil, nil 1790 } 1791 1792 if xv.DwarfType != nil && yv.DwarfType != nil { 1793 if xv.DwarfType.String() != yv.DwarfType.String() { 1794 return nil, fmt.Errorf("mismatched types %q and %q", xv.DwarfType.String(), yv.DwarfType.String()) 1795 } 1796 return xv.DwarfType, nil 1797 } else if xv.DwarfType != nil && yv.DwarfType == nil { 1798 if err := yv.isType(xv.DwarfType, xv.Kind); err != nil { 1799 return nil, err 1800 } 1801 return xv.DwarfType, nil 1802 } else if xv.DwarfType == nil && yv.DwarfType != nil { 1803 if err := xv.isType(yv.DwarfType, yv.Kind); err != nil { 1804 return nil, err 1805 } 1806 return yv.DwarfType, nil 1807 } 1808 1809 panic("unreachable") 1810 } 1811 1812 func negotiateTypeNil(op token.Token, v *Variable) error { 1813 if op != token.EQL && op != token.NEQ { 1814 return fmt.Errorf("operator %s can not be applied to \"nil\"", op.String()) 1815 } 1816 switch v.Kind { 1817 case reflect.Ptr, reflect.UnsafePointer, reflect.Chan, reflect.Map, reflect.Interface, reflect.Slice, reflect.Func: 1818 return nil 1819 default: 1820 return fmt.Errorf("can not compare %s to nil", v.Kind.String()) 1821 } 1822 } 1823 1824 func (scope *EvalScope) evalBinary(node *ast.BinaryExpr) (*Variable, error) { 1825 switch node.Op { 1826 case token.INC, token.DEC, token.ARROW: 1827 return nil, fmt.Errorf("operator %s not supported", node.Op.String()) 1828 } 1829 1830 xv, err := scope.evalAST(node.X) 1831 if err != nil { 1832 return nil, err 1833 } 1834 if xv.Kind != reflect.String { // delay loading strings until we use them 1835 xv.loadValue(loadFullValue) 1836 } 1837 if xv.Unreadable != nil { 1838 return nil, xv.Unreadable 1839 } 1840 1841 // short circuits logical operators 1842 switch node.Op { 1843 case token.LAND: 1844 if !constant.BoolVal(xv.Value) { 1845 return newConstant(xv.Value, xv.mem), nil 1846 } 1847 case token.LOR: 1848 if constant.BoolVal(xv.Value) { 1849 return newConstant(xv.Value, xv.mem), nil 1850 } 1851 } 1852 1853 yv, err := scope.evalAST(node.Y) 1854 if err != nil { 1855 return nil, err 1856 } 1857 if yv.Kind != reflect.String { // delay loading strings until we use them 1858 yv.loadValue(loadFullValue) 1859 } 1860 if yv.Unreadable != nil { 1861 return nil, yv.Unreadable 1862 } 1863 1864 if xv.FloatSpecial != 0 || yv.FloatSpecial != 0 { 1865 return nil, errOperationOnSpecialFloat 1866 } 1867 1868 typ, err := negotiateType(node.Op, xv, yv) 1869 if err != nil { 1870 return nil, err 1871 } 1872 1873 op := node.Op 1874 if typ != nil && (op == token.QUO) { 1875 _, isint := typ.(*godwarf.IntType) 1876 _, isuint := typ.(*godwarf.UintType) 1877 if isint || isuint { 1878 // forces integer division if the result type is integer 1879 op = token.QUO_ASSIGN 1880 } 1881 } 1882 1883 switch op { 1884 case token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ: 1885 v, err := compareOp(op, xv, yv) 1886 if err != nil { 1887 return nil, err 1888 } 1889 return newConstant(constant.MakeBool(v), xv.mem), nil 1890 1891 default: 1892 if xv.Kind == reflect.String { 1893 xv.loadValue(loadFullValueLongerStrings) 1894 } 1895 if yv.Kind == reflect.String { 1896 yv.loadValue(loadFullValueLongerStrings) 1897 } 1898 if xv.Value == nil { 1899 return nil, fmt.Errorf("operator %s can not be applied to %q", node.Op.String(), exprToString(node.X)) 1900 } 1901 1902 if yv.Value == nil { 1903 return nil, fmt.Errorf("operator %s can not be applied to %q", node.Op.String(), exprToString(node.Y)) 1904 } 1905 1906 rc, err := constantBinaryOp(op, xv.Value, yv.Value) 1907 if err != nil { 1908 return nil, err 1909 } 1910 1911 if typ == nil { 1912 return newConstant(rc, xv.mem), nil 1913 } 1914 1915 r := xv.newVariable("", 0, typ, scope.Mem) 1916 r.Value = rc 1917 switch r.Kind { 1918 case reflect.String: 1919 r.Len = xv.Len + yv.Len 1920 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 1921 n, _ := constant.Int64Val(r.Value) 1922 r.Value = constant.MakeInt64(int64(convertInt(uint64(n), true, typ.Size()))) 1923 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 1924 n, _ := constant.Uint64Val(r.Value) 1925 r.Value = constant.MakeUint64(convertInt(n, false, typ.Size())) 1926 } 1927 return r, nil 1928 } 1929 } 1930 1931 // Compares xv to yv using operator op 1932 // Both xv and yv must be loaded and have a compatible type (as determined by negotiateType) 1933 func compareOp(op token.Token, xv *Variable, yv *Variable) (bool, error) { 1934 switch xv.Kind { 1935 case reflect.Bool: 1936 fallthrough 1937 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 1938 fallthrough 1939 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 1940 fallthrough 1941 case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: 1942 return constantCompare(op, xv.Value, yv.Value) 1943 case reflect.String: 1944 if xv.Len != yv.Len { 1945 switch op { 1946 case token.EQL: 1947 return false, nil 1948 case token.NEQ: 1949 return true, nil 1950 } 1951 } 1952 if xv.Kind == reflect.String { 1953 xv.loadValue(loadFullValueLongerStrings) 1954 } 1955 if yv.Kind == reflect.String { 1956 yv.loadValue(loadFullValueLongerStrings) 1957 } 1958 if int64(len(constant.StringVal(xv.Value))) != xv.Len || int64(len(constant.StringVal(yv.Value))) != yv.Len { 1959 return false, fmt.Errorf("string too long for comparison") 1960 } 1961 return constantCompare(op, xv.Value, yv.Value) 1962 } 1963 1964 if op != token.EQL && op != token.NEQ { 1965 return false, fmt.Errorf("operator %s not defined on %s", op.String(), xv.Kind.String()) 1966 } 1967 1968 var eql bool 1969 var err error 1970 1971 if xv == nilVariable { 1972 switch op { 1973 case token.EQL: 1974 return yv.isNil(), nil 1975 case token.NEQ: 1976 return !yv.isNil(), nil 1977 } 1978 } 1979 1980 if yv == nilVariable { 1981 switch op { 1982 case token.EQL: 1983 return xv.isNil(), nil 1984 case token.NEQ: 1985 return !xv.isNil(), nil 1986 } 1987 } 1988 1989 switch xv.Kind { 1990 case reflect.Ptr: 1991 eql = xv.Children[0].Addr == yv.Children[0].Addr 1992 case reflect.Array: 1993 if int64(len(xv.Children)) != xv.Len || int64(len(yv.Children)) != yv.Len { 1994 return false, fmt.Errorf("array too long for comparison") 1995 } 1996 eql, err = equalChildren(xv, yv, true) 1997 case reflect.Struct: 1998 if len(xv.Children) != len(yv.Children) { 1999 return false, nil 2000 } 2001 if int64(len(xv.Children)) != xv.Len || int64(len(yv.Children)) != yv.Len { 2002 return false, fmt.Errorf("structure too deep for comparison") 2003 } 2004 eql, err = equalChildren(xv, yv, false) 2005 case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: 2006 return false, fmt.Errorf("can not compare %s variables", xv.Kind.String()) 2007 case reflect.Interface: 2008 if xv.Children[0].RealType.String() != yv.Children[0].RealType.String() { 2009 eql = false 2010 } else { 2011 eql, err = compareOp(token.EQL, &xv.Children[0], &yv.Children[0]) 2012 } 2013 default: 2014 return false, fmt.Errorf("unimplemented comparison of %s variables", xv.Kind.String()) 2015 } 2016 2017 if op == token.NEQ { 2018 return !eql, err 2019 } 2020 return eql, err 2021 } 2022 2023 func (v *Variable) isNil() bool { 2024 switch v.Kind { 2025 case reflect.Ptr: 2026 return v.Children[0].Addr == 0 2027 case reflect.Interface: 2028 return v.Children[0].Addr == 0 && v.Children[0].Kind == reflect.Invalid 2029 case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: 2030 return v.Base == 0 2031 } 2032 return false 2033 } 2034 2035 func equalChildren(xv, yv *Variable, shortcircuit bool) (bool, error) { 2036 r := true 2037 for i := range xv.Children { 2038 eql, err := compareOp(token.EQL, &xv.Children[i], &yv.Children[i]) 2039 if err != nil { 2040 return false, err 2041 } 2042 r = r && eql 2043 if !r && shortcircuit { 2044 return false, nil 2045 } 2046 } 2047 return r, nil 2048 } 2049 2050 func (v *Variable) asInt() (int64, error) { 2051 if v.DwarfType == nil { 2052 if v.Value.Kind() != constant.Int { 2053 return 0, fmt.Errorf("can not convert constant %s to int", v.Value) 2054 } 2055 } else { 2056 v.loadValue(loadSingleValue) 2057 if v.Unreadable != nil { 2058 return 0, v.Unreadable 2059 } 2060 if _, ok := v.DwarfType.(*godwarf.IntType); !ok { 2061 return 0, fmt.Errorf("can not convert value of type %s to int", v.DwarfType.String()) 2062 } 2063 } 2064 n, _ := constant.Int64Val(v.Value) 2065 return n, nil 2066 } 2067 2068 func (v *Variable) asUint() (uint64, error) { 2069 if v.DwarfType == nil { 2070 if v.Value.Kind() != constant.Int { 2071 return 0, fmt.Errorf("can not convert constant %s to uint", v.Value) 2072 } 2073 } else { 2074 v.loadValue(loadSingleValue) 2075 if v.Unreadable != nil { 2076 return 0, v.Unreadable 2077 } 2078 if _, ok := v.DwarfType.(*godwarf.UintType); !ok { 2079 return 0, fmt.Errorf("can not convert value of type %s to uint", v.DwarfType.String()) 2080 } 2081 } 2082 n, _ := constant.Uint64Val(v.Value) 2083 return n, nil 2084 } 2085 2086 type typeConvErr struct { 2087 srcType, dstType godwarf.Type 2088 } 2089 2090 func (err *typeConvErr) Error() string { 2091 return fmt.Sprintf("can not convert value of type %s to %s", err.srcType.String(), err.dstType.String()) 2092 } 2093 2094 func (v *Variable) isType(typ godwarf.Type, kind reflect.Kind) error { 2095 if v.DwarfType != nil { 2096 if typ == nil || !sameType(typ, v.RealType) { 2097 return &typeConvErr{v.DwarfType, typ} 2098 } 2099 return nil 2100 } 2101 2102 if typ == nil { 2103 return nil 2104 } 2105 2106 if v == nilVariable { 2107 switch kind { 2108 case reflect.Slice, reflect.Map, reflect.Func, reflect.Ptr, reflect.Chan, reflect.Interface: 2109 return nil 2110 default: 2111 return fmt.Errorf("mismatched types nil and %s", typ.String()) 2112 } 2113 } 2114 2115 converr := fmt.Errorf("can not convert %s constant to %s", v.Value, typ.String()) 2116 2117 if v.Value == nil { 2118 return converr 2119 } 2120 2121 switch typ.(type) { 2122 case *godwarf.IntType: 2123 if v.Value.Kind() != constant.Int { 2124 return converr 2125 } 2126 case *godwarf.UintType: 2127 if v.Value.Kind() != constant.Int { 2128 return converr 2129 } 2130 case *godwarf.FloatType: 2131 if (v.Value.Kind() != constant.Int) && (v.Value.Kind() != constant.Float) { 2132 return converr 2133 } 2134 case *godwarf.BoolType: 2135 if v.Value.Kind() != constant.Bool { 2136 return converr 2137 } 2138 case *godwarf.StringType: 2139 if v.Value.Kind() != constant.String { 2140 return converr 2141 } 2142 case *godwarf.ComplexType: 2143 if v.Value.Kind() != constant.Complex && v.Value.Kind() != constant.Float && v.Value.Kind() != constant.Int { 2144 return converr 2145 } 2146 default: 2147 return converr 2148 } 2149 2150 return nil 2151 } 2152 2153 func sameType(t1, t2 godwarf.Type) bool { 2154 // Because of a bug in the go linker a type that refers to another type 2155 // (for example a pointer type) will usually use the typedef but rarely use 2156 // the non-typedef entry directly. 2157 // For types that we read directly from go this is fine because it's 2158 // consistent, however we also synthesize some types ourselves 2159 // (specifically pointers and slices) and we always use a reference through 2160 // a typedef. 2161 t1 = resolveTypedef(t1) 2162 t2 = resolveTypedef(t2) 2163 2164 if tt1, isptr1 := t1.(*godwarf.PtrType); isptr1 { 2165 tt2, isptr2 := t2.(*godwarf.PtrType) 2166 if !isptr2 { 2167 return false 2168 } 2169 return sameType(tt1.Type, tt2.Type) 2170 } 2171 if tt1, isslice1 := t1.(*godwarf.SliceType); isslice1 { 2172 tt2, isslice2 := t2.(*godwarf.SliceType) 2173 if !isslice2 { 2174 return false 2175 } 2176 return sameType(tt1.ElemType, tt2.ElemType) 2177 } 2178 return t1.String() == t2.String() 2179 } 2180 2181 func (v *Variable) sliceAccess(idx int) (*Variable, error) { 2182 wrong := false 2183 if v.Flags&VariableCPtr == 0 { 2184 wrong = idx < 0 || int64(idx) >= v.Len 2185 } else { 2186 wrong = idx < 0 2187 } 2188 if wrong { 2189 return nil, fmt.Errorf("index out of bounds") 2190 } 2191 if v.loaded { 2192 if v.Kind == reflect.String { 2193 s := constant.StringVal(v.Value) 2194 if idx >= len(s) { 2195 return nil, fmt.Errorf("index out of bounds") 2196 } 2197 r := v.newVariable("", v.Base+uint64(int64(idx)*v.stride), v.fieldType, v.mem) 2198 r.loaded = true 2199 r.Value = constant.MakeInt64(int64(s[idx])) 2200 return r, nil 2201 } else { 2202 if idx >= len(v.Children) { 2203 return nil, fmt.Errorf("index out of bounds") 2204 } 2205 return &v.Children[idx], nil 2206 } 2207 } 2208 mem := v.mem 2209 if v.Kind != reflect.Array { 2210 mem = DereferenceMemory(mem) 2211 } 2212 return v.newVariable("", v.Base+uint64(int64(idx)*v.stride), v.fieldType, mem), nil 2213 } 2214 2215 func (v *Variable) mapAccess(idx *Variable) (*Variable, error) { 2216 it := v.mapIterator() 2217 if it == nil { 2218 return nil, fmt.Errorf("can not access unreadable map: %v", v.Unreadable) 2219 } 2220 2221 lcfg := loadFullValue 2222 if idx.Kind == reflect.String && int64(len(constant.StringVal(idx.Value))) == idx.Len && idx.Len > int64(lcfg.MaxStringLen) { 2223 // If the index is a string load as much of the keys to at least match the length of the index. 2224 //TODO(aarzilli): when struct literals are implemented this needs to be 2225 //done recursively for literal struct fields. 2226 lcfg.MaxStringLen = int(idx.Len) 2227 } 2228 2229 first := true 2230 for it.next() { 2231 key := it.key() 2232 key.loadValue(lcfg) 2233 if key.Unreadable != nil { 2234 return nil, fmt.Errorf("can not access unreadable map: %v", key.Unreadable) 2235 } 2236 if first { 2237 first = false 2238 if err := idx.isType(key.RealType, key.Kind); err != nil { 2239 return nil, err 2240 } 2241 } 2242 eql, err := compareOp(token.EQL, key, idx) 2243 if err != nil { 2244 return nil, err 2245 } 2246 if eql { 2247 return it.value(), nil 2248 } 2249 } 2250 if v.Unreadable != nil { 2251 return nil, v.Unreadable 2252 } 2253 // go would return zero for the map value type here, we do not have the ability to create zeroes 2254 return nil, fmt.Errorf("key not found") 2255 } 2256 2257 // LoadResliced returns a new array, slice or map that starts at index start and contains 2258 // up to cfg.MaxArrayValues children. 2259 func (v *Variable) LoadResliced(start int, cfg LoadConfig) (newV *Variable, err error) { 2260 switch v.Kind { 2261 case reflect.Array, reflect.Slice: 2262 low, high := int64(start), int64(start+cfg.MaxArrayValues) 2263 if high > v.Len { 2264 high = v.Len 2265 } 2266 newV, err = v.reslice(low, high) 2267 if err != nil { 2268 return nil, err 2269 } 2270 case reflect.Map: 2271 newV = v.clone() 2272 newV.Children = nil 2273 newV.loaded = false 2274 newV.mapSkip = start 2275 default: 2276 return nil, fmt.Errorf("variable to reslice is not an array, slice, or map") 2277 } 2278 newV.loadValue(cfg) 2279 return newV, nil 2280 } 2281 2282 func (v *Variable) reslice(low int64, high int64) (*Variable, error) { 2283 wrong := false 2284 cptrNeedsFakeSlice := false 2285 if v.Flags&VariableCPtr == 0 { 2286 wrong = low < 0 || low > v.Len || high < 0 || high > v.Len 2287 } else { 2288 wrong = low < 0 || high < 0 2289 if high == 0 { 2290 high = low 2291 } 2292 cptrNeedsFakeSlice = v.Kind != reflect.String 2293 } 2294 if wrong { 2295 return nil, fmt.Errorf("index out of bounds") 2296 } 2297 2298 base := v.Base + uint64(int64(low)*v.stride) 2299 len := high - low 2300 2301 if high-low < 0 { 2302 return nil, fmt.Errorf("index out of bounds") 2303 } 2304 2305 typ := v.DwarfType 2306 if _, isarr := v.DwarfType.(*godwarf.ArrayType); isarr || cptrNeedsFakeSlice { 2307 typ = fakeSliceType(v.fieldType) 2308 } 2309 2310 mem := v.mem 2311 if v.Kind != reflect.Array { 2312 mem = DereferenceMemory(mem) 2313 } 2314 2315 r := v.newVariable("", 0, typ, mem) 2316 r.Cap = len 2317 r.Len = len 2318 r.Base = base 2319 r.stride = v.stride 2320 r.fieldType = v.fieldType 2321 r.Flags = v.Flags 2322 r.reg = v.reg 2323 2324 return r, nil 2325 } 2326 2327 // findMethod finds method mname in the type of variable v 2328 func (v *Variable) findMethod(mname string) (*Variable, error) { 2329 if _, isiface := v.RealType.(*godwarf.InterfaceType); isiface { 2330 v.loadInterface(0, false, loadFullValue) 2331 if v.Unreadable != nil { 2332 return nil, v.Unreadable 2333 } 2334 return v.Children[0].findMethod(mname) 2335 } 2336 2337 queue := []*Variable{v} 2338 seen := map[string]struct{}{} 2339 2340 for len(queue) > 0 { 2341 v := queue[0] 2342 queue = append(queue[:0], queue[1:]...) 2343 if _, isseen := seen[v.RealType.String()]; isseen { 2344 continue 2345 } 2346 seen[v.RealType.String()] = struct{}{} 2347 2348 typ := v.DwarfType 2349 ptyp, isptr := typ.(*godwarf.PtrType) 2350 if isptr { 2351 typ = ptyp.Type 2352 } 2353 2354 typePath := typ.Common().Name 2355 dot := strings.LastIndex(typePath, ".") 2356 if dot < 0 { 2357 // probably just a C type 2358 continue 2359 } 2360 2361 pkg := typePath[:dot] 2362 receiver := typePath[dot+1:] 2363 2364 //TODO(aarzilli): support generic functions? 2365 2366 if fns := v.bi.LookupFunc()[fmt.Sprintf("%s.%s.%s", pkg, receiver, mname)]; len(fns) == 1 { 2367 r, err := functionToVariable(fns[0], v.bi, v.mem) 2368 if err != nil { 2369 return nil, err 2370 } 2371 if isptr { 2372 r.Children = append(r.Children, *(v.maybeDereference())) 2373 } else { 2374 r.Children = append(r.Children, *v) 2375 } 2376 return r, nil 2377 } 2378 2379 if fns := v.bi.LookupFunc()[fmt.Sprintf("%s.(*%s).%s", pkg, receiver, mname)]; len(fns) == 1 { 2380 r, err := functionToVariable(fns[0], v.bi, v.mem) 2381 if err != nil { 2382 return nil, err 2383 } 2384 if isptr { 2385 r.Children = append(r.Children, *v) 2386 } else { 2387 r.Children = append(r.Children, *(v.pointerToVariable())) 2388 } 2389 return r, nil 2390 } 2391 2392 // queue embedded fields for search 2393 structVar := v.maybeDereference() 2394 structVar.Name = v.Name 2395 if structVar.Unreadable != nil { 2396 return structVar, nil 2397 } 2398 switch t := structVar.RealType.(type) { 2399 case *godwarf.StructType: 2400 for _, field := range t.Field { 2401 if field.Embedded { 2402 embeddedVar, err := structVar.toField(field) 2403 if err != nil { 2404 return nil, err 2405 } 2406 queue = append(queue, embeddedVar) 2407 } 2408 } 2409 } 2410 } 2411 2412 return nil, nil 2413 } 2414 2415 func functionToVariable(fn *Function, bi *BinaryInfo, mem MemoryReadWriter) (*Variable, error) { 2416 typ, err := fn.fakeType(bi, true) 2417 if err != nil { 2418 return nil, err 2419 } 2420 v := newVariable(fn.Name, 0, typ, bi, mem) 2421 v.Value = constant.MakeString(fn.Name) 2422 v.loaded = true 2423 v.Base = fn.Entry 2424 return v, nil 2425 } 2426 2427 func fakeBasicType(name string, bitSize int) godwarf.Type { 2428 byteSize := bitSize / 8 2429 szr := popcnt(uint64(byteSize^(byteSize-1))) - 1 // position of rightmost 1 bit, minus 1 2430 2431 basic := func(kind reflect.Kind) godwarf.BasicType { 2432 return godwarf.BasicType{ 2433 CommonType: godwarf.CommonType{ 2434 ByteSize: int64(byteSize), 2435 Name: fmt.Sprintf("%s%d", name, bitSize), 2436 ReflectKind: kind, 2437 }, 2438 BitSize: int64(bitSize), 2439 BitOffset: 0, 2440 } 2441 } 2442 2443 switch name { 2444 case "int": 2445 return &godwarf.IntType{BasicType: basic(reflect.Int8 + reflect.Kind(szr))} 2446 case "uint": 2447 return &godwarf.UintType{BasicType: basic(reflect.Uint8 + reflect.Kind(szr))} 2448 case "float": 2449 return &godwarf.FloatType{BasicType: basic(reflect.Float32 + reflect.Kind(szr-2))} 2450 case "complex": 2451 return &godwarf.ComplexType{BasicType: basic(reflect.Complex64 + reflect.Kind(szr-3))} 2452 default: 2453 panic("unsupported") 2454 } 2455 } 2456 2457 func fakeSliceType(fieldType godwarf.Type) godwarf.Type { 2458 return &godwarf.SliceType{ 2459 StructType: godwarf.StructType{ 2460 CommonType: godwarf.CommonType{ 2461 ByteSize: 24, 2462 Name: "", 2463 }, 2464 StructName: fmt.Sprintf("[]%s", fieldType.Common().Name), 2465 Kind: "struct", 2466 Field: nil, 2467 }, 2468 ElemType: fieldType, 2469 } 2470 } 2471 2472 func fakeArrayType(n uint64, fieldType godwarf.Type) godwarf.Type { 2473 stride := alignAddr(fieldType.Common().ByteSize, fieldType.Align()) 2474 return &godwarf.ArrayType{ 2475 CommonType: godwarf.CommonType{ 2476 ReflectKind: reflect.Array, 2477 ByteSize: int64(n) * stride, 2478 Name: fmt.Sprintf("[%d]%s", n, fieldType.String())}, 2479 Type: fieldType, 2480 StrideBitSize: stride * 8, 2481 Count: int64(n)} 2482 } 2483 2484 var errMethodEvalUnsupported = errors.New("evaluating methods not supported on this version of Go") 2485 2486 func (fn *Function) fakeType(bi *BinaryInfo, removeReceiver bool) (*godwarf.FuncType, error) { 2487 if producer := bi.Producer(); producer == "" || !goversion.ProducerAfterOrEqual(producer, 1, 10) { 2488 // versions of Go prior to 1.10 do not distinguish between parameters and 2489 // return values, therefore we can't use a subprogram DIE to derive a 2490 // function type. 2491 return nil, errMethodEvalUnsupported 2492 } 2493 _, formalArgs, err := funcCallArgs(fn, bi, true) 2494 if err != nil { 2495 return nil, err 2496 } 2497 2498 // Only try and remove the receiver if it is actually being passed in as a formal argument. 2499 // In the case of: 2500 // 2501 // func (_ X) Method() { ... } 2502 // 2503 // that would not be true, the receiver is not used and thus 2504 // not being passed in as a formal argument. 2505 // 2506 // TODO(derekparker) This, I think, creates a new bug where 2507 // if the receiver is not passed in as a formal argument but 2508 // there are other arguments, such as: 2509 // 2510 // func (_ X) Method(i int) { ... } 2511 // 2512 // The first argument 'i int' will be removed. We must actually detect 2513 // here if the receiver is being used. While this is a bug, it's not a 2514 // functional bug, it only affects the string representation of the fake 2515 // function type we create. It's not really easy to tell here if we use 2516 // the receiver or not. Perhaps we should not perform this manipulation at all? 2517 if removeReceiver && len(formalArgs) > 0 { 2518 formalArgs = formalArgs[1:] 2519 } 2520 2521 args := make([]string, 0, len(formalArgs)) 2522 rets := make([]string, 0, len(formalArgs)) 2523 2524 for _, formalArg := range formalArgs { 2525 var s string 2526 if strings.HasPrefix(formalArg.name, "~") { 2527 s = formalArg.typ.String() 2528 } else { 2529 s = fmt.Sprintf("%s %s", formalArg.name, formalArg.typ.String()) 2530 } 2531 if formalArg.isret { 2532 rets = append(rets, s) 2533 } else { 2534 args = append(args, s) 2535 } 2536 } 2537 2538 argstr := strings.Join(args, ", ") 2539 var retstr string 2540 switch len(rets) { 2541 case 0: 2542 retstr = "" 2543 case 1: 2544 retstr = " " + rets[0] 2545 default: 2546 retstr = " (" + strings.Join(rets, ", ") + ")" 2547 } 2548 return &godwarf.FuncType{ 2549 CommonType: godwarf.CommonType{ 2550 Name: "func(" + argstr + ")" + retstr, 2551 ReflectKind: reflect.Func, 2552 }, 2553 //TODO(aarzilli): at the moment we aren't using the ParamType and 2554 // ReturnType fields of FuncType anywhere (when this is returned to the 2555 // client it's first converted to a string and the function calling code 2556 // reads the subroutine entry because it needs to know the stack offsets). 2557 // If we start using them they should be filled here. 2558 }, nil 2559 } 2560 2561 func validRegisterName(s string) string { 2562 for len(s) > 0 && s[0] == '_' { 2563 s = s[1:] 2564 } 2565 for i := range s { 2566 if (s[i] < '0' || s[i] > '9') && (s[i] < 'A' || s[i] > 'Z') { 2567 return "" 2568 } 2569 } 2570 return s 2571 }