Debian Codegraph @

go/ssa/interp/interp.go

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