libgo: update to Go1.10rc1
[official-gcc.git] / libgo / go / runtime / panic.go
blobfbdb17e5e5a93f0400c494ec051a19bd6e072c27
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 //go:linkname panicmem runtime.panicmem
26 // Temporary for C code to call:
27 //go:linkname throw runtime.throw
29 // Calling panic with one of the errors below will call errorString.Error
30 // which will call mallocgc to concatenate strings. That will fail if
31 // malloc is locked, causing a confusing error message. Throw a better
32 // error message instead.
33 func panicCheckMalloc(err error) {
34 gp := getg()
35 if gp != nil && gp.m != nil && gp.m.mallocing != 0 {
36 throw(string(err.(errorString)))
40 var indexError = error(errorString("index out of range"))
42 func panicindex() {
43 panicCheckMalloc(indexError)
44 panic(indexError)
47 var sliceError = error(errorString("slice bounds out of range"))
49 func panicslice() {
50 panicCheckMalloc(sliceError)
51 panic(sliceError)
54 var divideError = error(errorString("integer divide by zero"))
56 func panicdivide() {
57 panicCheckMalloc(divideError)
58 panic(divideError)
61 var overflowError = error(errorString("integer overflow"))
63 func panicoverflow() {
64 panicCheckMalloc(overflowError)
65 panic(overflowError)
68 var floatError = error(errorString("floating point error"))
70 func panicfloat() {
71 panicCheckMalloc(floatError)
72 panic(floatError)
75 var memoryError = error(errorString("invalid memory address or nil pointer dereference"))
77 func panicmem() {
78 panicCheckMalloc(memoryError)
79 panic(memoryError)
82 func throwinit() {
83 throw("recursive call during initialization - linker skew")
86 // deferproc creates a new deferred function.
87 // The compiler turns a defer statement into a call to this.
88 // frame points into the stack frame; it is used to determine which
89 // deferred functions are for the current stack frame, and whether we
90 // have already deferred functions for this frame.
91 // pfn is a C function pointer.
92 // arg is a value to pass to pfn.
93 func deferproc(frame *bool, pfn uintptr, arg unsafe.Pointer) {
94 d := newdefer()
95 if d._panic != nil {
96 throw("deferproc: d.panic != nil after newdefer")
98 d.frame = frame
99 d.panicStack = getg()._panic
100 d.pfn = pfn
101 d.arg = arg
102 d.retaddr = 0
103 d.makefunccanrecover = false
106 // Allocate a Defer, usually using per-P pool.
107 // Each defer must be released with freedefer.
108 func newdefer() *_defer {
109 var d *_defer
110 gp := getg()
111 pp := gp.m.p.ptr()
112 if len(pp.deferpool) == 0 && sched.deferpool != nil {
113 systemstack(func() {
114 lock(&sched.deferlock)
115 for len(pp.deferpool) < cap(pp.deferpool)/2 && sched.deferpool != nil {
116 d := sched.deferpool
117 sched.deferpool = d.link
118 d.link = nil
119 pp.deferpool = append(pp.deferpool, d)
121 unlock(&sched.deferlock)
124 if n := len(pp.deferpool); n > 0 {
125 d = pp.deferpool[n-1]
126 pp.deferpool[n-1] = nil
127 pp.deferpool = pp.deferpool[:n-1]
129 if d == nil {
130 systemstack(func() {
131 d = new(_defer)
134 d.link = gp._defer
135 gp._defer = d
136 return d
139 // Free the given defer.
140 // The defer cannot be used after this call.
142 // This must not grow the stack because there may be a frame without a
143 // stack map when this is called.
145 //go:nosplit
146 func freedefer(d *_defer) {
147 pp := getg().m.p.ptr()
148 if len(pp.deferpool) == cap(pp.deferpool) {
149 // Transfer half of local cache to the central cache.
151 // Take this slow path on the system stack so
152 // we don't grow freedefer's stack.
153 systemstack(func() {
154 var first, last *_defer
155 for len(pp.deferpool) > cap(pp.deferpool)/2 {
156 n := len(pp.deferpool)
157 d := pp.deferpool[n-1]
158 pp.deferpool[n-1] = nil
159 pp.deferpool = pp.deferpool[:n-1]
160 if first == nil {
161 first = d
162 } else {
163 last.link = d
165 last = d
167 lock(&sched.deferlock)
168 last.link = sched.deferpool
169 sched.deferpool = first
170 unlock(&sched.deferlock)
174 // These lines used to be simply `*d = _defer{}` but that
175 // started causing a nosplit stack overflow via typedmemmove.
176 d.link = nil
177 d.frame = nil
178 d.panicStack = nil
179 d._panic = nil
180 d.pfn = 0
181 d.arg = nil
182 d.retaddr = 0
183 d.makefunccanrecover = false
185 pp.deferpool = append(pp.deferpool, d)
188 // deferreturn is called to undefer the stack.
189 // The compiler inserts a call to this function as a finally clause
190 // wrapped around the body of any function that calls defer.
191 // The frame argument points to the stack frame of the function.
192 func deferreturn(frame *bool) {
193 gp := getg()
194 for gp._defer != nil && gp._defer.frame == frame {
195 d := gp._defer
196 pfn := d.pfn
197 d.pfn = 0
199 if pfn != 0 {
200 // This is rather awkward.
201 // The gc compiler does this using assembler
202 // code in jmpdefer.
203 var fn func(unsafe.Pointer)
204 *(*uintptr)(unsafe.Pointer(&fn)) = uintptr(noescape(unsafe.Pointer(&pfn)))
205 fn(d.arg)
208 // If we are returning from a Go function called by a
209 // C function running in a C thread, g may now be nil,
210 // in which case CgocallBackDone will have cleared _defer.
211 // In that case some other goroutine may already be using gp.
212 if getg() == nil {
213 *frame = true
214 return
217 gp._defer = d.link
219 freedefer(d)
221 // Since we are executing a defer function now, we
222 // know that we are returning from the calling
223 // function. If the calling function, or one of its
224 // callees, panicked, then the defer functions would
225 // be executed by panic.
226 *frame = true
230 // __builtin_extract_return_addr is a GCC intrinsic that converts an
231 // address returned by __builtin_return_address(0) to a real address.
232 // On most architectures this is a nop.
233 //extern __builtin_extract_return_addr
234 func __builtin_extract_return_addr(uintptr) uintptr
236 // setdeferretaddr records the address to which the deferred function
237 // returns. This is check by canrecover. The frontend relies on this
238 // function returning false.
239 func setdeferretaddr(retaddr uintptr) bool {
240 gp := getg()
241 if gp._defer != nil {
242 gp._defer.retaddr = __builtin_extract_return_addr(retaddr)
244 return false
247 // checkdefer is called by exception handlers used when unwinding the
248 // stack after a recovered panic. The exception handler is simply
249 // checkdefer(frame)
250 // return;
251 // If we have not yet reached the frame we are looking for, we
252 // continue unwinding.
253 func checkdefer(frame *bool) {
254 gp := getg()
255 if gp == nil {
256 // We should never wind up here. Even if some other
257 // language throws an exception, the cgo code
258 // should ensure that g is set.
259 throw("no g in checkdefer")
260 } else if gp.isforeign {
261 // Some other language has thrown an exception.
262 // We need to run the local defer handlers.
263 // If they call recover, we stop unwinding here.
264 var p _panic
265 p.isforeign = true
266 p.link = gp._panic
267 gp._panic = (*_panic)(noescape(unsafe.Pointer(&p)))
268 for {
269 d := gp._defer
270 if d == nil || d.frame != frame || d.pfn == 0 {
271 break
274 pfn := d.pfn
275 gp._defer = d.link
277 var fn func(unsafe.Pointer)
278 *(*uintptr)(unsafe.Pointer(&fn)) = uintptr(noescape(unsafe.Pointer(&pfn)))
279 fn(d.arg)
281 freedefer(d)
283 if p.recovered {
284 // The recover function caught the panic
285 // thrown by some other language.
286 break
290 recovered := p.recovered
291 gp._panic = p.link
293 if recovered {
294 // Just return and continue executing Go code.
295 *frame = true
296 return
299 // We are panicking through this function.
300 *frame = false
301 } else if gp._defer != nil && gp._defer.pfn == 0 && gp._defer.frame == frame {
302 // This is the defer function that called recover.
303 // Simply return to stop the stack unwind, and let the
304 // Go code continue to execute.
305 d := gp._defer
306 gp._defer = d.link
307 freedefer(d)
309 // We are returning from this function.
310 *frame = true
312 return
315 // This is some other defer function. It was already run by
316 // the call to panic, or just above. Rethrow the exception.
317 rethrowException()
318 throw("rethrowException returned")
321 // unwindStack starts unwinding the stack for a panic. We unwind
322 // function calls until we reach the one which used a defer function
323 // which called recover. Each function which uses a defer statement
324 // will have an exception handler, as shown above for checkdefer.
325 func unwindStack() {
326 // Allocate the exception type used by the unwind ABI.
327 // It would be nice to define it in runtime_sysinfo.go,
328 // but current definitions don't work because the required
329 // alignment is larger than can be represented in Go.
330 // The type never contains any Go pointers.
331 size := unwindExceptionSize()
332 usize := uintptr(unsafe.Sizeof(uintptr(0)))
333 c := (size + usize - 1) / usize
334 s := make([]uintptr, c)
335 getg().exception = unsafe.Pointer(&s[0])
336 throwException()
339 // Goexit terminates the goroutine that calls it. No other goroutine is affected.
340 // Goexit runs all deferred calls before terminating the goroutine. Because Goexit
341 // is not a panic, any recover calls in those deferred functions will return nil.
343 // Calling Goexit from the main goroutine terminates that goroutine
344 // without func main returning. Since func main has not returned,
345 // the program continues execution of other goroutines.
346 // If all other goroutines exit, the program crashes.
347 func Goexit() {
348 // Run all deferred functions for the current goroutine.
349 // This code is similar to gopanic, see that implementation
350 // for detailed comments.
351 gp := getg()
352 for {
353 d := gp._defer
354 if d == nil {
355 break
358 pfn := d.pfn
359 if pfn == 0 {
360 if d._panic != nil {
361 d._panic.aborted = true
362 d._panic = nil
364 gp._defer = d.link
365 freedefer(d)
366 continue
368 d.pfn = 0
370 var fn func(unsafe.Pointer)
371 *(*uintptr)(unsafe.Pointer(&fn)) = uintptr(noescape(unsafe.Pointer(&pfn)))
372 fn(d.arg)
374 if gp._defer != d {
375 throw("bad defer entry in Goexit")
377 d._panic = nil
378 gp._defer = d.link
379 freedefer(d)
380 // Note: we ignore recovers here because Goexit isn't a panic
382 goexit1()
385 // Call all Error and String methods before freezing the world.
386 // Used when crashing with panicking.
387 // This must match types handled by printany.
388 func preprintpanics(p *_panic) {
389 defer func() {
390 if recover() != nil {
391 throw("panic while printing panic value")
394 for p != nil {
395 switch v := p.arg.(type) {
396 case error:
397 p.arg = v.Error()
398 case stringer:
399 p.arg = v.String()
401 p = p.link
405 // Print all currently active panics. Used when crashing.
406 // Should only be called after preprintpanics.
407 func printpanics(p *_panic) {
408 if p.link != nil {
409 printpanics(p.link)
410 print("\t")
412 print("panic: ")
413 // Because of preprintpanics, p.arg cannot be an error or
414 // stringer, so this won't call into user code.
415 printany(p.arg)
416 if p.recovered {
417 print(" [recovered]")
419 print("\n")
422 // The implementation of the predeclared function panic.
423 func gopanic(e interface{}) {
424 gp := getg()
425 if gp.m.curg != gp {
426 print("panic: ")
427 printany(e)
428 print("\n")
429 throw("panic on system stack")
432 if gp.m.mallocing != 0 {
433 print("panic: ")
434 printany(e)
435 print("\n")
436 throw("panic during malloc")
438 if gp.m.preemptoff != "" {
439 print("panic: ")
440 printany(e)
441 print("\n")
442 print("preempt off reason: ")
443 print(gp.m.preemptoff)
444 print("\n")
445 throw("panic during preemptoff")
447 if gp.m.locks != 0 {
448 print("panic: ")
449 printany(e)
450 print("\n")
451 throw("panic holding locks")
454 // The gc compiler allocates this new _panic struct on the
455 // stack. We can't do that, because when a deferred function
456 // recovers the panic we unwind the stack. We unlink this
457 // entry before unwinding the stack, but that doesn't help in
458 // the case where we panic, a deferred function recovers and
459 // then panics itself, that panic is in turn recovered, and
460 // unwinds the stack past this stack frame.
462 p := &_panic{
463 arg: e,
464 link: gp._panic,
466 gp._panic = p
468 atomic.Xadd(&runningPanicDefers, 1)
470 for {
471 d := gp._defer
472 if d == nil {
473 break
476 pfn := d.pfn
478 // If defer was started by earlier panic or Goexit (and, since we're back here, that triggered a new panic),
479 // take defer off list. The earlier panic or Goexit will not continue running.
480 if pfn == 0 {
481 if d._panic != nil {
482 d._panic.aborted = true
484 d._panic = nil
485 gp._defer = d.link
486 freedefer(d)
487 continue
489 d.pfn = 0
491 // Record the panic that is running the defer.
492 // If there is a new panic during the deferred call, that panic
493 // will find d in the list and will mark d._panic (this panic) aborted.
494 d._panic = p
496 var fn func(unsafe.Pointer)
497 *(*uintptr)(unsafe.Pointer(&fn)) = uintptr(noescape(unsafe.Pointer(&pfn)))
498 fn(d.arg)
500 if gp._defer != d {
501 throw("bad defer entry in panic")
503 d._panic = nil
505 if p.recovered {
506 atomic.Xadd(&runningPanicDefers, -1)
508 gp._panic = p.link
510 // Aborted panics are marked but remain on the g.panic list.
511 // Remove them from the list.
512 for gp._panic != nil && gp._panic.aborted {
513 gp._panic = gp._panic.link
515 if gp._panic == nil { // must be done with signal
516 gp.sig = 0
519 // Unwind the stack by throwing an exception.
520 // The compiler has arranged to create
521 // exception handlers in each function
522 // that uses a defer statement. These
523 // exception handlers will check whether
524 // the entry on the top of the defer stack
525 // is from the current function. If it is,
526 // we have unwound the stack far enough.
527 unwindStack()
529 throw("unwindStack returned")
532 // Because we executed that defer function by a panic,
533 // and it did not call recover, we know that we are
534 // not returning from the calling function--we are
535 // panicking through it.
536 *d.frame = false
538 // Deferred function did not panic. Remove d.
539 // In the p.recovered case, d will be removed by checkdefer.
540 gp._defer = d.link
542 freedefer(d)
545 // ran out of deferred calls - old-school panic now
546 // Because it is unsafe to call arbitrary user code after freezing
547 // the world, we call preprintpanics to invoke all necessary Error
548 // and String methods to prepare the panic strings before startpanic.
549 preprintpanics(gp._panic)
550 startpanic()
552 // startpanic set panicking, which will block main from exiting,
553 // so now OK to decrement runningPanicDefers.
554 atomic.Xadd(&runningPanicDefers, -1)
556 printpanics(gp._panic)
557 dopanic(0) // should not return
558 *(*int)(nil) = 0 // not reached
561 // currentDefer returns the top of the defer stack if it can be recovered.
562 // Otherwise it returns nil.
563 func currentDefer() *_defer {
564 gp := getg()
565 d := gp._defer
566 if d == nil {
567 return nil
570 // The panic that would be recovered is the one on the top of
571 // the panic stack. We do not want to recover it if that panic
572 // was on the top of the panic stack when this function was
573 // deferred.
574 if d.panicStack == gp._panic {
575 return nil
578 // The deferred thunk will call setdeferretaddr. If this has
579 // not happened, then we have not been called via defer, and
580 // we can not recover.
581 if d.retaddr == 0 {
582 return nil
585 return d
588 // canrecover is called by a thunk to see if the real function would
589 // be permitted to recover a panic value. Recovering a value is
590 // permitted if the thunk was called directly by defer. retaddr is the
591 // return address of the function that is calling canrecover--that is,
592 // the thunk.
593 func canrecover(retaddr uintptr) bool {
594 d := currentDefer()
595 if d == nil {
596 return false
599 ret := __builtin_extract_return_addr(retaddr)
600 dret := d.retaddr
601 if ret <= dret && ret+16 >= dret {
602 return true
605 // On some systems, in some cases, the return address does not
606 // work reliably. See http://gcc.gnu.org/PR60406. If we are
607 // permitted to call recover, the call stack will look like this:
608 // runtime.gopanic, runtime.deferreturn, etc.
609 // thunk to call deferred function (calls __go_set_defer_retaddr)
610 // function that calls __go_can_recover (passing return address)
611 // runtime.canrecover
612 // Calling callers will skip the thunks. So if our caller's
613 // caller starts with "runtime.", then we are permitted to
614 // call recover.
615 var locs [16]location
616 if callers(1, locs[:2]) < 2 {
617 return false
620 name := locs[1].function
621 if hasprefix(name, "runtime.") {
622 return true
625 // If the function calling recover was created by reflect.MakeFunc,
626 // then makefuncfficanrecover will have set makefunccanrecover.
627 if !d.makefunccanrecover {
628 return false
631 // We look up the stack, ignoring libffi functions and
632 // functions in the reflect package, until we find
633 // reflect.makeFuncStub or reflect.ffi_callback called by FFI
634 // functions. Then we check the caller of that function.
636 n := callers(2, locs[:])
637 foundFFICallback := false
638 i := 0
639 for ; i < n; i++ {
640 name = locs[i].function
641 if name == "" {
642 // No function name means this caller isn't Go code.
643 // Assume that this is libffi.
644 continue
647 // Ignore function in libffi.
648 if hasprefix(name, "ffi_") {
649 continue
652 if foundFFICallback {
653 break
656 if name == "reflect.ffi_callback" {
657 foundFFICallback = true
658 continue
661 // Ignore other functions in the reflect package.
662 if hasprefix(name, "reflect.") || hasprefix(name, ".1reflect.") {
663 continue
666 // We should now be looking at the real caller.
667 break
670 if i < n {
671 name = locs[i].function
672 if hasprefix(name, "runtime.") {
673 return true
677 return false
680 // This function is called when code is about to enter a function
681 // created by the libffi version of reflect.MakeFunc. This function is
682 // passed the names of the callers of the libffi code that called the
683 // stub. It uses them to decide whether it is permitted to call
684 // recover, and sets d.makefunccanrecover so that gorecover can make
685 // the same decision.
686 func makefuncfficanrecover(loc []location) {
687 d := currentDefer()
688 if d == nil {
689 return
692 // If we are already in a call stack of MakeFunc functions,
693 // there is nothing we can usefully check here.
694 if d.makefunccanrecover {
695 return
698 // loc starts with the caller of our caller. That will be a thunk.
699 // If its caller was a function function, then it was called
700 // directly by defer.
701 if len(loc) < 2 {
702 return
705 name := loc[1].function
706 if hasprefix(name, "runtime.") {
707 d.makefunccanrecover = true
711 // makefuncreturning is called when code is about to exit a function
712 // created by reflect.MakeFunc. It is called by the function stub used
713 // by reflect.MakeFunc. It clears the makefunccanrecover field. It's
714 // OK to always clear this field, because canrecover will only be
715 // called by a stub created for a function that calls recover. That
716 // stub will not call a function created by reflect.MakeFunc, so by
717 // the time we get here any caller higher up on the call stack no
718 // longer needs the information.
719 func makefuncreturning() {
720 d := getg()._defer
721 if d != nil {
722 d.makefunccanrecover = false
726 // The implementation of the predeclared function recover.
727 func gorecover() interface{} {
728 gp := getg()
729 p := gp._panic
730 if p != nil && !p.recovered {
731 p.recovered = true
732 return p.arg
734 return nil
737 // deferredrecover is called when a call to recover is deferred. That
738 // is, something like
739 // defer recover()
741 // We need to handle this specially. In gc, the recover function
742 // looks up the stack frame. In particular, that means that a deferred
743 // recover will not recover a panic thrown in the same function that
744 // defers the recover. It will only recover a panic thrown in a
745 // function that defers the deferred call to recover.
747 // In other words:
749 // func f1() {
750 // defer recover() // does not stop panic
751 // panic(0)
752 // }
754 // func f2() {
755 // defer func() {
756 // defer recover() // stops panic(0)
757 // }()
758 // panic(0)
759 // }
761 // func f3() {
762 // defer func() {
763 // defer recover() // does not stop panic
764 // panic(0)
765 // }()
766 // panic(1)
767 // }
769 // func f4() {
770 // defer func() {
771 // defer func() {
772 // defer recover() // stops panic(0)
773 // }()
774 // panic(0)
775 // }()
776 // panic(1)
777 // }
779 // The interesting case here is f3. As can be seen from f2, the
780 // deferred recover could pick up panic(1). However, this does not
781 // happen because it is blocked by the panic(0).
783 // When a function calls recover, then when we invoke it we pass a
784 // hidden parameter indicating whether it should recover something.
785 // This parameter is set based on whether the function is being
786 // invoked directly from defer. The parameter winds up determining
787 // whether __go_recover or __go_deferred_recover is called at all.
789 // In the case of a deferred recover, the hidden parameter that
790 // controls the call is actually the one set up for the function that
791 // runs the defer recover() statement. That is the right thing in all
792 // the cases above except for f3. In f3 the function is permitted to
793 // call recover, but the deferred recover call is not. We address that
794 // here by checking for that specific case before calling recover. If
795 // this function was deferred when there is already a panic on the
796 // panic stack, then we can only recover that panic, not any other.
798 // Note that we can get away with using a special function here
799 // because you are not permitted to take the address of a predeclared
800 // function like recover.
801 func deferredrecover() interface{} {
802 gp := getg()
803 if gp._defer == nil || gp._defer.panicStack != gp._panic {
804 return nil
806 return gorecover()
809 //go:linkname sync_throw sync.throw
810 func sync_throw(s string) {
811 throw(s)
814 //go:nosplit
815 func throw(s string) {
816 print("fatal error: ", s, "\n")
817 gp := getg()
818 if gp.m.throwing == 0 {
819 gp.m.throwing = 1
821 startpanic()
822 dopanic(0)
823 *(*int)(nil) = 0 // not reached
826 // runningPanicDefers is non-zero while running deferred functions for panic.
827 // runningPanicDefers is incremented and decremented atomically.
828 // This is used to try hard to get a panic stack trace out when exiting.
829 var runningPanicDefers uint32
831 // panicking is non-zero when crashing the program for an unrecovered panic.
832 // panicking is incremented and decremented atomically.
833 var panicking uint32
835 // paniclk is held while printing the panic information and stack trace,
836 // so that two concurrent panics don't overlap their output.
837 var paniclk mutex
839 // startpanic_m prepares for an unrecoverable panic.
841 // It can have write barriers because the write barrier explicitly
842 // ignores writes once dying > 0.
844 //go:yeswritebarrierrec
845 func startpanic() {
846 _g_ := getg()
847 if mheap_.cachealloc.size == 0 { // very early
848 print("runtime: panic before malloc heap initialized\n")
850 // Disallow malloc during an unrecoverable panic. A panic
851 // could happen in a signal handler, or in a throw, or inside
852 // malloc itself. We want to catch if an allocation ever does
853 // happen (even if we're not in one of these situations).
854 _g_.m.mallocing++
856 switch _g_.m.dying {
857 case 0:
858 _g_.m.dying = 1
859 _g_.writebuf = nil
860 atomic.Xadd(&panicking, 1)
861 lock(&paniclk)
862 if debug.schedtrace > 0 || debug.scheddetail > 0 {
863 schedtrace(true)
865 freezetheworld()
866 return
867 case 1:
868 // Something failed while panicking, probably the print of the
869 // argument to panic(). Just print a stack trace and exit.
870 _g_.m.dying = 2
871 print("panic during panic\n")
872 dopanic(0)
873 exit(3)
874 fallthrough
875 case 2:
876 // This is a genuine bug in the runtime, we couldn't even
877 // print the stack trace successfully.
878 _g_.m.dying = 3
879 print("stack trace unavailable\n")
880 exit(4)
881 fallthrough
882 default:
883 // Can't even print! Just exit.
884 exit(5)
888 var didothers bool
889 var deadlock mutex
891 func dopanic(unused int) {
892 gp := getg()
893 if gp.sig != 0 {
894 signame := signame(gp.sig)
895 if signame != "" {
896 print("[signal ", signame)
897 } else {
898 print("[signal ", hex(gp.sig))
900 print(" code=", hex(gp.sigcode0), " addr=", hex(gp.sigcode1), " pc=", hex(gp.sigpc), "]\n")
903 level, all, docrash := gotraceback()
904 _g_ := getg()
905 if level > 0 {
906 if gp != gp.m.curg {
907 all = true
909 if gp != gp.m.g0 {
910 print("\n")
911 goroutineheader(gp)
912 traceback(0)
913 } else if level >= 2 || _g_.m.throwing > 0 {
914 print("\nruntime stack:\n")
915 traceback(0)
917 if !didothers && all {
918 didothers = true
919 tracebackothers(gp)
922 unlock(&paniclk)
924 if atomic.Xadd(&panicking, -1) != 0 {
925 // Some other m is panicking too.
926 // Let it print what it needs to print.
927 // Wait forever without chewing up cpu.
928 // It will exit when it's done.
929 lock(&deadlock)
930 lock(&deadlock)
933 if docrash {
934 crash()
937 exit(2)
940 // canpanic returns false if a signal should throw instead of
941 // panicking.
943 //go:nosplit
944 func canpanic(gp *g) bool {
945 // Note that g is m->gsignal, different from gp.
946 // Note also that g->m can change at preemption, so m can go stale
947 // if this function ever makes a function call.
948 _g_ := getg()
949 _m_ := _g_.m
951 // Is it okay for gp to panic instead of crashing the program?
952 // Yes, as long as it is running Go code, not runtime code,
953 // and not stuck in a system call.
954 if gp == nil || gp != _m_.curg {
955 return false
957 if _m_.locks-_m_.softfloat != 0 || _m_.mallocing != 0 || _m_.throwing != 0 || _m_.preemptoff != "" || _m_.dying != 0 {
958 return false
960 status := readgstatus(gp)
961 if status&^_Gscan != _Grunning || gp.syscallsp != 0 {
962 return false
964 return true