Source file src/runtime/panic.go

Documentation: runtime

     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.
     4  
     5  package runtime
     6  
     7  import (
     8  	"runtime/internal/atomic"
     9  	"runtime/internal/sys"
    10  	"unsafe"
    11  )
    12  
    13  // We have two different ways of doing defers. The older way involves creating a
    14  // defer record at the time that a defer statement is executing and adding it to a
    15  // defer chain. This chain is inspected by the deferreturn call at all function
    16  // exits in order to run the appropriate defer calls. A cheaper way (which we call
    17  // open-coded defers) is used for functions in which no defer statements occur in
    18  // loops. In that case, we simply store the defer function/arg information into
    19  // specific stack slots at the point of each defer statement, as well as setting a
    20  // bit in a bitmask. At each function exit, we add inline code to directly make
    21  // the appropriate defer calls based on the bitmask and fn/arg information stored
    22  // on the stack. During panic/Goexit processing, the appropriate defer calls are
    23  // made using extra funcdata info that indicates the exact stack slots that
    24  // contain the bitmask and defer fn/args.
    25  
    26  // Check to make sure we can really generate a panic. If the panic
    27  // was generated from the runtime, or from inside malloc, then convert
    28  // to a throw of msg.
    29  // pc should be the program counter of the compiler-generated code that
    30  // triggered this panic.
    31  func panicCheck1(pc uintptr, msg string) {
    32  	if sys.GoarchWasm == 0 && hasPrefix(funcname(findfunc(pc)), "runtime.") {
    33  		// Note: wasm can't tail call, so we can't get the original caller's pc.
    34  		throw(msg)
    35  	}
    36  	// TODO: is this redundant? How could we be in malloc
    37  	// but not in the runtime? runtime/internal/*, maybe?
    38  	gp := getg()
    39  	if gp != nil && gp.m != nil && gp.m.mallocing != 0 {
    40  		throw(msg)
    41  	}
    42  }
    43  
    44  // Same as above, but calling from the runtime is allowed.
    45  //
    46  // Using this function is necessary for any panic that may be
    47  // generated by runtime.sigpanic, since those are always called by the
    48  // runtime.
    49  func panicCheck2(err string) {
    50  	// panic allocates, so to avoid recursive malloc, turn panics
    51  	// during malloc into throws.
    52  	gp := getg()
    53  	if gp != nil && gp.m != nil && gp.m.mallocing != 0 {
    54  		throw(err)
    55  	}
    56  }
    57  
    58  // Many of the following panic entry-points turn into throws when they
    59  // happen in various runtime contexts. These should never happen in
    60  // the runtime, and if they do, they indicate a serious issue and
    61  // should not be caught by user code.
    62  //
    63  // The panic{Index,Slice,divide,shift} functions are called by
    64  // code generated by the compiler for out of bounds index expressions,
    65  // out of bounds slice expressions, division by zero, and shift by negative.
    66  // The panicdivide (again), panicoverflow, panicfloat, and panicmem
    67  // functions are called by the signal handler when a signal occurs
    68  // indicating the respective problem.
    69  //
    70  // Since panic{Index,Slice,shift} are never called directly, and
    71  // since the runtime package should never have an out of bounds slice
    72  // or array reference or negative shift, if we see those functions called from the
    73  // runtime package we turn the panic into a throw. That will dump the
    74  // entire runtime stack for easier debugging.
    75  //
    76  // The entry points called by the signal handler will be called from
    77  // runtime.sigpanic, so we can't disallow calls from the runtime to
    78  // these (they always look like they're called from the runtime).
    79  // Hence, for these, we just check for clearly bad runtime conditions.
    80  //
    81  // The panic{Index,Slice} functions are implemented in assembly and tail call
    82  // to the goPanic{Index,Slice} functions below. This is done so we can use
    83  // a space-minimal register calling convention.
    84  
    85  // failures in the comparisons for s[x], 0 <= x < y (y == len(s))
    86  func goPanicIndex(x int, y int) {
    87  	panicCheck1(getcallerpc(), "index out of range")
    88  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsIndex})
    89  }
    90  func goPanicIndexU(x uint, y int) {
    91  	panicCheck1(getcallerpc(), "index out of range")
    92  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsIndex})
    93  }
    94  
    95  // failures in the comparisons for s[:x], 0 <= x <= y (y == len(s) or cap(s))
    96  func goPanicSliceAlen(x int, y int) {
    97  	panicCheck1(getcallerpc(), "slice bounds out of range")
    98  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsSliceAlen})
    99  }
   100  func goPanicSliceAlenU(x uint, y int) {
   101  	panicCheck1(getcallerpc(), "slice bounds out of range")
   102  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsSliceAlen})
   103  }
   104  func goPanicSliceAcap(x int, y int) {
   105  	panicCheck1(getcallerpc(), "slice bounds out of range")
   106  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsSliceAcap})
   107  }
   108  func goPanicSliceAcapU(x uint, y int) {
   109  	panicCheck1(getcallerpc(), "slice bounds out of range")
   110  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsSliceAcap})
   111  }
   112  
   113  // failures in the comparisons for s[x:y], 0 <= x <= y
   114  func goPanicSliceB(x int, y int) {
   115  	panicCheck1(getcallerpc(), "slice bounds out of range")
   116  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsSliceB})
   117  }
   118  func goPanicSliceBU(x uint, y int) {
   119  	panicCheck1(getcallerpc(), "slice bounds out of range")
   120  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsSliceB})
   121  }
   122  
   123  // failures in the comparisons for s[::x], 0 <= x <= y (y == len(s) or cap(s))
   124  func goPanicSlice3Alen(x int, y int) {
   125  	panicCheck1(getcallerpc(), "slice bounds out of range")
   126  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsSlice3Alen})
   127  }
   128  func goPanicSlice3AlenU(x uint, y int) {
   129  	panicCheck1(getcallerpc(), "slice bounds out of range")
   130  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsSlice3Alen})
   131  }
   132  func goPanicSlice3Acap(x int, y int) {
   133  	panicCheck1(getcallerpc(), "slice bounds out of range")
   134  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsSlice3Acap})
   135  }
   136  func goPanicSlice3AcapU(x uint, y int) {
   137  	panicCheck1(getcallerpc(), "slice bounds out of range")
   138  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsSlice3Acap})
   139  }
   140  
   141  // failures in the comparisons for s[:x:y], 0 <= x <= y
   142  func goPanicSlice3B(x int, y int) {
   143  	panicCheck1(getcallerpc(), "slice bounds out of range")
   144  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsSlice3B})
   145  }
   146  func goPanicSlice3BU(x uint, y int) {
   147  	panicCheck1(getcallerpc(), "slice bounds out of range")
   148  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsSlice3B})
   149  }
   150  
   151  // failures in the comparisons for s[x:y:], 0 <= x <= y
   152  func goPanicSlice3C(x int, y int) {
   153  	panicCheck1(getcallerpc(), "slice bounds out of range")
   154  	panic(boundsError{x: int64(x), signed: true, y: y, code: boundsSlice3C})
   155  }
   156  func goPanicSlice3CU(x uint, y int) {
   157  	panicCheck1(getcallerpc(), "slice bounds out of range")
   158  	panic(boundsError{x: int64(x), signed: false, y: y, code: boundsSlice3C})
   159  }
   160  
   161  // Implemented in assembly, as they take arguments in registers.
   162  // Declared here to mark them as ABIInternal.
   163  func panicIndex(x int, y int)
   164  func panicIndexU(x uint, y int)
   165  func panicSliceAlen(x int, y int)
   166  func panicSliceAlenU(x uint, y int)
   167  func panicSliceAcap(x int, y int)
   168  func panicSliceAcapU(x uint, y int)
   169  func panicSliceB(x int, y int)
   170  func panicSliceBU(x uint, y int)
   171  func panicSlice3Alen(x int, y int)
   172  func panicSlice3AlenU(x uint, y int)
   173  func panicSlice3Acap(x int, y int)
   174  func panicSlice3AcapU(x uint, y int)
   175  func panicSlice3B(x int, y int)
   176  func panicSlice3BU(x uint, y int)
   177  func panicSlice3C(x int, y int)
   178  func panicSlice3CU(x uint, y int)
   179  
   180  var shiftError = error(errorString("negative shift amount"))
   181  
   182  func panicshift() {
   183  	panicCheck1(getcallerpc(), "negative shift amount")
   184  	panic(shiftError)
   185  }
   186  
   187  var divideError = error(errorString("integer divide by zero"))
   188  
   189  func panicdivide() {
   190  	panicCheck2("integer divide by zero")
   191  	panic(divideError)
   192  }
   193  
   194  var overflowError = error(errorString("integer overflow"))
   195  
   196  func panicoverflow() {
   197  	panicCheck2("integer overflow")
   198  	panic(overflowError)
   199  }
   200  
   201  var floatError = error(errorString("floating point error"))
   202  
   203  func panicfloat() {
   204  	panicCheck2("floating point error")
   205  	panic(floatError)
   206  }
   207  
   208  var memoryError = error(errorString("invalid memory address or nil pointer dereference"))
   209  
   210  func panicmem() {
   211  	panicCheck2("invalid memory address or nil pointer dereference")
   212  	panic(memoryError)
   213  }
   214  
   215  // Create a new deferred function fn with siz bytes of arguments.
   216  // The compiler turns a defer statement into a call to this.
   217  //go:nosplit
   218  func deferproc(siz int32, fn *funcval) { // arguments of fn follow fn
   219  	if getg().m.curg != getg() {
   220  		// go code on the system stack can't defer
   221  		throw("defer on system stack")
   222  	}
   223  
   224  	// the arguments of fn are in a perilous state. The stack map
   225  	// for deferproc does not describe them. So we can't let garbage
   226  	// collection or stack copying trigger until we've copied them out
   227  	// to somewhere safe. The memmove below does that.
   228  	// Until the copy completes, we can only call nosplit routines.
   229  	sp := getcallersp()
   230  	argp := uintptr(unsafe.Pointer(&fn)) + unsafe.Sizeof(fn)
   231  	callerpc := getcallerpc()
   232  
   233  	d := newdefer(siz)
   234  	if d._panic != nil {
   235  		throw("deferproc: d.panic != nil after newdefer")
   236  	}
   237  	d.fn = fn
   238  	d.pc = callerpc
   239  	d.sp = sp
   240  	switch siz {
   241  	case 0:
   242  		// Do nothing.
   243  	case sys.PtrSize:
   244  		*(*uintptr)(deferArgs(d)) = *(*uintptr)(unsafe.Pointer(argp))
   245  	default:
   246  		memmove(deferArgs(d), unsafe.Pointer(argp), uintptr(siz))
   247  	}
   248  
   249  	// deferproc returns 0 normally.
   250  	// a deferred func that stops a panic
   251  	// makes the deferproc return 1.
   252  	// the code the compiler generates always
   253  	// checks the return value and jumps to the
   254  	// end of the function if deferproc returns != 0.
   255  	return0()
   256  	// No code can go here - the C return register has
   257  	// been set and must not be clobbered.
   258  }
   259  
   260  // deferprocStack queues a new deferred function with a defer record on the stack.
   261  // The defer record must have its siz and fn fields initialized.
   262  // All other fields can contain junk.
   263  // The defer record must be immediately followed in memory by
   264  // the arguments of the defer.
   265  // Nosplit because the arguments on the stack won't be scanned
   266  // until the defer record is spliced into the gp._defer list.
   267  //go:nosplit
   268  func deferprocStack(d *_defer) {
   269  	gp := getg()
   270  	if gp.m.curg != gp {
   271  		// go code on the system stack can't defer
   272  		throw("defer on system stack")
   273  	}
   274  	// siz and fn are already set.
   275  	// The other fields are junk on entry to deferprocStack and
   276  	// are initialized here.
   277  	d.started = false
   278  	d.heap = false
   279  	d.openDefer = false
   280  	d.sp = getcallersp()
   281  	d.pc = getcallerpc()
   282  	d.framepc = 0
   283  	d.varp = 0
   284  	// The lines below implement:
   285  	//   d.panic = nil
   286  	//   d.fd = nil
   287  	//   d.link = gp._defer
   288  	//   gp._defer = d
   289  	// But without write barriers. The first three are writes to
   290  	// the stack so they don't need a write barrier, and furthermore
   291  	// are to uninitialized memory, so they must not use a write barrier.
   292  	// The fourth write does not require a write barrier because we
   293  	// explicitly mark all the defer structures, so we don't need to
   294  	// keep track of pointers to them with a write barrier.
   295  	*(*uintptr)(unsafe.Pointer(&d._panic)) = 0
   296  	*(*uintptr)(unsafe.Pointer(&d.fd)) = 0
   297  	*(*uintptr)(unsafe.Pointer(&d.link)) = uintptr(unsafe.Pointer(gp._defer))
   298  	*(*uintptr)(unsafe.Pointer(&gp._defer)) = uintptr(unsafe.Pointer(d))
   299  
   300  	return0()
   301  	// No code can go here - the C return register has
   302  	// been set and must not be clobbered.
   303  }
   304  
   305  // Small malloc size classes >= 16 are the multiples of 16: 16, 32, 48, 64, 80, 96, 112, 128, 144, ...
   306  // Each P holds a pool for defers with small arg sizes.
   307  // Assign defer allocations to pools by rounding to 16, to match malloc size classes.
   308  
   309  const (
   310  	deferHeaderSize = unsafe.Sizeof(_defer{})
   311  	minDeferAlloc   = (deferHeaderSize + 15) &^ 15
   312  	minDeferArgs    = minDeferAlloc - deferHeaderSize
   313  )
   314  
   315  // defer size class for arg size sz
   316  //go:nosplit
   317  func deferclass(siz uintptr) uintptr {
   318  	if siz <= minDeferArgs {
   319  		return 0
   320  	}
   321  	return (siz - minDeferArgs + 15) / 16
   322  }
   323  
   324  // total size of memory block for defer with arg size sz
   325  func totaldefersize(siz uintptr) uintptr {
   326  	if siz <= minDeferArgs {
   327  		return minDeferAlloc
   328  	}
   329  	return deferHeaderSize + siz
   330  }
   331  
   332  // Ensure that defer arg sizes that map to the same defer size class
   333  // also map to the same malloc size class.
   334  func testdefersizes() {
   335  	var m [len(p{}.deferpool)]int32
   336  
   337  	for i := range m {
   338  		m[i] = -1
   339  	}
   340  	for i := uintptr(0); ; i++ {
   341  		defersc := deferclass(i)
   342  		if defersc >= uintptr(len(m)) {
   343  			break
   344  		}
   345  		siz := roundupsize(totaldefersize(i))
   346  		if m[defersc] < 0 {
   347  			m[defersc] = int32(siz)
   348  			continue
   349  		}
   350  		if m[defersc] != int32(siz) {
   351  			print("bad defer size class: i=", i, " siz=", siz, " defersc=", defersc, "\n")
   352  			throw("bad defer size class")
   353  		}
   354  	}
   355  }
   356  
   357  // The arguments associated with a deferred call are stored
   358  // immediately after the _defer header in memory.
   359  //go:nosplit
   360  func deferArgs(d *_defer) unsafe.Pointer {
   361  	if d.siz == 0 {
   362  		// Avoid pointer past the defer allocation.
   363  		return nil
   364  	}
   365  	return add(unsafe.Pointer(d), unsafe.Sizeof(*d))
   366  }
   367  
   368  var deferType *_type // type of _defer struct
   369  
   370  func init() {
   371  	var x interface{}
   372  	x = (*_defer)(nil)
   373  	deferType = (*(**ptrtype)(unsafe.Pointer(&x))).elem
   374  }
   375  
   376  // Allocate a Defer, usually using per-P pool.
   377  // Each defer must be released with freedefer.
   378  //
   379  // This must not grow the stack because there may be a frame without
   380  // stack map information when this is called.
   381  //
   382  //go:nosplit
   383  func newdefer(siz int32) *_defer {
   384  	var d *_defer
   385  	sc := deferclass(uintptr(siz))
   386  	gp := getg()
   387  	if sc < uintptr(len(p{}.deferpool)) {
   388  		pp := gp.m.p.ptr()
   389  		if len(pp.deferpool[sc]) == 0 && sched.deferpool[sc] != nil {
   390  			// Take the slow path on the system stack so
   391  			// we don't grow newdefer's stack.
   392  			systemstack(func() {
   393  				lock(&sched.deferlock)
   394  				for len(pp.deferpool[sc]) < cap(pp.deferpool[sc])/2 && sched.deferpool[sc] != nil {
   395  					d := sched.deferpool[sc]
   396  					sched.deferpool[sc] = d.link
   397  					d.link = nil
   398  					pp.deferpool[sc] = append(pp.deferpool[sc], d)
   399  				}
   400  				unlock(&sched.deferlock)
   401  			})
   402  		}
   403  		if n := len(pp.deferpool[sc]); n > 0 {
   404  			d = pp.deferpool[sc][n-1]
   405  			pp.deferpool[sc][n-1] = nil
   406  			pp.deferpool[sc] = pp.deferpool[sc][:n-1]
   407  		}
   408  	}
   409  	if d == nil {
   410  		// Allocate new defer+args.
   411  		systemstack(func() {
   412  			total := roundupsize(totaldefersize(uintptr(siz)))
   413  			d = (*_defer)(mallocgc(total, deferType, true))
   414  		})
   415  		if debugCachedWork {
   416  			// Duplicate the tail below so if there's a
   417  			// crash in checkPut we can tell if d was just
   418  			// allocated or came from the pool.
   419  			d.siz = siz
   420  			d.link = gp._defer
   421  			gp._defer = d
   422  			return d
   423  		}
   424  	}
   425  	d.siz = siz
   426  	d.heap = true
   427  	d.link = gp._defer
   428  	gp._defer = d
   429  	return d
   430  }
   431  
   432  // Free the given defer.
   433  // The defer cannot be used after this call.
   434  //
   435  // This must not grow the stack because there may be a frame without a
   436  // stack map when this is called.
   437  //
   438  //go:nosplit
   439  func freedefer(d *_defer) {
   440  	if d._panic != nil {
   441  		freedeferpanic()
   442  	}
   443  	if d.fn != nil {
   444  		freedeferfn()
   445  	}
   446  	if !d.heap {
   447  		return
   448  	}
   449  	sc := deferclass(uintptr(d.siz))
   450  	if sc >= uintptr(len(p{}.deferpool)) {
   451  		return
   452  	}
   453  	pp := getg().m.p.ptr()
   454  	if len(pp.deferpool[sc]) == cap(pp.deferpool[sc]) {
   455  		// Transfer half of local cache to the central cache.
   456  		//
   457  		// Take this slow path on the system stack so
   458  		// we don't grow freedefer's stack.
   459  		systemstack(func() {
   460  			var first, last *_defer
   461  			for len(pp.deferpool[sc]) > cap(pp.deferpool[sc])/2 {
   462  				n := len(pp.deferpool[sc])
   463  				d := pp.deferpool[sc][n-1]
   464  				pp.deferpool[sc][n-1] = nil
   465  				pp.deferpool[sc] = pp.deferpool[sc][:n-1]
   466  				if first == nil {
   467  					first = d
   468  				} else {
   469  					last.link = d
   470  				}
   471  				last = d
   472  			}
   473  			lock(&sched.deferlock)
   474  			last.link = sched.deferpool[sc]
   475  			sched.deferpool[sc] = first
   476  			unlock(&sched.deferlock)
   477  		})
   478  	}
   479  
   480  	// These lines used to be simply `*d = _defer{}` but that
   481  	// started causing a nosplit stack overflow via typedmemmove.
   482  	d.siz = 0
   483  	d.started = false
   484  	d.openDefer = false
   485  	d.sp = 0
   486  	d.pc = 0
   487  	d.framepc = 0
   488  	d.varp = 0
   489  	d.fd = nil
   490  	// d._panic and d.fn must be nil already.
   491  	// If not, we would have called freedeferpanic or freedeferfn above,
   492  	// both of which throw.
   493  	d.link = nil
   494  
   495  	pp.deferpool[sc] = append(pp.deferpool[sc], d)
   496  }
   497  
   498  // Separate function so that it can split stack.
   499  // Windows otherwise runs out of stack space.
   500  func freedeferpanic() {
   501  	// _panic must be cleared before d is unlinked from gp.
   502  	throw("freedefer with d._panic != nil")
   503  }
   504  
   505  func freedeferfn() {
   506  	// fn must be cleared before d is unlinked from gp.
   507  	throw("freedefer with d.fn != nil")
   508  }
   509  
   510  // Run a deferred function if there is one.
   511  // The compiler inserts a call to this at the end of any
   512  // function which calls defer.
   513  // If there is a deferred function, this will call runtime¬∑jmpdefer,
   514  // which will jump to the deferred function such that it appears
   515  // to have been called by the caller of deferreturn at the point
   516  // just before deferreturn was called. The effect is that deferreturn
   517  // is called again and again until there are no more deferred functions.
   518  //
   519  // Declared as nosplit, because the function should not be preempted once we start
   520  // modifying the caller's frame in order to reuse the frame to call the deferred
   521  // function.
   522  //
   523  // The single argument isn't actually used - it just has its address
   524  // taken so it can be matched against pending defers.
   525  //go:nosplit
   526  func deferreturn(arg0 uintptr) {
   527  	gp := getg()
   528  	d := gp._defer
   529  	if d == nil {
   530  		return
   531  	}
   532  	sp := getcallersp()
   533  	if d.sp != sp {
   534  		return
   535  	}
   536  	if d.openDefer {
   537  		done := runOpenDeferFrame(gp, d)
   538  		if !done {
   539  			throw("unfinished open-coded defers in deferreturn")
   540  		}
   541  		gp._defer = d.link
   542  		freedefer(d)
   543  		return
   544  	}
   545  
   546  	// Moving arguments around.
   547  	//
   548  	// Everything called after this point must be recursively
   549  	// nosplit because the garbage collector won't know the form
   550  	// of the arguments until the jmpdefer can flip the PC over to
   551  	// fn.
   552  	switch d.siz {
   553  	case 0:
   554  		// Do nothing.
   555  	case sys.PtrSize:
   556  		*(*uintptr)(unsafe.Pointer(&arg0)) = *(*uintptr)(deferArgs(d))
   557  	default:
   558  		memmove(unsafe.Pointer(&arg0), deferArgs(d), uintptr(d.siz))
   559  	}
   560  	fn := d.fn
   561  	d.fn = nil
   562  	gp._defer = d.link
   563  	freedefer(d)
   564  	// If the defer function pointer is nil, force the seg fault to happen
   565  	// here rather than in jmpdefer. gentraceback() throws an error if it is
   566  	// called with a callback on an LR architecture and jmpdefer is on the
   567  	// stack, because the stack trace can be incorrect in that case - see
   568  	// issue #8153).
   569  	_ = fn.fn
   570  	jmpdefer(fn, uintptr(unsafe.Pointer(&arg0)))
   571  }
   572  
   573  // Goexit terminates the goroutine that calls it. No other goroutine is affected.
   574  // Goexit runs all deferred calls before terminating the goroutine. Because Goexit
   575  // is not a panic, any recover calls in those deferred functions will return nil.
   576  //
   577  // Calling Goexit from the main goroutine terminates that goroutine
   578  // without func main returning. Since func main has not returned,
   579  // the program continues execution of other goroutines.
   580  // If all other goroutines exit, the program crashes.
   581  func Goexit() {
   582  	// Run all deferred functions for the current goroutine.
   583  	// This code is similar to gopanic, see that implementation
   584  	// for detailed comments.
   585  	gp := getg()
   586  
   587  	// Create a panic object for Goexit, so we can recognize when it might be
   588  	// bypassed by a recover().
   589  	var p _panic
   590  	p.goexit = true
   591  	p.link = gp._panic
   592  	gp._panic = (*_panic)(noescape(unsafe.Pointer(&p)))
   593  
   594  	addOneOpenDeferFrame(gp, getcallerpc(), unsafe.Pointer(getcallersp()))
   595  	for {
   596  		d := gp._defer
   597  		if d == nil {
   598  			break
   599  		}
   600  		if d.started {
   601  			if d._panic != nil {
   602  				d._panic.aborted = true
   603  				d._panic = nil
   604  			}
   605  			if !d.openDefer {
   606  				d.fn = nil
   607  				gp._defer = d.link
   608  				freedefer(d)
   609  				continue
   610  			}
   611  		}
   612  		d.started = true
   613  		d._panic = (*_panic)(noescape(unsafe.Pointer(&p)))
   614  		if d.openDefer {
   615  			done := runOpenDeferFrame(gp, d)
   616  			if !done {
   617  				// We should always run all defers in the frame,
   618  				// since there is no panic associated with this
   619  				// defer that can be recovered.
   620  				throw("unfinished open-coded defers in Goexit")
   621  			}
   622  			if p.aborted {
   623  				// Since our current defer caused a panic and may
   624  				// have been already freed, just restart scanning
   625  				// for open-coded defers from this frame again.
   626  				addOneOpenDeferFrame(gp, getcallerpc(), unsafe.Pointer(getcallersp()))
   627  			} else {
   628  				addOneOpenDeferFrame(gp, 0, nil)
   629  			}
   630  		} else {
   631  
   632  			// Save the pc/sp in reflectcallSave(), so we can "recover" back to this
   633  			// loop if necessary.
   634  			reflectcallSave(&p, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz))
   635  		}
   636  		if p.aborted {
   637  			// We had a recursive panic in the defer d we started, and
   638  			// then did a recover in a defer that was further down the
   639  			// defer chain than d. In the case of an outstanding Goexit,
   640  			// we force the recover to return back to this loop. d will
   641  			// have already been freed if completed, so just continue
   642  			// immediately to the next defer on the chain.
   643  			p.aborted = false
   644  			continue
   645  		}
   646  		if gp._defer != d {
   647  			throw("bad defer entry in Goexit")
   648  		}
   649  		d._panic = nil
   650  		d.fn = nil
   651  		gp._defer = d.link
   652  		freedefer(d)
   653  		// Note: we ignore recovers here because Goexit isn't a panic
   654  	}
   655  	goexit1()
   656  }
   657  
   658  // Call all Error and String methods before freezing the world.
   659  // Used when crashing with panicking.
   660  func preprintpanics(p *_panic) {
   661  	defer func() {
   662  		if recover() != nil {
   663  			throw("panic while printing panic value")
   664  		}
   665  	}()
   666  	for p != nil {
   667  		switch v := p.arg.(type) {
   668  		case error:
   669  			p.arg = v.Error()
   670  		case stringer:
   671  			p.arg = v.String()
   672  		}
   673  		p = p.link
   674  	}
   675  }
   676  
   677  // Print all currently active panics. Used when crashing.
   678  // Should only be called after preprintpanics.
   679  func printpanics(p *_panic) {
   680  	if p.link != nil {
   681  		printpanics(p.link)
   682  		if !p.link.goexit {
   683  			print("\t")
   684  		}
   685  	}
   686  	if p.goexit {
   687  		return
   688  	}
   689  	print("panic: ")
   690  	printany(p.arg)
   691  	if p.recovered {
   692  		print(" [recovered]")
   693  	}
   694  	print("\n")
   695  }
   696  
   697  // addOneOpenDeferFrame scans the stack for the first frame (if any) with
   698  // open-coded defers and if it finds one, adds a single record to the defer chain
   699  // for that frame. If sp is non-nil, it starts the stack scan from the frame
   700  // specified by sp. If sp is nil, it uses the sp from the current defer record
   701  // (which has just been finished). Hence, it continues the stack scan from the
   702  // frame of the defer that just finished. It skips any frame that already has an
   703  // open-coded _defer record, which would have been been created from a previous
   704  // (unrecovered) panic.
   705  //
   706  // Note: All entries of the defer chain (including this new open-coded entry) have
   707  // their pointers (including sp) adjusted properly if the stack moves while
   708  // running deferred functions. Also, it is safe to pass in the sp arg (which is
   709  // the direct result of calling getcallersp()), because all pointer variables
   710  // (including arguments) are adjusted as needed during stack copies.
   711  func addOneOpenDeferFrame(gp *g, pc uintptr, sp unsafe.Pointer) {
   712  	var prevDefer *_defer
   713  	if sp == nil {
   714  		prevDefer = gp._defer
   715  		pc = prevDefer.framepc
   716  		sp = unsafe.Pointer(prevDefer.sp)
   717  	}
   718  	systemstack(func() {
   719  		gentraceback(pc, uintptr(sp), 0, gp, 0, nil, 0x7fffffff,
   720  			func(frame *stkframe, unused unsafe.Pointer) bool {
   721  				if prevDefer != nil && prevDefer.sp == frame.sp {
   722  					// Skip the frame for the previous defer that
   723  					// we just finished (and was used to set
   724  					// where we restarted the stack scan)
   725  					return true
   726  				}
   727  				f := frame.fn
   728  				fd := funcdata(f, _FUNCDATA_OpenCodedDeferInfo)
   729  				if fd == nil {
   730  					return true
   731  				}
   732  				// Insert the open defer record in the
   733  				// chain, in order sorted by sp.
   734  				d := gp._defer
   735  				var prev *_defer
   736  				for d != nil {
   737  					dsp := d.sp
   738  					if frame.sp < dsp {
   739  						break
   740  					}
   741  					if frame.sp == dsp {
   742  						if !d.openDefer {
   743  							throw("duplicated defer entry")
   744  						}
   745  						return true
   746  					}
   747  					prev = d
   748  					d = d.link
   749  				}
   750  				if frame.fn.deferreturn == 0 {
   751  					throw("missing deferreturn")
   752  				}
   753  
   754  				maxargsize, _ := readvarintUnsafe(fd)
   755  				d1 := newdefer(int32(maxargsize))
   756  				d1.openDefer = true
   757  				d1._panic = nil
   758  				// These are the pc/sp to set after we've
   759  				// run a defer in this frame that did a
   760  				// recover. We return to a special
   761  				// deferreturn that runs any remaining
   762  				// defers and then returns from the
   763  				// function.
   764  				d1.pc = frame.fn.entry + uintptr(frame.fn.deferreturn)
   765  				d1.varp = frame.varp
   766  				d1.fd = fd
   767  				// Save the SP/PC associated with current frame,
   768  				// so we can continue stack trace later if needed.
   769  				d1.framepc = frame.pc
   770  				d1.sp = frame.sp
   771  				d1.link = d
   772  				if prev == nil {
   773  					gp._defer = d1
   774  				} else {
   775  					prev.link = d1
   776  				}
   777  				// Stop stack scanning after adding one open defer record
   778  				return false
   779  			},
   780  			nil, 0)
   781  	})
   782  }
   783  
   784  // readvarintUnsafe reads the uint32 in varint format starting at fd, and returns the
   785  // uint32 and a pointer to the byte following the varint.
   786  //
   787  // There is a similar function runtime.readvarint, which takes a slice of bytes,
   788  // rather than an unsafe pointer. These functions are duplicated, because one of
   789  // the two use cases for the functions would get slower if the functions were
   790  // combined.
   791  func readvarintUnsafe(fd unsafe.Pointer) (uint32, unsafe.Pointer) {
   792  	var r uint32
   793  	var shift int
   794  	for {
   795  		b := *(*uint8)((unsafe.Pointer(fd)))
   796  		fd = add(fd, unsafe.Sizeof(b))
   797  		if b < 128 {
   798  			return r + uint32(b)<<shift, fd
   799  		}
   800  		r += ((uint32(b) &^ 128) << shift)
   801  		shift += 7
   802  		if shift > 28 {
   803  			panic("Bad varint")
   804  		}
   805  	}
   806  }
   807  
   808  // runOpenDeferFrame runs the active open-coded defers in the frame specified by
   809  // d. It normally processes all active defers in the frame, but stops immediately
   810  // if a defer does a successful recover. It returns true if there are no
   811  // remaining defers to run in the frame.
   812  func runOpenDeferFrame(gp *g, d *_defer) bool {
   813  	done := true
   814  	fd := d.fd
   815  
   816  	// Skip the maxargsize
   817  	_, fd = readvarintUnsafe(fd)
   818  	deferBitsOffset, fd := readvarintUnsafe(fd)
   819  	nDefers, fd := readvarintUnsafe(fd)
   820  	deferBits := *(*uint8)(unsafe.Pointer(d.varp - uintptr(deferBitsOffset)))
   821  
   822  	for i := int(nDefers) - 1; i >= 0; i-- {
   823  		// read the funcdata info for this defer
   824  		var argWidth, closureOffset, nArgs uint32
   825  		argWidth, fd = readvarintUnsafe(fd)
   826  		closureOffset, fd = readvarintUnsafe(fd)
   827  		nArgs, fd = readvarintUnsafe(fd)
   828  		if deferBits&(1<<i) == 0 {
   829  			for j := uint32(0); j < nArgs; j++ {
   830  				_, fd = readvarintUnsafe(fd)
   831  				_, fd = readvarintUnsafe(fd)
   832  				_, fd = readvarintUnsafe(fd)
   833  			}
   834  			continue
   835  		}
   836  		closure := *(**funcval)(unsafe.Pointer(d.varp - uintptr(closureOffset)))
   837  		d.fn = closure
   838  		deferArgs := deferArgs(d)
   839  		// If there is an interface receiver or method receiver, it is
   840  		// described/included as the first arg.
   841  		for j := uint32(0); j < nArgs; j++ {
   842  			var argOffset, argLen, argCallOffset uint32
   843  			argOffset, fd = readvarintUnsafe(fd)
   844  			argLen, fd = readvarintUnsafe(fd)
   845  			argCallOffset, fd = readvarintUnsafe(fd)
   846  			memmove(unsafe.Pointer(uintptr(deferArgs)+uintptr(argCallOffset)),
   847  				unsafe.Pointer(d.varp-uintptr(argOffset)),
   848  				uintptr(argLen))
   849  		}
   850  		deferBits = deferBits &^ (1 << i)
   851  		*(*uint8)(unsafe.Pointer(d.varp - uintptr(deferBitsOffset))) = deferBits
   852  		p := d._panic
   853  		reflectcallSave(p, unsafe.Pointer(closure), deferArgs, argWidth)
   854  		if p != nil && p.aborted {
   855  			break
   856  		}
   857  		d.fn = nil
   858  		// These args are just a copy, so can be cleared immediately
   859  		memclrNoHeapPointers(deferArgs, uintptr(argWidth))
   860  		if d._panic != nil && d._panic.recovered {
   861  			done = deferBits == 0
   862  			break
   863  		}
   864  	}
   865  
   866  	return done
   867  }
   868  
   869  // reflectcallSave calls reflectcall after saving the caller's pc and sp in the
   870  // panic record. This allows the runtime to return to the Goexit defer processing
   871  // loop, in the unusual case where the Goexit may be bypassed by a successful
   872  // recover.
   873  func reflectcallSave(p *_panic, fn, arg unsafe.Pointer, argsize uint32) {
   874  	if p != nil {
   875  		p.argp = unsafe.Pointer(getargp(0))
   876  		p.pc = getcallerpc()
   877  		p.sp = unsafe.Pointer(getcallersp())
   878  	}
   879  	reflectcall(nil, fn, arg, argsize, argsize)
   880  	if p != nil {
   881  		p.pc = 0
   882  		p.sp = unsafe.Pointer(nil)
   883  	}
   884  }
   885  
   886  // The implementation of the predeclared function panic.
   887  func gopanic(e interface{}) {
   888  	gp := getg()
   889  	if gp.m.curg != gp {
   890  		print("panic: ")
   891  		printany(e)
   892  		print("\n")
   893  		throw("panic on system stack")
   894  	}
   895  
   896  	if gp.m.mallocing != 0 {
   897  		print("panic: ")
   898  		printany(e)
   899  		print("\n")
   900  		throw("panic during malloc")
   901  	}
   902  	if gp.m.preemptoff != "" {
   903  		print("panic: ")
   904  		printany(e)
   905  		print("\n")
   906  		print("preempt off reason: ")
   907  		print(gp.m.preemptoff)
   908  		print("\n")
   909  		throw("panic during preemptoff")
   910  	}
   911  	if gp.m.locks != 0 {
   912  		print("panic: ")
   913  		printany(e)
   914  		print("\n")
   915  		throw("panic holding locks")
   916  	}
   917  
   918  	var p _panic
   919  	p.arg = e
   920  	p.link = gp._panic
   921  	gp._panic = (*_panic)(noescape(unsafe.Pointer(&p)))
   922  
   923  	atomic.Xadd(&runningPanicDefers, 1)
   924  
   925  	// By calculating getcallerpc/getcallersp here, we avoid scanning the
   926  	// gopanic frame (stack scanning is slow...)
   927  	addOneOpenDeferFrame(gp, getcallerpc(), unsafe.Pointer(getcallersp()))
   928  
   929  	for {
   930  		d := gp._defer
   931  		if d == nil {
   932  			break
   933  		}
   934  
   935  		// If defer was started by earlier panic or Goexit (and, since we're back here, that triggered a new panic),
   936  		// take defer off list. An earlier panic will not continue running, but we will make sure below that an
   937  		// earlier Goexit does continue running.
   938  		if d.started {
   939  			if d._panic != nil {
   940  				d._panic.aborted = true
   941  			}
   942  			d._panic = nil
   943  			if !d.openDefer {
   944  				// For open-coded defers, we need to process the
   945  				// defer again, in case there are any other defers
   946  				// to call in the frame (not including the defer
   947  				// call that caused the panic).
   948  				d.fn = nil
   949  				gp._defer = d.link
   950  				freedefer(d)
   951  				continue
   952  			}
   953  		}
   954  
   955  		// Mark defer as started, but keep on list, so that traceback
   956  		// can find and update the defer's argument frame if stack growth
   957  		// or a garbage collection happens before reflectcall starts executing d.fn.
   958  		d.started = true
   959  
   960  		// Record the panic that is running the defer.
   961  		// If there is a new panic during the deferred call, that panic
   962  		// will find d in the list and will mark d._panic (this panic) aborted.
   963  		d._panic = (*_panic)(noescape(unsafe.Pointer(&p)))
   964  
   965  		done := true
   966  		if d.openDefer {
   967  			done = runOpenDeferFrame(gp, d)
   968  			if done && !d._panic.recovered {
   969  				addOneOpenDeferFrame(gp, 0, nil)
   970  			}
   971  		} else {
   972  			p.argp = unsafe.Pointer(getargp(0))
   973  			reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
   974  		}
   975  		p.argp = nil
   976  
   977  		// reflectcall did not panic. Remove d.
   978  		if gp._defer != d {
   979  			throw("bad defer entry in panic")
   980  		}
   981  		d._panic = nil
   982  
   983  		// trigger shrinkage to test stack copy. See stack_test.go:TestStackPanic
   984  		//GC()
   985  
   986  		pc := d.pc
   987  		sp := unsafe.Pointer(d.sp) // must be pointer so it gets adjusted during stack copy
   988  		if done {
   989  			d.fn = nil
   990  			gp._defer = d.link
   991  			freedefer(d)
   992  		}
   993  		if p.recovered {
   994  			gp._panic = p.link
   995  			if gp._panic != nil && gp._panic.goexit && gp._panic.aborted {
   996  				// A normal recover would bypass/abort the Goexit.  Instead,
   997  				// we return to the processing loop of the Goexit.
   998  				gp.sigcode0 = uintptr(gp._panic.sp)
   999  				gp.sigcode1 = uintptr(gp._panic.pc)
  1000  				mcall(recovery)
  1001  				throw("bypassed recovery failed") // mcall should not return
  1002  			}
  1003  			atomic.Xadd(&runningPanicDefers, -1)
  1004  
  1005  			if done {
  1006  				// Remove any remaining non-started, open-coded
  1007  				// defer entries after a recover, since the
  1008  				// corresponding defers will be executed normally
  1009  				// (inline). Any such entry will become stale once
  1010  				// we run the corresponding defers inline and exit
  1011  				// the associated stack frame.
  1012  				d := gp._defer
  1013  				var prev *_defer
  1014  				for d != nil {
  1015  					if d.openDefer {
  1016  						if d.started {
  1017  							// This defer is started but we
  1018  							// are in the middle of a
  1019  							// defer-panic-recover inside of
  1020  							// it, so don't remove it or any
  1021  							// further defer entries
  1022  							break
  1023  						}
  1024  						if prev == nil {
  1025  							gp._defer = d.link
  1026  						} else {
  1027  							prev.link = d.link
  1028  						}
  1029  						newd := d.link
  1030  						freedefer(d)
  1031  						d = newd
  1032  					} else {
  1033  						prev = d
  1034  						d = d.link
  1035  					}
  1036  				}
  1037  			}
  1038  
  1039  			gp._panic = p.link
  1040  			// Aborted panics are marked but remain on the g.panic list.
  1041  			// Remove them from the list.
  1042  			for gp._panic != nil && gp._panic.aborted {
  1043  				gp._panic = gp._panic.link
  1044  			}
  1045  			if gp._panic == nil { // must be done with signal
  1046  				gp.sig = 0
  1047  			}
  1048  			// Pass information about recovering frame to recovery.
  1049  			gp.sigcode0 = uintptr(sp)
  1050  			gp.sigcode1 = pc
  1051  			mcall(recovery)
  1052  			throw("recovery failed") // mcall should not return
  1053  		}
  1054  	}
  1055  
  1056  	// ran out of deferred calls - old-school panic now
  1057  	// Because it is unsafe to call arbitrary user code after freezing
  1058  	// the world, we call preprintpanics to invoke all necessary Error
  1059  	// and String methods to prepare the panic strings before startpanic.
  1060  	preprintpanics(gp._panic)
  1061  
  1062  	fatalpanic(gp._panic) // should not return
  1063  	*(*int)(nil) = 0      // not reached
  1064  }
  1065  
  1066  // getargp returns the location where the caller
  1067  // writes outgoing function call arguments.
  1068  //go:nosplit
  1069  //go:noinline
  1070  func getargp(x int) uintptr {
  1071  	// x is an argument mainly so that we can return its address.
  1072  	return uintptr(noescape(unsafe.Pointer(&x)))
  1073  }
  1074  
  1075  // The implementation of the predeclared function recover.
  1076  // Cannot split the stack because it needs to reliably
  1077  // find the stack segment of its caller.
  1078  //
  1079  // TODO(rsc): Once we commit to CopyStackAlways,
  1080  // this doesn't need to be nosplit.
  1081  //go:nosplit
  1082  func gorecover(argp uintptr) interface{} {
  1083  	// Must be in a function running as part of a deferred call during the panic.
  1084  	// Must be called from the topmost function of the call
  1085  	// (the function used in the defer statement).
  1086  	// p.argp is the argument pointer of that topmost deferred function call.
  1087  	// Compare against argp reported by caller.
  1088  	// If they match, the caller is the one who can recover.
  1089  	gp := getg()
  1090  	p := gp._panic
  1091  	if p != nil && !p.goexit && !p.recovered && argp == uintptr(p.argp) {
  1092  		p.recovered = true
  1093  		return p.arg
  1094  	}
  1095  	return nil
  1096  }
  1097  
  1098  //go:linkname sync_throw sync.throw
  1099  func sync_throw(s string) {
  1100  	throw(s)
  1101  }
  1102  
  1103  //go:nosplit
  1104  func throw(s string) {
  1105  	// Everything throw does should be recursively nosplit so it
  1106  	// can be called even when it's unsafe to grow the stack.
  1107  	systemstack(func() {
  1108  		print("fatal error: ", s, "\n")
  1109  	})
  1110  	gp := getg()
  1111  	if gp.m.throwing == 0 {
  1112  		gp.m.throwing = 1
  1113  	}
  1114  	fatalthrow()
  1115  	*(*int)(nil) = 0 // not reached
  1116  }
  1117  
  1118  // runningPanicDefers is non-zero while running deferred functions for panic.
  1119  // runningPanicDefers is incremented and decremented atomically.
  1120  // This is used to try hard to get a panic stack trace out when exiting.
  1121  var runningPanicDefers uint32
  1122  
  1123  // panicking is non-zero when crashing the program for an unrecovered panic.
  1124  // panicking is incremented and decremented atomically.
  1125  var panicking uint32
  1126  
  1127  // paniclk is held while printing the panic information and stack trace,
  1128  // so that two concurrent panics don't overlap their output.
  1129  var paniclk mutex
  1130  
  1131  // Unwind the stack after a deferred function calls recover
  1132  // after a panic. Then arrange to continue running as though
  1133  // the caller of the deferred function returned normally.
  1134  func recovery(gp *g) {
  1135  	// Info about defer passed in G struct.
  1136  	sp := gp.sigcode0
  1137  	pc := gp.sigcode1
  1138  
  1139  	// d's arguments need to be in the stack.
  1140  	if sp != 0 && (sp < gp.stack.lo || gp.stack.hi < sp) {
  1141  		print("recover: ", hex(sp), " not in [", hex(gp.stack.lo), ", ", hex(gp.stack.hi), "]\n")
  1142  		throw("bad recovery")
  1143  	}
  1144  
  1145  	// Make the deferproc for this d return again,
  1146  	// this time returning 1. The calling function will
  1147  	// jump to the standard return epilogue.
  1148  	gp.sched.sp = sp
  1149  	gp.sched.pc = pc
  1150  	gp.sched.lr = 0
  1151  	gp.sched.ret = 1
  1152  	gogo(&gp.sched)
  1153  }
  1154  
  1155  // fatalthrow implements an unrecoverable runtime throw. It freezes the
  1156  // system, prints stack traces starting from its caller, and terminates the
  1157  // process.
  1158  //
  1159  //go:nosplit
  1160  func fatalthrow() {
  1161  	pc := getcallerpc()
  1162  	sp := getcallersp()
  1163  	gp := getg()
  1164  	// Switch to the system stack to avoid any stack growth, which
  1165  	// may make things worse if the runtime is in a bad state.
  1166  	systemstack(func() {
  1167  		startpanic_m()
  1168  
  1169  		if dopanic_m(gp, pc, sp) {
  1170  			// crash uses a decent amount of nosplit stack and we're already
  1171  			// low on stack in throw, so crash on the system stack (unlike
  1172  			// fatalpanic).
  1173  			crash()
  1174  		}
  1175  
  1176  		exit(2)
  1177  	})
  1178  
  1179  	*(*int)(nil) = 0 // not reached
  1180  }
  1181  
  1182  // fatalpanic implements an unrecoverable panic. It is like fatalthrow, except
  1183  // that if msgs != nil, fatalpanic also prints panic messages and decrements
  1184  // runningPanicDefers once main is blocked from exiting.
  1185  //
  1186  //go:nosplit
  1187  func fatalpanic(msgs *_panic) {
  1188  	pc := getcallerpc()
  1189  	sp := getcallersp()
  1190  	gp := getg()
  1191  	var docrash bool
  1192  	// Switch to the system stack to avoid any stack growth, which
  1193  	// may make things worse if the runtime is in a bad state.
  1194  	systemstack(func() {
  1195  		if startpanic_m() && msgs != nil {
  1196  			// There were panic messages and startpanic_m
  1197  			// says it's okay to try to print them.
  1198  
  1199  			// startpanic_m set panicking, which will
  1200  			// block main from exiting, so now OK to
  1201  			// decrement runningPanicDefers.
  1202  			atomic.Xadd(&runningPanicDefers, -1)
  1203  
  1204  			printpanics(msgs)
  1205  		}
  1206  
  1207  		docrash = dopanic_m(gp, pc, sp)
  1208  	})
  1209  
  1210  	if docrash {
  1211  		// By crashing outside the above systemstack call, debuggers
  1212  		// will not be confused when generating a backtrace.
  1213  		// Function crash is marked nosplit to avoid stack growth.
  1214  		crash()
  1215  	}
  1216  
  1217  	systemstack(func() {
  1218  		exit(2)
  1219  	})
  1220  
  1221  	*(*int)(nil) = 0 // not reached
  1222  }
  1223  
  1224  // startpanic_m prepares for an unrecoverable panic.
  1225  //
  1226  // It returns true if panic messages should be printed, or false if
  1227  // the runtime is in bad shape and should just print stacks.
  1228  //
  1229  // It must not have write barriers even though the write barrier
  1230  // explicitly ignores writes once dying > 0. Write barriers still
  1231  // assume that g.m.p != nil, and this function may not have P
  1232  // in some contexts (e.g. a panic in a signal handler for a signal
  1233  // sent to an M with no P).
  1234  //
  1235  //go:nowritebarrierrec
  1236  func startpanic_m() bool {
  1237  	_g_ := getg()
  1238  	if mheap_.cachealloc.size == 0 { // very early
  1239  		print("runtime: panic before malloc heap initialized\n")
  1240  	}
  1241  	// Disallow malloc during an unrecoverable panic. A panic
  1242  	// could happen in a signal handler, or in a throw, or inside
  1243  	// malloc itself. We want to catch if an allocation ever does
  1244  	// happen (even if we're not in one of these situations).
  1245  	_g_.m.mallocing++
  1246  
  1247  	// If we're dying because of a bad lock count, set it to a
  1248  	// good lock count so we don't recursively panic below.
  1249  	if _g_.m.locks < 0 {
  1250  		_g_.m.locks = 1
  1251  	}
  1252  
  1253  	switch _g_.m.dying {
  1254  	case 0:
  1255  		// Setting dying >0 has the side-effect of disabling this G's writebuf.
  1256  		_g_.m.dying = 1
  1257  		atomic.Xadd(&panicking, 1)
  1258  		lock(&paniclk)
  1259  		if debug.schedtrace > 0 || debug.scheddetail > 0 {
  1260  			schedtrace(true)
  1261  		}
  1262  		freezetheworld()
  1263  		return true
  1264  	case 1:
  1265  		// Something failed while panicking.
  1266  		// Just print a stack trace and exit.
  1267  		_g_.m.dying = 2
  1268  		print("panic during panic\n")
  1269  		return false
  1270  	case 2:
  1271  		// This is a genuine bug in the runtime, we couldn't even
  1272  		// print the stack trace successfully.
  1273  		_g_.m.dying = 3
  1274  		print("stack trace unavailable\n")
  1275  		exit(4)
  1276  		fallthrough
  1277  	default:
  1278  		// Can't even print! Just exit.
  1279  		exit(5)
  1280  		return false // Need to return something.
  1281  	}
  1282  }
  1283  
  1284  // throwReportQuirk, if non-nil, is called by throw after dumping the stacks.
  1285  //
  1286  // TODO(austin): Remove this after Go 1.15 when we remove the
  1287  // mlockGsignal workaround.
  1288  var throwReportQuirk func()
  1289  
  1290  var didothers bool
  1291  var deadlock mutex
  1292  
  1293  func dopanic_m(gp *g, pc, sp uintptr) bool {
  1294  	if gp.sig != 0 {
  1295  		signame := signame(gp.sig)
  1296  		if signame != "" {
  1297  			print("[signal ", signame)
  1298  		} else {
  1299  			print("[signal ", hex(gp.sig))
  1300  		}
  1301  		print(" code=", hex(gp.sigcode0), " addr=", hex(gp.sigcode1), " pc=", hex(gp.sigpc), "]\n")
  1302  	}
  1303  
  1304  	level, all, docrash := gotraceback()
  1305  	_g_ := getg()
  1306  	if level > 0 {
  1307  		if gp != gp.m.curg {
  1308  			all = true
  1309  		}
  1310  		if gp != gp.m.g0 {
  1311  			print("\n")
  1312  			goroutineheader(gp)
  1313  			traceback(pc, sp, 0, gp)
  1314  		} else if level >= 2 || _g_.m.throwing > 0 {
  1315  			print("\nruntime stack:\n")
  1316  			traceback(pc, sp, 0, gp)
  1317  		}
  1318  		if !didothers && all {
  1319  			didothers = true
  1320  			tracebackothers(gp)
  1321  		}
  1322  	}
  1323  	unlock(&paniclk)
  1324  
  1325  	if atomic.Xadd(&panicking, -1) != 0 {
  1326  		// Some other m is panicking too.
  1327  		// Let it print what it needs to print.
  1328  		// Wait forever without chewing up cpu.
  1329  		// It will exit when it's done.
  1330  		lock(&deadlock)
  1331  		lock(&deadlock)
  1332  	}
  1333  
  1334  	printDebugLog()
  1335  
  1336  	if throwReportQuirk != nil {
  1337  		throwReportQuirk()
  1338  	}
  1339  
  1340  	return docrash
  1341  }
  1342  
  1343  // canpanic returns false if a signal should throw instead of
  1344  // panicking.
  1345  //
  1346  //go:nosplit
  1347  func canpanic(gp *g) bool {
  1348  	// Note that g is m->gsignal, different from gp.
  1349  	// Note also that g->m can change at preemption, so m can go stale
  1350  	// if this function ever makes a function call.
  1351  	_g_ := getg()
  1352  	_m_ := _g_.m
  1353  
  1354  	// Is it okay for gp to panic instead of crashing the program?
  1355  	// Yes, as long as it is running Go code, not runtime code,
  1356  	// and not stuck in a system call.
  1357  	if gp == nil || gp != _m_.curg {
  1358  		return false
  1359  	}
  1360  	if _m_.locks != 0 || _m_.mallocing != 0 || _m_.throwing != 0 || _m_.preemptoff != "" || _m_.dying != 0 {
  1361  		return false
  1362  	}
  1363  	status := readgstatus(gp)
  1364  	if status&^_Gscan != _Grunning || gp.syscallsp != 0 {
  1365  		return false
  1366  	}
  1367  	if GOOS == "windows" && _m_.libcallsp != 0 {
  1368  		return false
  1369  	}
  1370  	return true
  1371  }
  1372  
  1373  // shouldPushSigpanic reports whether pc should be used as sigpanic's
  1374  // return PC (pushing a frame for the call). Otherwise, it should be
  1375  // left alone so that LR is used as sigpanic's return PC, effectively
  1376  // replacing the top-most frame with sigpanic. This is used by
  1377  // preparePanic.
  1378  func shouldPushSigpanic(gp *g, pc, lr uintptr) bool {
  1379  	if pc == 0 {
  1380  		// Probably a call to a nil func. The old LR is more
  1381  		// useful in the stack trace. Not pushing the frame
  1382  		// will make the trace look like a call to sigpanic
  1383  		// instead. (Otherwise the trace will end at sigpanic
  1384  		// and we won't get to see who faulted.)
  1385  		return false
  1386  	}
  1387  	// If we don't recognize the PC as code, but we do recognize
  1388  	// the link register as code, then this assumes the panic was
  1389  	// caused by a call to non-code. In this case, we want to
  1390  	// ignore this call to make unwinding show the context.
  1391  	//
  1392  	// If we running C code, we're not going to recognize pc as a
  1393  	// Go function, so just assume it's good. Otherwise, traceback
  1394  	// may try to read a stale LR that looks like a Go code
  1395  	// pointer and wander into the woods.
  1396  	if gp.m.incgo || findfunc(pc).valid() {
  1397  		// This wasn't a bad call, so use PC as sigpanic's
  1398  		// return PC.
  1399  		return true
  1400  	}
  1401  	if findfunc(lr).valid() {
  1402  		// This was a bad call, but the LR is good, so use the
  1403  		// LR as sigpanic's return PC.
  1404  		return false
  1405  	}
  1406  	// Neither the PC or LR is good. Hopefully pushing a frame
  1407  	// will work.
  1408  	return true
  1409  }
  1410  
  1411  // isAbortPC reports whether pc is the program counter at which
  1412  // runtime.abort raises a signal.
  1413  //
  1414  // It is nosplit because it's part of the isgoexception
  1415  // implementation.
  1416  //
  1417  //go:nosplit
  1418  func isAbortPC(pc uintptr) bool {
  1419  	return pc == funcPC(abort) || ((GOARCH == "arm" || GOARCH == "arm64") && pc == funcPC(abort)+sys.PCQuantum)
  1420  }
  1421  

View as plain text