* typeck2.c (cxx_incomplete_type_diagnostic): Revert change and
[official-gcc.git] / libgo / go / runtime / panic.go
blobaa196aee7b564e52d93fab76e94a56bc68ba5616
1 // Copyright 2014 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.
5 package runtime
7 import (
8 "runtime/internal/atomic"
9 "unsafe"
12 // For gccgo, use go:linkname to rename compiler-called functions to
13 // themselves, so that the compiler will export them.
15 //go:linkname deferproc runtime.deferproc
16 //go:linkname deferreturn runtime.deferreturn
17 //go:linkname setdeferretaddr runtime.setdeferretaddr
18 //go:linkname checkdefer runtime.checkdefer
19 //go:linkname gopanic runtime.gopanic
20 //go:linkname canrecover runtime.canrecover
21 //go:linkname makefuncfficanrecover runtime.makefuncfficanrecover
22 //go:linkname makefuncreturning runtime.makefuncreturning
23 //go:linkname gorecover runtime.gorecover
24 //go:linkname deferredrecover runtime.deferredrecover
25 // Temporary for C code to call:
26 //go:linkname throw runtime.throw
28 // Calling panic with one of the errors below will call errorString.Error
29 // which will call mallocgc to concatenate strings. That will fail if
30 // malloc is locked, causing a confusing error message. Throw a better
31 // error message instead.
32 func panicCheckMalloc(err error) {
33 gp := getg()
34 if gp != nil && gp.m != nil && gp.m.mallocing != 0 {
35 throw(string(err.(errorString)))
39 var indexError = error(errorString("index out of range"))
41 func panicindex() {
42 panicCheckMalloc(indexError)
43 panic(indexError)
46 var sliceError = error(errorString("slice bounds out of range"))
48 func panicslice() {
49 panicCheckMalloc(sliceError)
50 panic(sliceError)
53 var divideError = error(errorString("integer divide by zero"))
55 func panicdivide() {
56 panicCheckMalloc(divideError)
57 panic(divideError)
60 var overflowError = error(errorString("integer overflow"))
62 func panicoverflow() {
63 panicCheckMalloc(overflowError)
64 panic(overflowError)
67 var floatError = error(errorString("floating point error"))
69 func panicfloat() {
70 panicCheckMalloc(floatError)
71 panic(floatError)
74 var memoryError = error(errorString("invalid memory address or nil pointer dereference"))
76 func panicmem() {
77 panicCheckMalloc(memoryError)
78 panic(memoryError)
81 func throwinit() {
82 throw("recursive call during initialization - linker skew")
85 // deferproc creates a new deferred function.
86 // The compiler turns a defer statement into a call to this.
87 // frame points into the stack frame; it is used to determine which
88 // deferred functions are for the current stack frame, and whether we
89 // have already deferred functions for this frame.
90 // pfn is a C function pointer.
91 // arg is a value to pass to pfn.
92 func deferproc(frame *bool, pfn uintptr, arg unsafe.Pointer) {
93 n := newdefer()
94 n.frame = frame
95 n._panic = getg()._panic
96 n.pfn = pfn
97 n.arg = arg
98 n.retaddr = 0
99 n.makefunccanrecover = false
102 // Allocate a Defer, usually using per-P pool.
103 // Each defer must be released with freedefer.
104 func newdefer() *_defer {
105 var d *_defer
106 gp := getg()
107 pp := gp.m.p.ptr()
108 if len(pp.deferpool) == 0 && sched.deferpool != nil {
109 systemstack(func() {
110 lock(&sched.deferlock)
111 for len(pp.deferpool) < cap(pp.deferpool)/2 && sched.deferpool != nil {
112 d := sched.deferpool
113 sched.deferpool = d.link
114 d.link = nil
115 pp.deferpool = append(pp.deferpool, d)
117 unlock(&sched.deferlock)
120 if n := len(pp.deferpool); n > 0 {
121 d = pp.deferpool[n-1]
122 pp.deferpool[n-1] = nil
123 pp.deferpool = pp.deferpool[:n-1]
125 if d == nil {
126 systemstack(func() {
127 d = new(_defer)
130 d.link = gp._defer
131 gp._defer = d
132 return d
135 // Free the given defer.
136 // The defer cannot be used after this call.
138 // This must not grow the stack because there may be a frame without a
139 // stack map when this is called.
141 //go:nosplit
142 func freedefer(d *_defer) {
143 // When C code calls a Go function on a non-Go thread, the
144 // deferred call to cgocallBackDone will set g to nil.
145 // Don't crash trying to put d on the free list; just let it
146 // be garbage collected.
147 if getg() == nil {
148 return
151 pp := getg().m.p.ptr()
152 if len(pp.deferpool) == cap(pp.deferpool) {
153 // Transfer half of local cache to the central cache.
155 // Take this slow path on the system stack so
156 // we don't grow freedefer's stack.
157 systemstack(func() {
158 var first, last *_defer
159 for len(pp.deferpool) > cap(pp.deferpool)/2 {
160 n := len(pp.deferpool)
161 d := pp.deferpool[n-1]
162 pp.deferpool[n-1] = nil
163 pp.deferpool = pp.deferpool[:n-1]
164 if first == nil {
165 first = d
166 } else {
167 last.link = d
169 last = d
171 lock(&sched.deferlock)
172 last.link = sched.deferpool
173 sched.deferpool = first
174 unlock(&sched.deferlock)
177 *d = _defer{}
178 pp.deferpool = append(pp.deferpool, d)
181 // deferreturn is called to undefer the stack.
182 // The compiler inserts a call to this function as a finally clause
183 // wrapped around the body of any function that calls defer.
184 // The frame argument points to the stack frame of the function.
185 func deferreturn(frame *bool) {
186 gp := getg()
187 for gp._defer != nil && gp._defer.frame == frame {
188 d := gp._defer
189 pfn := d.pfn
190 d.pfn = 0
192 if pfn != 0 {
193 // This is rather awkward.
194 // The gc compiler does this using assembler
195 // code in jmpdefer.
196 var fn func(unsafe.Pointer)
197 *(**uintptr)(unsafe.Pointer(&fn)) = &pfn
198 fn(d.arg)
201 gp._defer = d.link
203 freedefer(d)
205 // Since we are executing a defer function now, we
206 // know that we are returning from the calling
207 // function. If the calling function, or one of its
208 // callees, panicked, then the defer functions would
209 // be executed by panic.
210 *frame = true
214 // __builtin_extract_return_addr is a GCC intrinsic that converts an
215 // address returned by __builtin_return_address(0) to a real address.
216 // On most architectures this is a nop.
217 //extern __builtin_extract_return_addr
218 func __builtin_extract_return_addr(uintptr) uintptr
220 // setdeferretaddr records the address to which the deferred function
221 // returns. This is check by canrecover. The frontend relies on this
222 // function returning false.
223 func setdeferretaddr(retaddr uintptr) bool {
224 gp := getg()
225 if gp._defer != nil {
226 gp._defer.retaddr = __builtin_extract_return_addr(retaddr)
228 return false
231 // checkdefer is called by exception handlers used when unwinding the
232 // stack after a recovered panic. The exception handler is simply
233 // checkdefer(frame)
234 // return;
235 // If we have not yet reached the frame we are looking for, we
236 // continue unwinding.
237 func checkdefer(frame *bool) {
238 gp := getg()
239 if gp == nil {
240 // We should never wind up here. Even if some other
241 // language throws an exception, the cgo code
242 // should ensure that g is set.
243 throw("no g in checkdefer")
244 } else if gp.isforeign {
245 // Some other language has thrown an exception.
246 // We need to run the local defer handlers.
247 // If they call recover, we stop unwinding here.
248 var p _panic
249 p.isforeign = true
250 p.link = gp._panic
251 gp._panic = &p
252 for {
253 d := gp._defer
254 if d == nil || d.frame != frame || d.pfn == 0 {
255 break
258 pfn := d.pfn
259 gp._defer = d.link
261 var fn func(unsafe.Pointer)
262 *(**uintptr)(unsafe.Pointer(&fn)) = &pfn
263 fn(d.arg)
265 freedefer(d)
267 if p.recovered {
268 // The recover function caught the panic
269 // thrown by some other language.
270 break
274 recovered := p.recovered
275 gp._panic = p.link
277 if recovered {
278 // Just return and continue executing Go code.
279 *frame = true
280 return
283 // We are panicking through this function.
284 *frame = false
285 } else if gp._defer != nil && gp._defer.pfn == 0 && gp._defer.frame == frame {
286 // This is the defer function that called recover.
287 // Simply return to stop the stack unwind, and let the
288 // Go code continue to execute.
289 d := gp._defer
290 gp._defer = d.link
291 freedefer(d)
293 // We are returning from this function.
294 *frame = true
296 return
299 // This is some other defer function. It was already run by
300 // the call to panic, or just above. Rethrow the exception.
301 rethrowException()
302 throw("rethrowException returned")
305 // unwindStack starts unwinding the stack for a panic. We unwind
306 // function calls until we reach the one which used a defer function
307 // which called recover. Each function which uses a defer statement
308 // will have an exception handler, as shown above for checkdefer.
309 func unwindStack() {
310 // Allocate the exception type used by the unwind ABI.
311 // It would be nice to define it in runtime_sysinfo.go,
312 // but current definitions don't work because the required
313 // alignment is larger than can be represented in Go.
314 // The type never contains any Go pointers.
315 size := unwindExceptionSize()
316 usize := uintptr(unsafe.Sizeof(uintptr(0)))
317 c := (size + usize - 1) / usize
318 s := make([]uintptr, c)
319 getg().exception = unsafe.Pointer(&s[0])
320 throwException()
323 // Goexit terminates the goroutine that calls it. No other goroutine is affected.
324 // Goexit runs all deferred calls before terminating the goroutine. Because Goexit
325 // is not panic, however, any recover calls in those deferred functions will return nil.
327 // Calling Goexit from the main goroutine terminates that goroutine
328 // without func main returning. Since func main has not returned,
329 // the program continues execution of other goroutines.
330 // If all other goroutines exit, the program crashes.
331 func Goexit() {
332 // Run all deferred functions for the current goroutine.
333 // This code is similar to gopanic, see that implementation
334 // for detailed comments.
335 gp := getg()
336 for {
337 d := gp._defer
338 if d == nil {
339 break
341 gp._defer = d.link
343 pfn := d.pfn
344 d.pfn = 0
346 if pfn != 0 {
347 var fn func(unsafe.Pointer)
348 *(**uintptr)(unsafe.Pointer(&fn)) = &pfn
349 fn(d.arg)
352 freedefer(d)
353 // Note: we ignore recovers here because Goexit isn't a panic
355 goexit1()
358 // Call all Error and String methods before freezing the world.
359 // Used when crashing with panicking.
360 // This must match types handled by printany.
361 func preprintpanics(p *_panic) {
362 defer func() {
363 if recover() != nil {
364 throw("panic while printing panic value")
367 for p != nil {
368 switch v := p.arg.(type) {
369 case error:
370 p.arg = v.Error()
371 case stringer:
372 p.arg = v.String()
374 p = p.link
378 // Print all currently active panics. Used when crashing.
379 func printpanics(p *_panic) {
380 if p.link != nil {
381 printpanics(p.link)
382 print("\t")
384 print("panic: ")
385 printany(p.arg)
386 if p.recovered {
387 print(" [recovered]")
389 print("\n")
392 // The implementation of the predeclared function panic.
393 func gopanic(e interface{}) {
394 gp := getg()
395 if gp.m.curg != gp {
396 print("panic: ")
397 printany(e)
398 print("\n")
399 throw("panic on system stack")
402 if gp.m.mallocing != 0 {
403 print("panic: ")
404 printany(e)
405 print("\n")
406 throw("panic during malloc")
408 if gp.m.preemptoff != "" {
409 print("panic: ")
410 printany(e)
411 print("\n")
412 print("preempt off reason: ")
413 print(gp.m.preemptoff)
414 print("\n")
415 throw("panic during preemptoff")
417 if gp.m.locks != 0 {
418 print("panic: ")
419 printany(e)
420 print("\n")
421 throw("panic holding locks")
424 // The gc compiler allocates this new _panic struct on the
425 // stack. We can't do that, because when a deferred function
426 // recovers the panic we unwind the stack. We unlink this
427 // entry before unwinding the stack, but that doesn't help in
428 // the case where we panic, a deferred function recovers and
429 // then panics itself, that panic is in turn recovered, and
430 // unwinds the stack past this stack frame.
432 p := &_panic{
433 arg: e,
434 link: gp._panic,
436 gp._panic = p
438 for {
439 d := gp._defer
440 if d == nil {
441 break
444 pfn := d.pfn
445 d.pfn = 0
447 if pfn != 0 {
448 var fn func(unsafe.Pointer)
449 *(**uintptr)(unsafe.Pointer(&fn)) = &pfn
450 fn(d.arg)
452 if p.recovered {
453 // Some deferred function called recover.
454 // Stop running this panic.
455 gp._panic = p.link
457 // Unwind the stack by throwing an exception.
458 // The compiler has arranged to create
459 // exception handlers in each function
460 // that uses a defer statement. These
461 // exception handlers will check whether
462 // the entry on the top of the defer stack
463 // is from the current function. If it is,
464 // we have unwound the stack far enough.
465 unwindStack()
467 throw("unwindStack returned")
470 // Because we executed that defer function by a panic,
471 // and it did not call recover, we know that we are
472 // not returning from the calling function--we are
473 // panicking through it.
474 *d.frame = false
477 gp._defer = d.link
478 freedefer(d)
481 // ran out of deferred calls - old-school panic now
482 // Because it is unsafe to call arbitrary user code after freezing
483 // the world, we call preprintpanics to invoke all necessary Error
484 // and String methods to prepare the panic strings before startpanic.
485 preprintpanics(gp._panic)
486 startpanic()
487 printpanics(gp._panic)
488 dopanic(0) // should not return
489 *(*int)(nil) = 0 // not reached
492 // currentDefer returns the top of the defer stack if it can be recovered.
493 // Otherwise it returns nil.
494 func currentDefer() *_defer {
495 gp := getg()
496 d := gp._defer
497 if d == nil {
498 return nil
501 // The panic that would be recovered is the one on the top of
502 // the panic stack. We do not want to recover it if that panic
503 // was on the top of the panic stack when this function was
504 // deferred.
505 if d._panic == gp._panic {
506 return nil
509 // The deferred thunk will call setdeferretaddr. If this has
510 // not happened, then we have not been called via defer, and
511 // we can not recover.
512 if d.retaddr == 0 {
513 return nil
516 return d
519 // canrecover is called by a thunk to see if the real function would
520 // be permitted to recover a panic value. Recovering a value is
521 // permitted if the thunk was called directly by defer. retaddr is the
522 // return address of the function that is calling canrecover--that is,
523 // the thunk.
524 func canrecover(retaddr uintptr) bool {
525 d := currentDefer()
526 if d == nil {
527 return false
530 ret := __builtin_extract_return_addr(retaddr)
531 dret := d.retaddr
532 if ret <= dret && ret+16 >= dret {
533 return true
536 // On some systems, in some cases, the return address does not
537 // work reliably. See http://gcc.gnu.org/PR60406. If we are
538 // permitted to call recover, the call stack will look like this:
539 // runtime.gopanic, runtime.deferreturn, etc.
540 // thunk to call deferred function (calls __go_set_defer_retaddr)
541 // function that calls __go_can_recover (passing return address)
542 // runtime.canrecover
543 // Calling callers will skip the thunks. So if our caller's
544 // caller starts with "runtime.", then we are permitted to
545 // call recover.
546 var locs [16]location
547 if callers(2, locs[:2]) < 2 {
548 return false
551 name := locs[1].function
552 if hasprefix(name, "runtime.") {
553 return true
556 // If the function calling recover was created by reflect.MakeFunc,
557 // then makefuncfficanrecover will have set makefunccanrecover.
558 if !d.makefunccanrecover {
559 return false
562 // We look up the stack, ignoring libffi functions and
563 // functions in the reflect package, until we find
564 // reflect.makeFuncStub or reflect.ffi_callback called by FFI
565 // functions. Then we check the caller of that function.
567 n := callers(3, locs[:])
568 foundFFICallback := false
569 i := 0
570 for ; i < n; i++ {
571 name = locs[i].function
572 if name == "" {
573 // No function name means this caller isn't Go code.
574 // Assume that this is libffi.
575 continue
578 // Ignore function in libffi.
579 if hasprefix(name, "ffi_") {
580 continue
583 if foundFFICallback {
584 break
587 if name == "reflect.ffi_callback" {
588 foundFFICallback = true
589 continue
592 // Ignore other functions in the reflect package.
593 if hasprefix(name, "reflect.") {
594 continue
597 // We should now be looking at the real caller.
598 break
601 if i < n {
602 name = locs[i].function
603 if hasprefix(name, "runtime.") {
604 return true
608 return false
611 // This function is called when code is about to enter a function
612 // created by the libffi version of reflect.MakeFunc. This function is
613 // passed the names of the callers of the libffi code that called the
614 // stub. It uses them to decide whether it is permitted to call
615 // recover, and sets d.makefunccanrecover so that gorecover can make
616 // the same decision.
617 func makefuncfficanrecover(loc []location) {
618 d := currentDefer()
619 if d == nil {
620 return
623 // If we are already in a call stack of MakeFunc functions,
624 // there is nothing we can usefully check here.
625 if d.makefunccanrecover {
626 return
629 // loc starts with the caller of our caller. That will be a thunk.
630 // If its caller was a function function, then it was called
631 // directly by defer.
632 if len(loc) < 2 {
633 return
636 name := loc[1].function
637 if hasprefix(name, "runtime.") {
638 d.makefunccanrecover = true
642 // makefuncreturning is called when code is about to exit a function
643 // created by reflect.MakeFunc. It is called by the function stub used
644 // by reflect.MakeFunc. It clears the makefunccanrecover field. It's
645 // OK to always clear this field, because canrecover will only be
646 // called by a stub created for a function that calls recover. That
647 // stub will not call a function created by reflect.MakeFunc, so by
648 // the time we get here any caller higher up on the call stack no
649 // longer needs the information.
650 func makefuncreturning() {
651 d := getg()._defer
652 if d != nil {
653 d.makefunccanrecover = false
657 // The implementation of the predeclared function recover.
658 func gorecover() interface{} {
659 gp := getg()
660 p := gp._panic
661 if p != nil && !p.recovered {
662 p.recovered = true
663 return p.arg
665 return nil
668 // deferredrecover is called when a call to recover is deferred. That
669 // is, something like
670 // defer recover()
672 // We need to handle this specially. In gc, the recover function
673 // looks up the stack frame. In particular, that means that a deferred
674 // recover will not recover a panic thrown in the same function that
675 // defers the recover. It will only recover a panic thrown in a
676 // function that defers the deferred call to recover.
678 // In other words:
680 // func f1() {
681 // defer recover() // does not stop panic
682 // panic(0)
683 // }
685 // func f2() {
686 // defer func() {
687 // defer recover() // stops panic(0)
688 // }()
689 // panic(0)
690 // }
692 // func f3() {
693 // defer func() {
694 // defer recover() // does not stop panic
695 // panic(0)
696 // }()
697 // panic(1)
698 // }
700 // func f4() {
701 // defer func() {
702 // defer func() {
703 // defer recover() // stops panic(0)
704 // }()
705 // panic(0)
706 // }()
707 // panic(1)
708 // }
710 // The interesting case here is f3. As can be seen from f2, the
711 // deferred recover could pick up panic(1). However, this does not
712 // happen because it is blocked by the panic(0).
714 // When a function calls recover, then when we invoke it we pass a
715 // hidden parameter indicating whether it should recover something.
716 // This parameter is set based on whether the function is being
717 // invoked directly from defer. The parameter winds up determining
718 // whether __go_recover or __go_deferred_recover is called at all.
720 // In the case of a deferred recover, the hidden parameter that
721 // controls the call is actually the one set up for the function that
722 // runs the defer recover() statement. That is the right thing in all
723 // the cases above except for f3. In f3 the function is permitted to
724 // call recover, but the deferred recover call is not. We address that
725 // here by checking for that specific case before calling recover. If
726 // this function was deferred when there is already a panic on the
727 // panic stack, then we can only recover that panic, not any other.
729 // Note that we can get away with using a special function here
730 // because you are not permitted to take the address of a predeclared
731 // function like recover.
732 func deferredrecover() interface{} {
733 gp := getg()
734 if gp._defer == nil || gp._defer._panic != gp._panic {
735 return nil
737 return gorecover()
740 //go:linkname sync_throw sync.throw
741 func sync_throw(s string) {
742 throw(s)
745 //go:nosplit
746 func throw(s string) {
747 print("fatal error: ", s, "\n")
748 gp := getg()
749 if gp.m.throwing == 0 {
750 gp.m.throwing = 1
752 startpanic()
753 dopanic(0)
754 *(*int)(nil) = 0 // not reached
757 //uint32 runtime·panicking;
758 var paniclk mutex
760 func startpanic() {
761 _g_ := getg()
762 // Uncomment when mheap_ is in Go.
763 // if mheap_.cachealloc.size == 0 { // very early
764 // print("runtime: panic before malloc heap initialized\n")
765 // _g_.m.mallocing = 1 // tell rest of panic not to try to malloc
766 // } else
767 if _g_.m.mcache == nil { // can happen if called from signal handler or throw
768 _g_.m.mcache = allocmcache()
771 switch _g_.m.dying {
772 case 0:
773 _g_.m.dying = 1
774 _g_.writebuf = nil
775 atomic.Xadd(&panicking, 1)
776 lock(&paniclk)
777 if debug.schedtrace > 0 || debug.scheddetail > 0 {
778 schedtrace(true)
780 freezetheworld()
781 return
782 case 1:
783 // Something failed while panicking, probably the print of the
784 // argument to panic(). Just print a stack trace and exit.
785 _g_.m.dying = 2
786 print("panic during panic\n")
787 dopanic(0)
788 exit(3)
789 fallthrough
790 case 2:
791 // This is a genuine bug in the runtime, we couldn't even
792 // print the stack trace successfully.
793 _g_.m.dying = 3
794 print("stack trace unavailable\n")
795 exit(4)
796 fallthrough
797 default:
798 // Can't even print! Just exit.
799 exit(5)
803 var didothers bool
804 var deadlock mutex
806 func dopanic(unused int) {
807 gp := getg()
808 if gp.sig != 0 {
809 signame := signame(gp.sig)
810 if signame != "" {
811 print("[signal ", signame)
812 } else {
813 print("[signal ", hex(gp.sig))
815 print(" code=", hex(gp.sigcode0), " addr=", hex(gp.sigcode1), " pc=", hex(gp.sigpc), "]\n")
818 level, all, docrash := gotraceback()
819 _g_ := getg()
820 if level > 0 {
821 if gp != gp.m.curg {
822 all = true
824 if gp != gp.m.g0 {
825 print("\n")
826 goroutineheader(gp)
827 traceback(0)
828 } else if level >= 2 || _g_.m.throwing > 0 {
829 print("\nruntime stack:\n")
830 traceback(0)
832 if !didothers && all {
833 didothers = true
834 tracebackothers(gp)
837 unlock(&paniclk)
839 if atomic.Xadd(&panicking, -1) != 0 {
840 // Some other m is panicking too.
841 // Let it print what it needs to print.
842 // Wait forever without chewing up cpu.
843 // It will exit when it's done.
844 lock(&deadlock)
845 lock(&deadlock)
848 if docrash {
849 crash()
852 exit(2)
855 //go:nosplit
856 func canpanic(gp *g) bool {
857 // Note that g is m->gsignal, different from gp.
858 // Note also that g->m can change at preemption, so m can go stale
859 // if this function ever makes a function call.
860 _g_ := getg()
861 _m_ := _g_.m
863 // Is it okay for gp to panic instead of crashing the program?
864 // Yes, as long as it is running Go code, not runtime code,
865 // and not stuck in a system call.
866 if gp == nil || gp != _m_.curg {
867 return false
869 if _m_.locks-_m_.softfloat != 0 || _m_.mallocing != 0 || _m_.throwing != 0 || _m_.preemptoff != "" || _m_.dying != 0 {
870 return false
872 status := readgstatus(gp)
873 if status&^_Gscan != _Grunning || gp.syscallsp != 0 {
874 return false
876 return true