github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/go/ssa/interp/interp.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package ssa/interp defines an interpreter for the SSA 6 // representation of Go programs. 7 // 8 // This interpreter is provided as an adjunct for testing the SSA 9 // construction algorithm. Its purpose is to provide a minimal 10 // metacircular implementation of the dynamic semantics of each SSA 11 // instruction. It is not, and will never be, a production-quality Go 12 // interpreter. 13 // 14 // The following is a partial list of Go features that are currently 15 // unsupported or incomplete in the interpreter. 16 // 17 // * Unsafe operations, including all uses of unsafe.Pointer, are 18 // impossible to support given the "boxed" value representation we 19 // have chosen. 20 // 21 // * The reflect package is only partially implemented. 22 // 23 // * The "testing" package is no longer supported because it 24 // depends on low-level details that change too often. 25 // 26 // * "sync/atomic" operations are not atomic due to the "boxed" value 27 // representation: it is not possible to read, modify and write an 28 // interface value atomically. As a consequence, Mutexes are currently 29 // broken. 30 // 31 // * recover is only partially implemented. Also, the interpreter 32 // makes no attempt to distinguish target panics from interpreter 33 // crashes. 34 // 35 // * the sizes of the int, uint and uintptr types in the target 36 // program are assumed to be the same as those of the interpreter 37 // itself. 38 // 39 // * all values occupy space, even those of types defined by the spec 40 // to have zero size, e.g. struct{}. This can cause asymptotic 41 // performance degradation. 42 // 43 // * os.Exit is implemented using panic, causing deferred functions to 44 // run. 45 package interp // import "github.com/powerman/golang-tools/go/ssa/interp" 46 47 import ( 48 "fmt" 49 "go/token" 50 "go/types" 51 "os" 52 "reflect" 53 "runtime" 54 "sync/atomic" 55 56 "github.com/powerman/golang-tools/go/ssa" 57 ) 58 59 type continuation int 60 61 const ( 62 kNext continuation = iota 63 kReturn 64 kJump 65 ) 66 67 // Mode is a bitmask of options affecting the interpreter. 68 type Mode uint 69 70 const ( 71 DisableRecover Mode = 1 << iota // Disable recover() in target programs; show interpreter crash instead. 72 EnableTracing // Print a trace of all instructions as they are interpreted. 73 ) 74 75 type methodSet map[string]*ssa.Function 76 77 // State shared between all interpreted goroutines. 78 type interpreter struct { 79 osArgs []value // the value of os.Args 80 prog *ssa.Program // the SSA program 81 globals map[ssa.Value]*value // addresses of global variables (immutable) 82 mode Mode // interpreter options 83 reflectPackage *ssa.Package // the fake reflect package 84 errorMethods methodSet // the method set of reflect.error, which implements the error interface. 85 rtypeMethods methodSet // the method set of rtype, which implements the reflect.Type interface. 86 runtimeErrorString types.Type // the runtime.errorString type 87 sizes types.Sizes // the effective type-sizing function 88 goroutines int32 // atomically updated 89 } 90 91 type deferred struct { 92 fn value 93 args []value 94 instr *ssa.Defer 95 tail *deferred 96 } 97 98 type frame struct { 99 i *interpreter 100 caller *frame 101 fn *ssa.Function 102 block, prevBlock *ssa.BasicBlock 103 env map[ssa.Value]value // dynamic values of SSA variables 104 locals []value 105 defers *deferred 106 result value 107 panicking bool 108 panic interface{} 109 } 110 111 func (fr *frame) get(key ssa.Value) value { 112 switch key := key.(type) { 113 case nil: 114 // Hack; simplifies handling of optional attributes 115 // such as ssa.Slice.{Low,High}. 116 return nil 117 case *ssa.Function, *ssa.Builtin: 118 return key 119 case *ssa.Const: 120 return constValue(key) 121 case *ssa.Global: 122 if r, ok := fr.i.globals[key]; ok { 123 return r 124 } 125 } 126 if r, ok := fr.env[key]; ok { 127 return r 128 } 129 panic(fmt.Sprintf("get: no value for %T: %v", key, key.Name())) 130 } 131 132 // runDefer runs a deferred call d. 133 // It always returns normally, but may set or clear fr.panic. 134 // 135 func (fr *frame) runDefer(d *deferred) { 136 if fr.i.mode&EnableTracing != 0 { 137 fmt.Fprintf(os.Stderr, "%s: invoking deferred function call\n", 138 fr.i.prog.Fset.Position(d.instr.Pos())) 139 } 140 var ok bool 141 defer func() { 142 if !ok { 143 // Deferred call created a new state of panic. 144 fr.panicking = true 145 fr.panic = recover() 146 } 147 }() 148 call(fr.i, fr, d.instr.Pos(), d.fn, d.args) 149 ok = true 150 } 151 152 // runDefers executes fr's deferred function calls in LIFO order. 153 // 154 // On entry, fr.panicking indicates a state of panic; if 155 // true, fr.panic contains the panic value. 156 // 157 // On completion, if a deferred call started a panic, or if no 158 // deferred call recovered from a previous state of panic, then 159 // runDefers itself panics after the last deferred call has run. 160 // 161 // If there was no initial state of panic, or it was recovered from, 162 // runDefers returns normally. 163 // 164 func (fr *frame) runDefers() { 165 for d := fr.defers; d != nil; d = d.tail { 166 fr.runDefer(d) 167 } 168 fr.defers = nil 169 if fr.panicking { 170 panic(fr.panic) // new panic, or still panicking 171 } 172 } 173 174 // lookupMethod returns the method set for type typ, which may be one 175 // of the interpreter's fake types. 176 func lookupMethod(i *interpreter, typ types.Type, meth *types.Func) *ssa.Function { 177 switch typ { 178 case rtypeType: 179 return i.rtypeMethods[meth.Id()] 180 case errorType: 181 return i.errorMethods[meth.Id()] 182 } 183 return i.prog.LookupMethod(typ, meth.Pkg(), meth.Name()) 184 } 185 186 // visitInstr interprets a single ssa.Instruction within the activation 187 // record frame. It returns a continuation value indicating where to 188 // read the next instruction from. 189 func visitInstr(fr *frame, instr ssa.Instruction) continuation { 190 switch instr := instr.(type) { 191 case *ssa.DebugRef: 192 // no-op 193 194 case *ssa.UnOp: 195 fr.env[instr] = unop(instr, fr.get(instr.X)) 196 197 case *ssa.BinOp: 198 fr.env[instr] = binop(instr.Op, instr.X.Type(), fr.get(instr.X), fr.get(instr.Y)) 199 200 case *ssa.Call: 201 fn, args := prepareCall(fr, &instr.Call) 202 fr.env[instr] = call(fr.i, fr, instr.Pos(), fn, args) 203 204 case *ssa.ChangeInterface: 205 fr.env[instr] = fr.get(instr.X) 206 207 case *ssa.ChangeType: 208 fr.env[instr] = fr.get(instr.X) // (can't fail) 209 210 case *ssa.Convert: 211 fr.env[instr] = conv(instr.Type(), instr.X.Type(), fr.get(instr.X)) 212 213 case *ssa.SliceToArrayPointer: 214 fr.env[instr] = sliceToArrayPointer(instr.Type(), instr.X.Type(), fr.get(instr.X)) 215 216 case *ssa.MakeInterface: 217 fr.env[instr] = iface{t: instr.X.Type(), v: fr.get(instr.X)} 218 219 case *ssa.Extract: 220 fr.env[instr] = fr.get(instr.Tuple).(tuple)[instr.Index] 221 222 case *ssa.Slice: 223 fr.env[instr] = slice(fr.get(instr.X), fr.get(instr.Low), fr.get(instr.High), fr.get(instr.Max)) 224 225 case *ssa.Return: 226 switch len(instr.Results) { 227 case 0: 228 case 1: 229 fr.result = fr.get(instr.Results[0]) 230 default: 231 var res []value 232 for _, r := range instr.Results { 233 res = append(res, fr.get(r)) 234 } 235 fr.result = tuple(res) 236 } 237 fr.block = nil 238 return kReturn 239 240 case *ssa.RunDefers: 241 fr.runDefers() 242 243 case *ssa.Panic: 244 panic(targetPanic{fr.get(instr.X)}) 245 246 case *ssa.Send: 247 fr.get(instr.Chan).(chan value) <- fr.get(instr.X) 248 249 case *ssa.Store: 250 store(deref(instr.Addr.Type()), fr.get(instr.Addr).(*value), fr.get(instr.Val)) 251 252 case *ssa.If: 253 succ := 1 254 if fr.get(instr.Cond).(bool) { 255 succ = 0 256 } 257 fr.prevBlock, fr.block = fr.block, fr.block.Succs[succ] 258 return kJump 259 260 case *ssa.Jump: 261 fr.prevBlock, fr.block = fr.block, fr.block.Succs[0] 262 return kJump 263 264 case *ssa.Defer: 265 fn, args := prepareCall(fr, &instr.Call) 266 fr.defers = &deferred{ 267 fn: fn, 268 args: args, 269 instr: instr, 270 tail: fr.defers, 271 } 272 273 case *ssa.Go: 274 fn, args := prepareCall(fr, &instr.Call) 275 atomic.AddInt32(&fr.i.goroutines, 1) 276 go func() { 277 call(fr.i, nil, instr.Pos(), fn, args) 278 atomic.AddInt32(&fr.i.goroutines, -1) 279 }() 280 281 case *ssa.MakeChan: 282 fr.env[instr] = make(chan value, asInt64(fr.get(instr.Size))) 283 284 case *ssa.Alloc: 285 var addr *value 286 if instr.Heap { 287 // new 288 addr = new(value) 289 fr.env[instr] = addr 290 } else { 291 // local 292 addr = fr.env[instr].(*value) 293 } 294 *addr = zero(deref(instr.Type())) 295 296 case *ssa.MakeSlice: 297 slice := make([]value, asInt64(fr.get(instr.Cap))) 298 tElt := instr.Type().Underlying().(*types.Slice).Elem() 299 for i := range slice { 300 slice[i] = zero(tElt) 301 } 302 fr.env[instr] = slice[:asInt64(fr.get(instr.Len))] 303 304 case *ssa.MakeMap: 305 var reserve int64 306 if instr.Reserve != nil { 307 reserve = asInt64(fr.get(instr.Reserve)) 308 } 309 if !fitsInt(reserve, fr.i.sizes) { 310 panic(fmt.Sprintf("ssa.MakeMap.Reserve value %d does not fit in int", reserve)) 311 } 312 fr.env[instr] = makeMap(instr.Type().Underlying().(*types.Map).Key(), reserve) 313 314 case *ssa.Range: 315 fr.env[instr] = rangeIter(fr.get(instr.X), instr.X.Type()) 316 317 case *ssa.Next: 318 fr.env[instr] = fr.get(instr.Iter).(iter).next() 319 320 case *ssa.FieldAddr: 321 fr.env[instr] = &(*fr.get(instr.X).(*value)).(structure)[instr.Field] 322 323 case *ssa.Field: 324 fr.env[instr] = fr.get(instr.X).(structure)[instr.Field] 325 326 case *ssa.IndexAddr: 327 x := fr.get(instr.X) 328 idx := fr.get(instr.Index) 329 switch x := x.(type) { 330 case []value: 331 fr.env[instr] = &x[asInt64(idx)] 332 case *value: // *array 333 fr.env[instr] = &(*x).(array)[asInt64(idx)] 334 default: 335 panic(fmt.Sprintf("unexpected x type in IndexAddr: %T", x)) 336 } 337 338 case *ssa.Index: 339 fr.env[instr] = fr.get(instr.X).(array)[asInt64(fr.get(instr.Index))] 340 341 case *ssa.Lookup: 342 fr.env[instr] = lookup(instr, fr.get(instr.X), fr.get(instr.Index)) 343 344 case *ssa.MapUpdate: 345 m := fr.get(instr.Map) 346 key := fr.get(instr.Key) 347 v := fr.get(instr.Value) 348 switch m := m.(type) { 349 case map[value]value: 350 m[key] = v 351 case *hashmap: 352 m.insert(key.(hashable), v) 353 default: 354 panic(fmt.Sprintf("illegal map type: %T", m)) 355 } 356 357 case *ssa.TypeAssert: 358 fr.env[instr] = typeAssert(fr.i, instr, fr.get(instr.X).(iface)) 359 360 case *ssa.MakeClosure: 361 var bindings []value 362 for _, binding := range instr.Bindings { 363 bindings = append(bindings, fr.get(binding)) 364 } 365 fr.env[instr] = &closure{instr.Fn.(*ssa.Function), bindings} 366 367 case *ssa.Phi: 368 for i, pred := range instr.Block().Preds { 369 if fr.prevBlock == pred { 370 fr.env[instr] = fr.get(instr.Edges[i]) 371 break 372 } 373 } 374 375 case *ssa.Select: 376 var cases []reflect.SelectCase 377 if !instr.Blocking { 378 cases = append(cases, reflect.SelectCase{ 379 Dir: reflect.SelectDefault, 380 }) 381 } 382 for _, state := range instr.States { 383 var dir reflect.SelectDir 384 if state.Dir == types.RecvOnly { 385 dir = reflect.SelectRecv 386 } else { 387 dir = reflect.SelectSend 388 } 389 var send reflect.Value 390 if state.Send != nil { 391 send = reflect.ValueOf(fr.get(state.Send)) 392 } 393 cases = append(cases, reflect.SelectCase{ 394 Dir: dir, 395 Chan: reflect.ValueOf(fr.get(state.Chan)), 396 Send: send, 397 }) 398 } 399 chosen, recv, recvOk := reflect.Select(cases) 400 if !instr.Blocking { 401 chosen-- // default case should have index -1. 402 } 403 r := tuple{chosen, recvOk} 404 for i, st := range instr.States { 405 if st.Dir == types.RecvOnly { 406 var v value 407 if i == chosen && recvOk { 408 // No need to copy since send makes an unaliased copy. 409 v = recv.Interface().(value) 410 } else { 411 v = zero(st.Chan.Type().Underlying().(*types.Chan).Elem()) 412 } 413 r = append(r, v) 414 } 415 } 416 fr.env[instr] = r 417 418 default: 419 panic(fmt.Sprintf("unexpected instruction: %T", instr)) 420 } 421 422 // if val, ok := instr.(ssa.Value); ok { 423 // fmt.Println(toString(fr.env[val])) // debugging 424 // } 425 426 return kNext 427 } 428 429 // prepareCall determines the function value and argument values for a 430 // function call in a Call, Go or Defer instruction, performing 431 // interface method lookup if needed. 432 // 433 func prepareCall(fr *frame, call *ssa.CallCommon) (fn value, args []value) { 434 v := fr.get(call.Value) 435 if call.Method == nil { 436 // Function call. 437 fn = v 438 } else { 439 // Interface method invocation. 440 recv := v.(iface) 441 if recv.t == nil { 442 panic("method invoked on nil interface") 443 } 444 if f := lookupMethod(fr.i, recv.t, call.Method); f == nil { 445 // Unreachable in well-typed programs. 446 panic(fmt.Sprintf("method set for dynamic type %v does not contain %s", recv.t, call.Method)) 447 } else { 448 fn = f 449 } 450 args = append(args, recv.v) 451 } 452 for _, arg := range call.Args { 453 args = append(args, fr.get(arg)) 454 } 455 return 456 } 457 458 // call interprets a call to a function (function, builtin or closure) 459 // fn with arguments args, returning its result. 460 // callpos is the position of the callsite. 461 // 462 func call(i *interpreter, caller *frame, callpos token.Pos, fn value, args []value) value { 463 switch fn := fn.(type) { 464 case *ssa.Function: 465 if fn == nil { 466 panic("call of nil function") // nil of func type 467 } 468 return callSSA(i, caller, callpos, fn, args, nil) 469 case *closure: 470 return callSSA(i, caller, callpos, fn.Fn, args, fn.Env) 471 case *ssa.Builtin: 472 return callBuiltin(caller, callpos, fn, args) 473 } 474 panic(fmt.Sprintf("cannot call %T", fn)) 475 } 476 477 func loc(fset *token.FileSet, pos token.Pos) string { 478 if pos == token.NoPos { 479 return "" 480 } 481 return " at " + fset.Position(pos).String() 482 } 483 484 // callSSA interprets a call to function fn with arguments args, 485 // and lexical environment env, returning its result. 486 // callpos is the position of the callsite. 487 // 488 func callSSA(i *interpreter, caller *frame, callpos token.Pos, fn *ssa.Function, args []value, env []value) value { 489 if i.mode&EnableTracing != 0 { 490 fset := fn.Prog.Fset 491 // TODO(adonovan): fix: loc() lies for external functions. 492 fmt.Fprintf(os.Stderr, "Entering %s%s.\n", fn, loc(fset, fn.Pos())) 493 suffix := "" 494 if caller != nil { 495 suffix = ", resuming " + caller.fn.String() + loc(fset, callpos) 496 } 497 defer fmt.Fprintf(os.Stderr, "Leaving %s%s.\n", fn, suffix) 498 } 499 fr := &frame{ 500 i: i, 501 caller: caller, // for panic/recover 502 fn: fn, 503 } 504 if fn.Parent() == nil { 505 name := fn.String() 506 if ext := externals[name]; ext != nil { 507 if i.mode&EnableTracing != 0 { 508 fmt.Fprintln(os.Stderr, "\t(external)") 509 } 510 return ext(fr, args) 511 } 512 if fn.Blocks == nil { 513 panic("no code for function: " + name) 514 } 515 } 516 fr.env = make(map[ssa.Value]value) 517 fr.block = fn.Blocks[0] 518 fr.locals = make([]value, len(fn.Locals)) 519 for i, l := range fn.Locals { 520 fr.locals[i] = zero(deref(l.Type())) 521 fr.env[l] = &fr.locals[i] 522 } 523 for i, p := range fn.Params { 524 fr.env[p] = args[i] 525 } 526 for i, fv := range fn.FreeVars { 527 fr.env[fv] = env[i] 528 } 529 for fr.block != nil { 530 runFrame(fr) 531 } 532 // Destroy the locals to avoid accidental use after return. 533 for i := range fn.Locals { 534 fr.locals[i] = bad{} 535 } 536 return fr.result 537 } 538 539 // runFrame executes SSA instructions starting at fr.block and 540 // continuing until a return, a panic, or a recovered panic. 541 // 542 // After a panic, runFrame panics. 543 // 544 // After a normal return, fr.result contains the result of the call 545 // and fr.block is nil. 546 // 547 // A recovered panic in a function without named return parameters 548 // (NRPs) becomes a normal return of the zero value of the function's 549 // result type. 550 // 551 // After a recovered panic in a function with NRPs, fr.result is 552 // undefined and fr.block contains the block at which to resume 553 // control. 554 // 555 func runFrame(fr *frame) { 556 defer func() { 557 if fr.block == nil { 558 return // normal return 559 } 560 if fr.i.mode&DisableRecover != 0 { 561 return // let interpreter crash 562 } 563 fr.panicking = true 564 fr.panic = recover() 565 if fr.i.mode&EnableTracing != 0 { 566 fmt.Fprintf(os.Stderr, "Panicking: %T %v.\n", fr.panic, fr.panic) 567 } 568 fr.runDefers() 569 fr.block = fr.fn.Recover 570 }() 571 572 for { 573 if fr.i.mode&EnableTracing != 0 { 574 fmt.Fprintf(os.Stderr, ".%s:\n", fr.block) 575 } 576 block: 577 for _, instr := range fr.block.Instrs { 578 if fr.i.mode&EnableTracing != 0 { 579 if v, ok := instr.(ssa.Value); ok { 580 fmt.Fprintln(os.Stderr, "\t", v.Name(), "=", instr) 581 } else { 582 fmt.Fprintln(os.Stderr, "\t", instr) 583 } 584 } 585 switch visitInstr(fr, instr) { 586 case kReturn: 587 return 588 case kNext: 589 // no-op 590 case kJump: 591 break block 592 } 593 } 594 } 595 } 596 597 // doRecover implements the recover() built-in. 598 func doRecover(caller *frame) value { 599 // recover() must be exactly one level beneath the deferred 600 // function (two levels beneath the panicking function) to 601 // have any effect. Thus we ignore both "defer recover()" and 602 // "defer f() -> g() -> recover()". 603 if caller.i.mode&DisableRecover == 0 && 604 caller != nil && !caller.panicking && 605 caller.caller != nil && caller.caller.panicking { 606 caller.caller.panicking = false 607 p := caller.caller.panic 608 caller.caller.panic = nil 609 610 // TODO(adonovan): support runtime.Goexit. 611 switch p := p.(type) { 612 case targetPanic: 613 // The target program explicitly called panic(). 614 return p.v 615 case runtime.Error: 616 // The interpreter encountered a runtime error. 617 return iface{caller.i.runtimeErrorString, p.Error()} 618 case string: 619 // The interpreter explicitly called panic(). 620 return iface{caller.i.runtimeErrorString, p} 621 default: 622 panic(fmt.Sprintf("unexpected panic type %T in target call to recover()", p)) 623 } 624 } 625 return iface{} 626 } 627 628 // setGlobal sets the value of a system-initialized global variable. 629 func setGlobal(i *interpreter, pkg *ssa.Package, name string, v value) { 630 if g, ok := i.globals[pkg.Var(name)]; ok { 631 *g = v 632 return 633 } 634 panic("no global variable: " + pkg.Pkg.Path() + "." + name) 635 } 636 637 // Interpret interprets the Go program whose main package is mainpkg. 638 // mode specifies various interpreter options. filename and args are 639 // the initial values of os.Args for the target program. sizes is the 640 // effective type-sizing function for this program. 641 // 642 // Interpret returns the exit code of the program: 2 for panic (like 643 // gc does), or the argument to os.Exit for normal termination. 644 // 645 // The SSA program must include the "runtime" package. 646 // 647 func Interpret(mainpkg *ssa.Package, mode Mode, sizes types.Sizes, filename string, args []string) (exitCode int) { 648 i := &interpreter{ 649 prog: mainpkg.Prog, 650 globals: make(map[ssa.Value]*value), 651 mode: mode, 652 sizes: sizes, 653 goroutines: 1, 654 } 655 runtimePkg := i.prog.ImportedPackage("runtime") 656 if runtimePkg == nil { 657 panic("ssa.Program doesn't include runtime package") 658 } 659 i.runtimeErrorString = runtimePkg.Type("errorString").Object().Type() 660 661 initReflect(i) 662 663 i.osArgs = append(i.osArgs, filename) 664 for _, arg := range args { 665 i.osArgs = append(i.osArgs, arg) 666 } 667 668 for _, pkg := range i.prog.AllPackages() { 669 // Initialize global storage. 670 for _, m := range pkg.Members { 671 switch v := m.(type) { 672 case *ssa.Global: 673 cell := zero(deref(v.Type())) 674 i.globals[v] = &cell 675 } 676 } 677 } 678 679 // Top-level error handler. 680 exitCode = 2 681 defer func() { 682 if exitCode != 2 || i.mode&DisableRecover != 0 { 683 return 684 } 685 switch p := recover().(type) { 686 case exitPanic: 687 exitCode = int(p) 688 return 689 case targetPanic: 690 fmt.Fprintln(os.Stderr, "panic:", toString(p.v)) 691 case runtime.Error: 692 fmt.Fprintln(os.Stderr, "panic:", p.Error()) 693 case string: 694 fmt.Fprintln(os.Stderr, "panic:", p) 695 default: 696 fmt.Fprintf(os.Stderr, "panic: unexpected type: %T: %v\n", p, p) 697 } 698 699 // TODO(adonovan): dump panicking interpreter goroutine? 700 // buf := make([]byte, 0x10000) 701 // runtime.Stack(buf, false) 702 // fmt.Fprintln(os.Stderr, string(buf)) 703 // (Or dump panicking target goroutine?) 704 }() 705 706 // Run! 707 call(i, nil, token.NoPos, mainpkg.Func("init"), nil) 708 if mainFn := mainpkg.Func("main"); mainFn != nil { 709 call(i, nil, token.NoPos, mainFn, nil) 710 exitCode = 0 711 } else { 712 fmt.Fprintln(os.Stderr, "No main function.") 713 exitCode = 1 714 } 715 return 716 } 717 718 // deref returns a pointer's element type; otherwise it returns typ. 719 // TODO(adonovan): Import from ssa? 720 func deref(typ types.Type) types.Type { 721 if p, ok := typ.Underlying().(*types.Pointer); ok { 722 return p.Elem() 723 } 724 return typ 725 }