Source file src/runtime/panic.go

     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  	"internal/abi"
     9  	"internal/goarch"
    10  	"internal/runtime/atomic"
    11  	"internal/runtime/sys"
    12  	"internal/stringslite"
    13  	"unsafe"
    14  )
    15  
    16  // throwType indicates the current type of ongoing throw, which affects the
    17  // amount of detail printed to stderr. Higher values include more detail.
    18  type throwType uint32
    19  
    20  const (
    21  	// throwTypeNone means that we are not throwing.
    22  	throwTypeNone throwType = iota
    23  
    24  	// throwTypeUser is a throw due to a problem with the application.
    25  	//
    26  	// These throws do not include runtime frames, system goroutines, or
    27  	// frame metadata.
    28  	throwTypeUser
    29  
    30  	// throwTypeRuntime is a throw due to a problem with Go itself.
    31  	//
    32  	// These throws include as much information as possible to aid in
    33  	// debugging the runtime, including runtime frames, system goroutines,
    34  	// and frame metadata.
    35  	throwTypeRuntime
    36  )
    37  
    38  // We have two different ways of doing defers. The older way involves creating a
    39  // defer record at the time that a defer statement is executing and adding it to a
    40  // defer chain. This chain is inspected by the deferreturn call at all function
    41  // exits in order to run the appropriate defer calls. A cheaper way (which we call
    42  // open-coded defers) is used for functions in which no defer statements occur in
    43  // loops. In that case, we simply store the defer function/arg information into
    44  // specific stack slots at the point of each defer statement, as well as setting a
    45  // bit in a bitmask. At each function exit, we add inline code to directly make
    46  // the appropriate defer calls based on the bitmask and fn/arg information stored
    47  // on the stack. During panic/Goexit processing, the appropriate defer calls are
    48  // made using extra funcdata info that indicates the exact stack slots that
    49  // contain the bitmask and defer fn/args.
    50  
    51  // Check to make sure we can really generate a panic. If the panic
    52  // was generated from the runtime, or from inside malloc, then convert
    53  // to a throw of msg.
    54  // pc should be the program counter of the compiler-generated code that
    55  // triggered this panic.
    56  func panicCheck1(pc uintptr, msg string) {
    57  	if goarch.IsWasm == 0 && stringslite.HasPrefix(funcname(findfunc(pc)), "runtime.") {
    58  		// Note: wasm can't tail call, so we can't get the original caller's pc.
    59  		throw(msg)
    60  	}
    61  	// TODO: is this redundant? How could we be in malloc
    62  	// but not in the runtime? internal/runtime/*, maybe?
    63  	gp := getg()
    64  	if gp != nil && gp.m != nil && gp.m.mallocing != 0 {
    65  		throw(msg)
    66  	}
    67  }
    68  
    69  // Same as above, but calling from the runtime is allowed.
    70  //
    71  // Using this function is necessary for any panic that may be
    72  // generated by runtime.sigpanic, since those are always called by the
    73  // runtime.
    74  func panicCheck2(err string) {
    75  	// panic allocates, so to avoid recursive malloc, turn panics
    76  	// during malloc into throws.
    77  	gp := getg()
    78  	if gp != nil && gp.m != nil && gp.m.mallocing != 0 {
    79  		throw(err)
    80  	}
    81  }
    82  
    83  // Many of the following panic entry-points turn into throws when they
    84  // happen in various runtime contexts. These should never happen in
    85  // the runtime, and if they do, they indicate a serious issue and
    86  // should not be caught by user code.
    87  //
    88  // The panic{Index,Slice,divide,shift} functions are called by
    89  // code generated by the compiler for out of bounds index expressions,
    90  // out of bounds slice expressions, division by zero, and shift by negative.
    91  // The panicdivide (again), panicoverflow, panicfloat, and panicmem
    92  // functions are called by the signal handler when a signal occurs
    93  // indicating the respective problem.
    94  //
    95  // Since panic{Index,Slice,shift} are never called directly, and
    96  // since the runtime package should never have an out of bounds slice
    97  // or array reference or negative shift, if we see those functions called from the
    98  // runtime package we turn the panic into a throw. That will dump the
    99  // entire runtime stack for easier debugging.
   100  //
   101  // The entry points called by the signal handler will be called from
   102  // runtime.sigpanic, so we can't disallow calls from the runtime to
   103  // these (they always look like they're called from the runtime).
   104  // Hence, for these, we just check for clearly bad runtime conditions.
   105  //
   106  // The goPanic{Index,Slice} functions are only used by wasm. All the other architectures
   107  // use panic{Bounds,Extend} in assembly, which then call to panicBounds{64,32,32X}.
   108  
   109  // failures in the comparisons for s[x], 0 <= x < y (y == len(s))
   110  //
   111  //go:yeswritebarrierrec
   112  func goPanicIndex(x int, y int) {
   113  	panicCheck1(sys.GetCallerPC(), "index out of range")
   114  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsIndex})
   115  }
   116  
   117  //go:yeswritebarrierrec
   118  func goPanicIndexU(x uint, y int) {
   119  	panicCheck1(sys.GetCallerPC(), "index out of range")
   120  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsIndex})
   121  }
   122  
   123  // failures in the comparisons for s[:x], 0 <= x <= y (y == len(s) or cap(s))
   124  //
   125  //go:yeswritebarrierrec
   126  func goPanicSliceAlen(x int, y int) {
   127  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   128  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsSliceAlen})
   129  }
   130  
   131  //go:yeswritebarrierrec
   132  func goPanicSliceAlenU(x uint, y int) {
   133  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   134  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsSliceAlen})
   135  }
   136  
   137  //go:yeswritebarrierrec
   138  func goPanicSliceAcap(x int, y int) {
   139  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   140  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsSliceAcap})
   141  }
   142  
   143  //go:yeswritebarrierrec
   144  func goPanicSliceAcapU(x uint, y int) {
   145  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   146  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsSliceAcap})
   147  }
   148  
   149  // failures in the comparisons for s[x:y], 0 <= x <= y
   150  //
   151  //go:yeswritebarrierrec
   152  func goPanicSliceB(x int, y int) {
   153  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   154  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsSliceB})
   155  }
   156  
   157  //go:yeswritebarrierrec
   158  func goPanicSliceBU(x uint, y int) {
   159  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   160  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsSliceB})
   161  }
   162  
   163  // failures in the comparisons for s[::x], 0 <= x <= y (y == len(s) or cap(s))
   164  func goPanicSlice3Alen(x int, y int) {
   165  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   166  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsSlice3Alen})
   167  }
   168  func goPanicSlice3AlenU(x uint, y int) {
   169  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   170  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsSlice3Alen})
   171  }
   172  func goPanicSlice3Acap(x int, y int) {
   173  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   174  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsSlice3Acap})
   175  }
   176  func goPanicSlice3AcapU(x uint, y int) {
   177  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   178  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsSlice3Acap})
   179  }
   180  
   181  // failures in the comparisons for s[:x:y], 0 <= x <= y
   182  func goPanicSlice3B(x int, y int) {
   183  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   184  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsSlice3B})
   185  }
   186  func goPanicSlice3BU(x uint, y int) {
   187  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   188  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsSlice3B})
   189  }
   190  
   191  // failures in the comparisons for s[x:y:], 0 <= x <= y
   192  func goPanicSlice3C(x int, y int) {
   193  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   194  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsSlice3C})
   195  }
   196  func goPanicSlice3CU(x uint, y int) {
   197  	panicCheck1(sys.GetCallerPC(), "slice bounds out of range")
   198  	panic(boundsError{x: int64(x), signed: false, y: y, code: abi.BoundsSlice3C})
   199  }
   200  
   201  // failures in the conversion ([x]T)(s) or (*[x]T)(s), 0 <= x <= y, y == len(s)
   202  func goPanicSliceConvert(x int, y int) {
   203  	panicCheck1(sys.GetCallerPC(), "slice length too short to convert to array or pointer to array")
   204  	panic(boundsError{x: int64(x), signed: true, y: y, code: abi.BoundsConvert})
   205  }
   206  
   207  // Implemented in assembly. Declared here to mark them as ABIInternal.
   208  func panicBounds() // in asm_GOARCH.s files, called from generated code
   209  func panicExtend() // in asm_GOARCH.s files, called from generated code (on 32-bit archs)
   210  
   211  func panicBounds64(pc uintptr, regs *[16]int64) { // called from panicBounds on 64-bit archs
   212  	f := findfunc(pc)
   213  	v := pcdatavalue(f, abi.PCDATA_PanicBounds, pc-1)
   214  
   215  	code, signed, xIsReg, yIsReg, xVal, yVal := abi.BoundsDecode(int(v))
   216  
   217  	if code == abi.BoundsIndex {
   218  		panicCheck1(pc, "index out of range")
   219  	} else {
   220  		panicCheck1(pc, "slice bounds out of range")
   221  	}
   222  
   223  	var e boundsError
   224  	e.code = code
   225  	e.signed = signed
   226  	if xIsReg {
   227  		e.x = regs[xVal]
   228  	} else {
   229  		e.x = int64(xVal)
   230  	}
   231  	if yIsReg {
   232  		e.y = int(regs[yVal])
   233  	} else {
   234  		e.y = yVal
   235  	}
   236  	panic(e)
   237  }
   238  
   239  func panicBounds32(pc uintptr, regs *[16]int32) { // called from panicBounds on 32-bit archs
   240  	f := findfunc(pc)
   241  	v := pcdatavalue(f, abi.PCDATA_PanicBounds, pc-1)
   242  
   243  	code, signed, xIsReg, yIsReg, xVal, yVal := abi.BoundsDecode(int(v))
   244  
   245  	if code == abi.BoundsIndex {
   246  		panicCheck1(pc, "index out of range")
   247  	} else {
   248  		panicCheck1(pc, "slice bounds out of range")
   249  	}
   250  
   251  	var e boundsError
   252  	e.code = code
   253  	e.signed = signed
   254  	if xIsReg {
   255  		if signed {
   256  			e.x = int64(regs[xVal])
   257  		} else {
   258  			e.x = int64(uint32(regs[xVal]))
   259  		}
   260  	} else {
   261  		e.x = int64(xVal)
   262  	}
   263  	if yIsReg {
   264  		e.y = int(regs[yVal])
   265  	} else {
   266  		e.y = yVal
   267  	}
   268  	panic(e)
   269  }
   270  
   271  func panicBounds32X(pc uintptr, regs *[16]int32) { // called from panicExtend on 32-bit archs
   272  	f := findfunc(pc)
   273  	v := pcdatavalue(f, abi.PCDATA_PanicBounds, pc-1)
   274  
   275  	code, signed, xIsReg, yIsReg, xVal, yVal := abi.BoundsDecode(int(v))
   276  
   277  	if code == abi.BoundsIndex {
   278  		panicCheck1(pc, "index out of range")
   279  	} else {
   280  		panicCheck1(pc, "slice bounds out of range")
   281  	}
   282  
   283  	var e boundsError
   284  	e.code = code
   285  	e.signed = signed
   286  	if xIsReg {
   287  		// Our 4-bit register numbers are actually 2 2-bit register numbers.
   288  		lo := xVal & 3
   289  		hi := xVal >> 2
   290  		e.x = int64(regs[hi])<<32 + int64(uint32(regs[lo]))
   291  	} else {
   292  		e.x = int64(xVal)
   293  	}
   294  	if yIsReg {
   295  		e.y = int(regs[yVal])
   296  	} else {
   297  		e.y = yVal
   298  	}
   299  	panic(e)
   300  }
   301  
   302  var shiftError = error(errorString("negative shift amount"))
   303  
   304  //go:yeswritebarrierrec
   305  func panicshift() {
   306  	panicCheck1(sys.GetCallerPC(), "negative shift amount")
   307  	panic(shiftError)
   308  }
   309  
   310  var divideError = error(errorString("integer divide by zero"))
   311  
   312  //go:yeswritebarrierrec
   313  func panicdivide() {
   314  	panicCheck2("integer divide by zero")
   315  	panic(divideError)
   316  }
   317  
   318  var overflowError = error(errorString("integer overflow"))
   319  
   320  func panicoverflow() {
   321  	panicCheck2("integer overflow")
   322  	panic(overflowError)
   323  }
   324  
   325  var floatError = error(errorString("floating point error"))
   326  
   327  func panicfloat() {
   328  	panicCheck2("floating point error")
   329  	panic(floatError)
   330  }
   331  
   332  var memoryError = error(errorString("invalid memory address or nil pointer dereference"))
   333  
   334  func panicmem() {
   335  	panicCheck2("invalid memory address or nil pointer dereference")
   336  	panic(memoryError)
   337  }
   338  
   339  func panicmemAddr(addr uintptr) {
   340  	panicCheck2("invalid memory address or nil pointer dereference")
   341  	panic(errorAddressString{msg: "invalid memory address or nil pointer dereference", addr: addr})
   342  }
   343  
   344  // Create a new deferred function fn, which has no arguments and results.
   345  // The compiler turns a defer statement into a call to this.
   346  func deferproc(fn func()) {
   347  	gp := getg()
   348  	if gp.m.curg != gp {
   349  		// go code on the system stack can't defer
   350  		throw("defer on system stack")
   351  	}
   352  
   353  	d := newdefer()
   354  	d.link = gp._defer
   355  	gp._defer = d
   356  	d.fn = fn
   357  	d.pc = sys.GetCallerPC()
   358  	// We must not be preempted between calling GetCallerSP and
   359  	// storing it to d.sp because GetCallerSP's result is a
   360  	// uintptr stack pointer.
   361  	d.sp = sys.GetCallerSP()
   362  }
   363  
   364  var rangeDoneError = error(errorString("range function continued iteration after function for loop body returned false"))
   365  var rangePanicError = error(errorString("range function continued iteration after loop body panic"))
   366  var rangeExhaustedError = error(errorString("range function continued iteration after whole loop exit"))
   367  var rangeMissingPanicError = error(errorString("range function recovered a loop body panic and did not resume panicking"))
   368  
   369  //go:noinline
   370  func panicrangestate(state int) {
   371  	switch abi.RF_State(state) {
   372  	case abi.RF_DONE:
   373  		panic(rangeDoneError)
   374  	case abi.RF_PANIC:
   375  		panic(rangePanicError)
   376  	case abi.RF_EXHAUSTED:
   377  		panic(rangeExhaustedError)
   378  	case abi.RF_MISSING_PANIC:
   379  		panic(rangeMissingPanicError)
   380  	}
   381  	throw("unexpected state passed to panicrangestate")
   382  }
   383  
   384  // deferrangefunc is called by functions that are about to
   385  // execute a range-over-function loop in which the loop body
   386  // may execute a defer statement. That defer needs to add to
   387  // the chain for the current function, not the func literal synthesized
   388  // to represent the loop body. To do that, the original function
   389  // calls deferrangefunc to obtain an opaque token representing
   390  // the current frame, and then the loop body uses deferprocat
   391  // instead of deferproc to add to that frame's defer lists.
   392  //
   393  // The token is an 'any' with underlying type *atomic.Pointer[_defer].
   394  // It is the atomically-updated head of a linked list of _defer structs
   395  // representing deferred calls. At the same time, we create a _defer
   396  // struct on the main g._defer list with d.head set to this head pointer.
   397  //
   398  // The g._defer list is now a linked list of deferred calls,
   399  // but an atomic list hanging off:
   400  //
   401  //		g._defer => d4 -> d3 -> drangefunc -> d2 -> d1 -> nil
   402  //	                             | .head
   403  //	                             |
   404  //	                             +--> dY -> dX -> nil
   405  //
   406  // with each -> indicating a d.link pointer, and where drangefunc
   407  // has the d.rangefunc = true bit set.
   408  // Note that the function being ranged over may have added
   409  // its own defers (d4 and d3), so drangefunc need not be at the
   410  // top of the list when deferprocat is used. This is why we pass
   411  // the atomic head explicitly.
   412  //
   413  // To keep misbehaving programs from crashing the runtime,
   414  // deferprocat pushes new defers onto the .head list atomically.
   415  // The fact that it is a separate list from the main goroutine
   416  // defer list means that the main goroutine's defers can still
   417  // be handled non-atomically.
   418  //
   419  // In the diagram, dY and dX are meant to be processed when
   420  // drangefunc would be processed, which is to say the defer order
   421  // should be d4, d3, dY, dX, d2, d1. To make that happen,
   422  // when defer processing reaches a d with rangefunc=true,
   423  // it calls deferconvert to atomically take the extras
   424  // away from d.head and then adds them to the main list.
   425  //
   426  // That is, deferconvert changes this list:
   427  //
   428  //		g._defer => drangefunc -> d2 -> d1 -> nil
   429  //	                 | .head
   430  //	                 |
   431  //	                 +--> dY -> dX -> nil
   432  //
   433  // into this list:
   434  //
   435  //	g._defer => dY -> dX -> d2 -> d1 -> nil
   436  //
   437  // It also poisons *drangefunc.head so that any future
   438  // deferprocat using that head will throw.
   439  // (The atomic head is ordinary garbage collected memory so that
   440  // it's not a problem if user code holds onto it beyond
   441  // the lifetime of drangefunc.)
   442  //
   443  // TODO: We could arrange for the compiler to call into the
   444  // runtime after the loop finishes normally, to do an eager
   445  // deferconvert, which would catch calling the loop body
   446  // and having it defer after the loop is done. If we have a
   447  // more general catch of loop body misuse, though, this
   448  // might not be worth worrying about in addition.
   449  //
   450  // See also ../cmd/compile/internal/rangefunc/rewrite.go.
   451  func deferrangefunc() any {
   452  	gp := getg()
   453  	if gp.m.curg != gp {
   454  		// go code on the system stack can't defer
   455  		throw("defer on system stack")
   456  	}
   457  
   458  	d := newdefer()
   459  	d.link = gp._defer
   460  	gp._defer = d
   461  	d.pc = sys.GetCallerPC()
   462  	// We must not be preempted between calling GetCallerSP and
   463  	// storing it to d.sp because GetCallerSP's result is a
   464  	// uintptr stack pointer.
   465  	d.sp = sys.GetCallerSP()
   466  
   467  	d.rangefunc = true
   468  	d.head = new(atomic.Pointer[_defer])
   469  
   470  	return d.head
   471  }
   472  
   473  // badDefer returns a fixed bad defer pointer for poisoning an atomic defer list head.
   474  func badDefer() *_defer {
   475  	return (*_defer)(unsafe.Pointer(uintptr(1)))
   476  }
   477  
   478  // deferprocat is like deferproc but adds to the atomic list represented by frame.
   479  // See the doc comment for deferrangefunc for details.
   480  func deferprocat(fn func(), frame any) {
   481  	head := frame.(*atomic.Pointer[_defer])
   482  	if raceenabled {
   483  		racewritepc(unsafe.Pointer(head), sys.GetCallerPC(), abi.FuncPCABIInternal(deferprocat))
   484  	}
   485  	d1 := newdefer()
   486  	d1.fn = fn
   487  	for {
   488  		d1.link = head.Load()
   489  		if d1.link == badDefer() {
   490  			throw("defer after range func returned")
   491  		}
   492  		if head.CompareAndSwap(d1.link, d1) {
   493  			break
   494  		}
   495  	}
   496  }
   497  
   498  // deferconvert converts the rangefunc defer list of d0 into an ordinary list
   499  // following d0.
   500  // See the doc comment for deferrangefunc for details.
   501  func deferconvert(d0 *_defer) {
   502  	head := d0.head
   503  	if raceenabled {
   504  		racereadpc(unsafe.Pointer(head), sys.GetCallerPC(), abi.FuncPCABIInternal(deferconvert))
   505  	}
   506  	tail := d0.link
   507  	d0.rangefunc = false
   508  
   509  	var d *_defer
   510  	for {
   511  		d = head.Load()
   512  		if head.CompareAndSwap(d, badDefer()) {
   513  			break
   514  		}
   515  	}
   516  	if d == nil {
   517  		return
   518  	}
   519  	for d1 := d; ; d1 = d1.link {
   520  		d1.sp = d0.sp
   521  		d1.pc = d0.pc
   522  		if d1.link == nil {
   523  			d1.link = tail
   524  			break
   525  		}
   526  	}
   527  	d0.link = d
   528  	return
   529  }
   530  
   531  // deferprocStack queues a new deferred function with a defer record on the stack.
   532  // The defer record must have its fn field initialized.
   533  // All other fields can contain junk.
   534  // Nosplit because of the uninitialized pointer fields on the stack.
   535  //
   536  //go:nosplit
   537  func deferprocStack(d *_defer) {
   538  	gp := getg()
   539  	if gp.m.curg != gp {
   540  		// go code on the system stack can't defer
   541  		throw("defer on system stack")
   542  	}
   543  
   544  	// fn is already set.
   545  	// The other fields are junk on entry to deferprocStack and
   546  	// are initialized here.
   547  	d.heap = false
   548  	d.rangefunc = false
   549  	d.sp = sys.GetCallerSP()
   550  	d.pc = sys.GetCallerPC()
   551  	// The lines below implement:
   552  	//   d.panic = nil
   553  	//   d.fd = nil
   554  	//   d.link = gp._defer
   555  	//   d.head = nil
   556  	//   gp._defer = d
   557  	// But without write barriers. The first three are writes to
   558  	// the stack so they don't need a write barrier, and furthermore
   559  	// are to uninitialized memory, so they must not use a write barrier.
   560  	// The fourth write does not require a write barrier because we
   561  	// explicitly mark all the defer structures, so we don't need to
   562  	// keep track of pointers to them with a write barrier.
   563  	*(*uintptr)(unsafe.Pointer(&d.link)) = uintptr(unsafe.Pointer(gp._defer))
   564  	*(*uintptr)(unsafe.Pointer(&d.head)) = 0
   565  	*(*uintptr)(unsafe.Pointer(&gp._defer)) = uintptr(unsafe.Pointer(d))
   566  }
   567  
   568  // Each P holds a pool for defers.
   569  
   570  // Allocate a Defer, usually using per-P pool.
   571  // Each defer must be released with freedefer.  The defer is not
   572  // added to any defer chain yet.
   573  func newdefer() *_defer {
   574  	var d *_defer
   575  	mp := acquirem()
   576  	pp := mp.p.ptr()
   577  	if len(pp.deferpool) == 0 && sched.deferpool != nil {
   578  		lock(&sched.deferlock)
   579  		for len(pp.deferpool) < cap(pp.deferpool)/2 && sched.deferpool != nil {
   580  			d := sched.deferpool
   581  			sched.deferpool = d.link
   582  			d.link = nil
   583  			pp.deferpool = append(pp.deferpool, d)
   584  		}
   585  		unlock(&sched.deferlock)
   586  	}
   587  	if n := len(pp.deferpool); n > 0 {
   588  		d = pp.deferpool[n-1]
   589  		pp.deferpool[n-1] = nil
   590  		pp.deferpool = pp.deferpool[:n-1]
   591  	}
   592  	releasem(mp)
   593  	mp, pp = nil, nil
   594  
   595  	if d == nil {
   596  		// Allocate new defer.
   597  		d = new(_defer)
   598  	}
   599  	d.heap = true
   600  	return d
   601  }
   602  
   603  // popDefer pops the head of gp's defer list and frees it.
   604  func popDefer(gp *g) {
   605  	d := gp._defer
   606  	d.fn = nil // Can in theory point to the stack
   607  	// We must not copy the stack between the updating gp._defer and setting
   608  	// d.link to nil. Between these two steps, d is not on any defer list, so
   609  	// stack copying won't adjust stack pointers in it (namely, d.link). Hence,
   610  	// if we were to copy the stack, d could then contain a stale pointer.
   611  	gp._defer = d.link
   612  	d.link = nil
   613  	// After this point we can copy the stack.
   614  
   615  	if !d.heap {
   616  		return
   617  	}
   618  
   619  	mp := acquirem()
   620  	pp := mp.p.ptr()
   621  	if len(pp.deferpool) == cap(pp.deferpool) {
   622  		// Transfer half of local cache to the central cache.
   623  		var first, last *_defer
   624  		for len(pp.deferpool) > cap(pp.deferpool)/2 {
   625  			n := len(pp.deferpool)
   626  			d := pp.deferpool[n-1]
   627  			pp.deferpool[n-1] = nil
   628  			pp.deferpool = pp.deferpool[:n-1]
   629  			if first == nil {
   630  				first = d
   631  			} else {
   632  				last.link = d
   633  			}
   634  			last = d
   635  		}
   636  		lock(&sched.deferlock)
   637  		last.link = sched.deferpool
   638  		sched.deferpool = first
   639  		unlock(&sched.deferlock)
   640  	}
   641  
   642  	*d = _defer{}
   643  
   644  	pp.deferpool = append(pp.deferpool, d)
   645  
   646  	releasem(mp)
   647  	mp, pp = nil, nil
   648  }
   649  
   650  // deferreturn runs deferred functions for the caller's frame.
   651  // The compiler inserts a call to this at the end of any
   652  // function which calls defer.
   653  func deferreturn() {
   654  	var p _panic
   655  	p.deferreturn = true
   656  
   657  	p.start(sys.GetCallerPC(), unsafe.Pointer(sys.GetCallerSP()))
   658  	for {
   659  		fn, ok := p.nextDefer()
   660  		if !ok {
   661  			break
   662  		}
   663  		fn()
   664  	}
   665  }
   666  
   667  // Goexit terminates the goroutine that calls it. No other goroutine is affected.
   668  // Goexit runs all deferred calls before terminating the goroutine. Because Goexit
   669  // is not a panic, any recover calls in those deferred functions will return nil.
   670  //
   671  // Calling Goexit from the main goroutine terminates that goroutine
   672  // without func main returning. Since func main has not returned,
   673  // the program continues execution of other goroutines.
   674  // If all other goroutines exit, the program crashes.
   675  //
   676  // It crashes if called from a thread not created by the Go runtime.
   677  func Goexit() {
   678  	// Create a panic object for Goexit, so we can recognize when it might be
   679  	// bypassed by a recover().
   680  	var p _panic
   681  	p.goexit = true
   682  
   683  	p.start(sys.GetCallerPC(), unsafe.Pointer(sys.GetCallerSP()))
   684  	for {
   685  		fn, ok := p.nextDefer()
   686  		if !ok {
   687  			break
   688  		}
   689  		fn()
   690  	}
   691  
   692  	goexit1()
   693  }
   694  
   695  // Call all Error and String methods before freezing the world.
   696  // Used when crashing with panicking.
   697  func preprintpanics(p *_panic) {
   698  	defer func() {
   699  		text := "panic while printing panic value"
   700  		switch r := recover().(type) {
   701  		case nil:
   702  			// nothing to do
   703  		case string:
   704  			throw(text + ": " + r)
   705  		default:
   706  			throw(text + ": type " + toRType(efaceOf(&r)._type).string())
   707  		}
   708  	}()
   709  	for p != nil {
   710  		if p.link != nil && *efaceOf(&p.link.arg) == *efaceOf(&p.arg) {
   711  			// This panic contains the same value as the next one in the chain.
   712  			// Mark it as repanicked. We will skip printing it twice in a row.
   713  			p.link.repanicked = true
   714  			p = p.link
   715  			continue
   716  		}
   717  		switch v := p.arg.(type) {
   718  		case error:
   719  			p.arg = v.Error()
   720  		case stringer:
   721  			p.arg = v.String()
   722  		}
   723  		p = p.link
   724  	}
   725  }
   726  
   727  // Print all currently active panics. Used when crashing.
   728  // Should only be called after preprintpanics.
   729  func printpanics(p *_panic) {
   730  	if p.link != nil {
   731  		printpanics(p.link)
   732  		if p.link.repanicked {
   733  			return
   734  		}
   735  		if !p.link.goexit {
   736  			print("\t")
   737  		}
   738  	}
   739  	if p.goexit {
   740  		return
   741  	}
   742  	print("panic: ")
   743  	printpanicval(p.arg)
   744  	if p.repanicked {
   745  		print(" [recovered, repanicked]")
   746  	} else if p.recovered {
   747  		print(" [recovered]")
   748  	}
   749  	print("\n")
   750  }
   751  
   752  // readvarintUnsafe reads the uint32 in varint format starting at fd, and returns the
   753  // uint32 and a pointer to the byte following the varint.
   754  //
   755  // The implementation is the same with runtime.readvarint, except that this function
   756  // uses unsafe.Pointer for speed.
   757  func readvarintUnsafe(fd unsafe.Pointer) (uint32, unsafe.Pointer) {
   758  	var r uint32
   759  	var shift int
   760  	for {
   761  		b := *(*uint8)(fd)
   762  		fd = add(fd, unsafe.Sizeof(b))
   763  		if b < 128 {
   764  			return r + uint32(b)<<shift, fd
   765  		}
   766  		r += uint32(b&0x7F) << (shift & 31)
   767  		shift += 7
   768  		if shift > 28 {
   769  			panic("Bad varint")
   770  		}
   771  	}
   772  }
   773  
   774  // A PanicNilError happens when code calls panic(nil).
   775  //
   776  // Before Go 1.21, programs that called panic(nil) observed recover returning nil.
   777  // Starting in Go 1.21, programs that call panic(nil) observe recover returning a *PanicNilError.
   778  // Programs can change back to the old behavior by setting GODEBUG=panicnil=1.
   779  type PanicNilError struct {
   780  	// This field makes PanicNilError structurally different from
   781  	// any other struct in this package, and the _ makes it different
   782  	// from any struct in other packages too.
   783  	// This avoids any accidental conversions being possible
   784  	// between this struct and some other struct sharing the same fields,
   785  	// like happened in go.dev/issue/56603.
   786  	_ [0]*PanicNilError
   787  }
   788  
   789  func (*PanicNilError) Error() string { return "panic called with nil argument" }
   790  func (*PanicNilError) RuntimeError() {}
   791  
   792  var panicnil = &godebugInc{name: "panicnil"}
   793  
   794  // The implementation of the predeclared function panic.
   795  // The compiler emits calls to this function.
   796  //
   797  // gopanic should be an internal detail,
   798  // but widely used packages access it using linkname.
   799  // Notable members of the hall of shame include:
   800  //   - go.undefinedlabs.com/scopeagent
   801  //   - github.com/goplus/igop
   802  //
   803  // Do not remove or change the type signature.
   804  // See go.dev/issue/67401.
   805  //
   806  //go:linkname gopanic
   807  func gopanic(e any) {
   808  	if e == nil {
   809  		if debug.panicnil.Load() != 1 {
   810  			e = new(PanicNilError)
   811  		} else {
   812  			panicnil.IncNonDefault()
   813  		}
   814  	}
   815  
   816  	gp := getg()
   817  	if gp.m.curg != gp {
   818  		print("panic: ")
   819  		printpanicval(e)
   820  		print("\n")
   821  		throw("panic on system stack")
   822  	}
   823  
   824  	if gp.m.mallocing != 0 {
   825  		print("panic: ")
   826  		printpanicval(e)
   827  		print("\n")
   828  		throw("panic during malloc")
   829  	}
   830  	if gp.m.preemptoff != "" {
   831  		print("panic: ")
   832  		printpanicval(e)
   833  		print("\n")
   834  		print("preempt off reason: ")
   835  		print(gp.m.preemptoff)
   836  		print("\n")
   837  		throw("panic during preemptoff")
   838  	}
   839  	if gp.m.locks != 0 {
   840  		print("panic: ")
   841  		printpanicval(e)
   842  		print("\n")
   843  		throw("panic holding locks")
   844  	}
   845  
   846  	var p _panic
   847  	p.arg = e
   848  	p.gopanicFP = unsafe.Pointer(sys.GetCallerSP())
   849  
   850  	runningPanicDefers.Add(1)
   851  
   852  	p.start(sys.GetCallerPC(), unsafe.Pointer(sys.GetCallerSP()))
   853  	for {
   854  		fn, ok := p.nextDefer()
   855  		if !ok {
   856  			break
   857  		}
   858  		fn()
   859  	}
   860  
   861  	// If we're tracing, flush the current generation to make the trace more
   862  	// readable.
   863  	//
   864  	// TODO(aktau): Handle a panic from within traceAdvance more gracefully.
   865  	// Currently it would hang. Not handled now because it is very unlikely, and
   866  	// already unrecoverable.
   867  	if traceEnabled() {
   868  		traceAdvance(false)
   869  	}
   870  
   871  	// ran out of deferred calls - old-school panic now
   872  	// Because it is unsafe to call arbitrary user code after freezing
   873  	// the world, we call preprintpanics to invoke all necessary Error
   874  	// and String methods to prepare the panic strings before startpanic.
   875  	preprintpanics(&p)
   876  
   877  	fatalpanic(&p)   // should not return
   878  	*(*int)(nil) = 0 // not reached
   879  }
   880  
   881  // start initializes a panic to start unwinding the stack.
   882  //
   883  // If p.goexit is true, then start may return multiple times.
   884  func (p *_panic) start(pc uintptr, sp unsafe.Pointer) {
   885  	gp := getg()
   886  
   887  	// Record the caller's PC and SP, so recovery can identify panics
   888  	// that have been recovered. Also, so that if p is from Goexit, we
   889  	// can restart its defer processing loop if a recovered panic tries
   890  	// to jump past it.
   891  	p.startPC = sys.GetCallerPC()
   892  	p.startSP = unsafe.Pointer(sys.GetCallerSP())
   893  
   894  	if p.deferreturn {
   895  		p.sp = sp
   896  
   897  		if s := (*savedOpenDeferState)(gp.param); s != nil {
   898  			// recovery saved some state for us, so that we can resume
   899  			// calling open-coded defers without unwinding the stack.
   900  
   901  			gp.param = nil
   902  
   903  			p.retpc = s.retpc
   904  			p.deferBitsPtr = (*byte)(add(sp, s.deferBitsOffset))
   905  			p.slotsPtr = add(sp, s.slotsOffset)
   906  		}
   907  
   908  		return
   909  	}
   910  
   911  	p.link = gp._panic
   912  	gp._panic = (*_panic)(noescape(unsafe.Pointer(p)))
   913  
   914  	// Initialize state machine, and find the first frame with a defer.
   915  	//
   916  	// Note: We could use startPC and startSP here, but callers will
   917  	// never have defer statements themselves. By starting at their
   918  	// caller instead, we avoid needing to unwind through an extra
   919  	// frame. It also somewhat simplifies the terminating condition for
   920  	// deferreturn.
   921  	p.lr, p.fp = pc, sp
   922  	p.nextFrame()
   923  }
   924  
   925  // nextDefer returns the next deferred function to invoke, if any.
   926  //
   927  // Note: The "ok bool" result is necessary to correctly handle when
   928  // the deferred function itself was nil (e.g., "defer (func())(nil)").
   929  func (p *_panic) nextDefer() (func(), bool) {
   930  	gp := getg()
   931  
   932  	if !p.deferreturn {
   933  		if gp._panic != p {
   934  			throw("bad panic stack")
   935  		}
   936  
   937  		if p.recovered {
   938  			mcall(recovery) // does not return
   939  			throw("recovery failed")
   940  		}
   941  	}
   942  
   943  	for {
   944  		for p.deferBitsPtr != nil {
   945  			bits := *p.deferBitsPtr
   946  
   947  			// Check whether any open-coded defers are still pending.
   948  			//
   949  			// Note: We need to check this upfront (rather than after
   950  			// clearing the top bit) because it's possible that Goexit
   951  			// invokes a deferred call, and there were still more pending
   952  			// open-coded defers in the frame; but then the deferred call
   953  			// panic and invoked the remaining defers in the frame, before
   954  			// recovering and restarting the Goexit loop.
   955  			if bits == 0 {
   956  				p.deferBitsPtr = nil
   957  				break
   958  			}
   959  
   960  			// Find index of top bit set.
   961  			i := 7 - uintptr(sys.LeadingZeros8(bits))
   962  
   963  			// Clear bit and store it back.
   964  			bits &^= 1 << i
   965  			*p.deferBitsPtr = bits
   966  
   967  			return *(*func())(add(p.slotsPtr, i*goarch.PtrSize)), true
   968  		}
   969  
   970  	Recheck:
   971  		if d := gp._defer; d != nil && d.sp == uintptr(p.sp) {
   972  			if d.rangefunc {
   973  				deferconvert(d)
   974  				popDefer(gp)
   975  				goto Recheck
   976  			}
   977  
   978  			fn := d.fn
   979  
   980  			p.retpc = d.pc
   981  
   982  			// Unlink and free.
   983  			popDefer(gp)
   984  
   985  			return fn, true
   986  		}
   987  
   988  		if !p.nextFrame() {
   989  			return nil, false
   990  		}
   991  	}
   992  }
   993  
   994  // nextFrame finds the next frame that contains deferred calls, if any.
   995  func (p *_panic) nextFrame() (ok bool) {
   996  	if p.lr == 0 {
   997  		return false
   998  	}
   999  
  1000  	gp := getg()
  1001  	systemstack(func() {
  1002  		var limit uintptr
  1003  		if d := gp._defer; d != nil {
  1004  			limit = d.sp
  1005  		}
  1006  
  1007  		var u unwinder
  1008  		u.initAt(p.lr, uintptr(p.fp), 0, gp, 0)
  1009  		for {
  1010  			if !u.valid() {
  1011  				p.lr = 0
  1012  				return // ok == false
  1013  			}
  1014  
  1015  			// TODO(mdempsky): If we populate u.frame.fn.deferreturn for
  1016  			// every frame containing a defer (not just open-coded defers),
  1017  			// then we can simply loop until we find the next frame where
  1018  			// it's non-zero.
  1019  
  1020  			if u.frame.sp == limit {
  1021  				break // found a frame with linked defers
  1022  			}
  1023  
  1024  			if p.initOpenCodedDefers(u.frame.fn, unsafe.Pointer(u.frame.varp)) {
  1025  				break // found a frame with open-coded defers
  1026  			}
  1027  
  1028  			u.next()
  1029  		}
  1030  
  1031  		p.lr = u.frame.lr
  1032  		p.sp = unsafe.Pointer(u.frame.sp)
  1033  		p.fp = unsafe.Pointer(u.frame.fp)
  1034  
  1035  		ok = true
  1036  	})
  1037  
  1038  	return
  1039  }
  1040  
  1041  func (p *_panic) initOpenCodedDefers(fn funcInfo, varp unsafe.Pointer) bool {
  1042  	fd := funcdata(fn, abi.FUNCDATA_OpenCodedDeferInfo)
  1043  	if fd == nil {
  1044  		return false
  1045  	}
  1046  
  1047  	if fn.deferreturn == 0 {
  1048  		throw("missing deferreturn")
  1049  	}
  1050  
  1051  	deferBitsOffset, fd := readvarintUnsafe(fd)
  1052  	deferBitsPtr := (*uint8)(add(varp, -uintptr(deferBitsOffset)))
  1053  	if *deferBitsPtr == 0 {
  1054  		return false // has open-coded defers, but none pending
  1055  	}
  1056  
  1057  	slotsOffset, fd := readvarintUnsafe(fd)
  1058  
  1059  	p.retpc = fn.entry() + uintptr(fn.deferreturn)
  1060  	p.deferBitsPtr = deferBitsPtr
  1061  	p.slotsPtr = add(varp, -uintptr(slotsOffset))
  1062  
  1063  	return true
  1064  }
  1065  
  1066  // The implementation of the predeclared function recover.
  1067  func gorecover() any {
  1068  	gp := getg()
  1069  	p := gp._panic
  1070  	if p == nil || p.goexit || p.recovered {
  1071  		return nil
  1072  	}
  1073  
  1074  	// Check to see if the function that called recover() was
  1075  	// deferred directly from the panicking function.
  1076  	// For code like:
  1077  	//     func foo() {
  1078  	//         defer bar()
  1079  	//         panic("panic")
  1080  	//     }
  1081  	//     func bar() {
  1082  	//         recover()
  1083  	//     }
  1084  	// Normally the stack would look like this:
  1085  	//     foo
  1086  	//     runtime.gopanic
  1087  	//     bar
  1088  	//     runtime.gorecover
  1089  	//
  1090  	// However, if the function we deferred requires a wrapper
  1091  	// of some sort, we need to ignore the wrapper. In that case,
  1092  	// the stack looks like:
  1093  	//     foo
  1094  	//     runtime.gopanic
  1095  	//     wrapper
  1096  	//     bar
  1097  	//     runtime.gorecover
  1098  	// And we should also successfully recover.
  1099  	//
  1100  	// Finally, in the weird case "defer recover()", the stack looks like:
  1101  	//     foo
  1102  	//     runtime.gopanic
  1103  	//     wrapper
  1104  	//     runtime.gorecover
  1105  	// And we should not recover in that case.
  1106  	//
  1107  	// So our criteria is, there must be exactly one non-wrapper
  1108  	// frame between gopanic and gorecover.
  1109  	//
  1110  	// We don't recover this:
  1111  	//     defer func() { func() { recover() }() }
  1112  	// because there are 2 non-wrapper frames.
  1113  	//
  1114  	// We don't recover this:
  1115  	//     defer recover()
  1116  	// because there are 0 non-wrapper frames.
  1117  	canRecover := false
  1118  	systemstack(func() {
  1119  		var u unwinder
  1120  		u.init(gp, 0)
  1121  		u.next() // skip systemstack_switch
  1122  		u.next() // skip gorecover
  1123  		nonWrapperFrames := 0
  1124  	loop:
  1125  		for ; u.valid(); u.next() {
  1126  			for iu, f := newInlineUnwinder(u.frame.fn, u.symPC()); f.valid(); f = iu.next(f) {
  1127  				sf := iu.srcFunc(f)
  1128  				switch sf.funcID {
  1129  				case abi.FuncIDWrapper:
  1130  					continue
  1131  				case abi.FuncID_gopanic:
  1132  					if u.frame.fp == uintptr(p.gopanicFP) && nonWrapperFrames > 0 {
  1133  						canRecover = true
  1134  					}
  1135  					break loop
  1136  				default:
  1137  					nonWrapperFrames++
  1138  					if nonWrapperFrames > 1 {
  1139  						break loop
  1140  					}
  1141  				}
  1142  			}
  1143  		}
  1144  	})
  1145  	if !canRecover {
  1146  		return nil
  1147  	}
  1148  	p.recovered = true
  1149  	return p.arg
  1150  }
  1151  
  1152  //go:linkname sync_throw sync.throw
  1153  func sync_throw(s string) {
  1154  	throw(s)
  1155  }
  1156  
  1157  //go:linkname sync_fatal sync.fatal
  1158  func sync_fatal(s string) {
  1159  	fatal(s)
  1160  }
  1161  
  1162  //go:linkname rand_fatal crypto/rand.fatal
  1163  func rand_fatal(s string) {
  1164  	fatal(s)
  1165  }
  1166  
  1167  //go:linkname sysrand_fatal crypto/internal/sysrand.fatal
  1168  func sysrand_fatal(s string) {
  1169  	fatal(s)
  1170  }
  1171  
  1172  //go:linkname fips_fatal crypto/internal/fips140.fatal
  1173  func fips_fatal(s string) {
  1174  	fatal(s)
  1175  }
  1176  
  1177  //go:linkname maps_fatal internal/runtime/maps.fatal
  1178  func maps_fatal(s string) {
  1179  	fatal(s)
  1180  }
  1181  
  1182  //go:linkname internal_sync_throw internal/sync.throw
  1183  func internal_sync_throw(s string) {
  1184  	throw(s)
  1185  }
  1186  
  1187  //go:linkname internal_sync_fatal internal/sync.fatal
  1188  func internal_sync_fatal(s string) {
  1189  	fatal(s)
  1190  }
  1191  
  1192  //go:linkname cgroup_throw internal/runtime/cgroup.throw
  1193  func cgroup_throw(s string) {
  1194  	throw(s)
  1195  }
  1196  
  1197  // throw triggers a fatal error that dumps a stack trace and exits.
  1198  //
  1199  // throw should be used for runtime-internal fatal errors where Go itself,
  1200  // rather than user code, may be at fault for the failure.
  1201  //
  1202  // throw should be an internal detail,
  1203  // but widely used packages access it using linkname.
  1204  // Notable members of the hall of shame include:
  1205  //   - github.com/bytedance/sonic
  1206  //   - github.com/cockroachdb/pebble
  1207  //   - github.com/dgraph-io/ristretto
  1208  //   - github.com/outcaste-io/ristretto
  1209  //   - github.com/pingcap/br
  1210  //   - gvisor.dev/gvisor
  1211  //   - github.com/sagernet/gvisor
  1212  //
  1213  // Do not remove or change the type signature.
  1214  // See go.dev/issue/67401.
  1215  //
  1216  //go:linkname throw
  1217  //go:nosplit
  1218  func throw(s string) {
  1219  	// Everything throw does should be recursively nosplit so it
  1220  	// can be called even when it's unsafe to grow the stack.
  1221  	systemstack(func() {
  1222  		print("fatal error: ")
  1223  		printindented(s) // logically printpanicval(s), but avoids convTstring write barrier
  1224  		print("\n")
  1225  	})
  1226  
  1227  	fatalthrow(throwTypeRuntime)
  1228  }
  1229  
  1230  // fatal triggers a fatal error that dumps a stack trace and exits.
  1231  //
  1232  // fatal is equivalent to throw, but is used when user code is expected to be
  1233  // at fault for the failure, such as racing map writes.
  1234  //
  1235  // fatal does not include runtime frames, system goroutines, or frame metadata
  1236  // (fp, sp, pc) in the stack trace unless GOTRACEBACK=system or higher.
  1237  //
  1238  //go:nosplit
  1239  func fatal(s string) {
  1240  	// Everything fatal does should be recursively nosplit so it
  1241  	// can be called even when it's unsafe to grow the stack.
  1242  	printlock() // Prevent multiple interleaved fatal reports. See issue 69447.
  1243  	systemstack(func() {
  1244  		print("fatal error: ")
  1245  		printindented(s) // logically printpanicval(s), but avoids convTstring write barrier
  1246  		print("\n")
  1247  	})
  1248  
  1249  	fatalthrow(throwTypeUser)
  1250  	printunlock()
  1251  }
  1252  
  1253  // runningPanicDefers is non-zero while running deferred functions for panic.
  1254  // This is used to try hard to get a panic stack trace out when exiting.
  1255  var runningPanicDefers atomic.Uint32
  1256  
  1257  // panicking is non-zero when crashing the program for an unrecovered panic.
  1258  var panicking atomic.Uint32
  1259  
  1260  // paniclk is held while printing the panic information and stack trace,
  1261  // so that two concurrent panics don't overlap their output.
  1262  var paniclk mutex
  1263  
  1264  // Unwind the stack after a deferred function calls recover
  1265  // after a panic. Then arrange to continue running as though
  1266  // the caller of the deferred function returned normally.
  1267  //
  1268  // However, if unwinding the stack would skip over a Goexit call, we
  1269  // return into the Goexit loop instead, so it can continue processing
  1270  // defers instead.
  1271  func recovery(gp *g) {
  1272  	p := gp._panic
  1273  	pc, sp, fp := p.retpc, uintptr(p.sp), uintptr(p.fp)
  1274  	p0, saveOpenDeferState := p, p.deferBitsPtr != nil && *p.deferBitsPtr != 0
  1275  
  1276  	// The linker records the f-relative address of a call to deferreturn in f's funcInfo.
  1277  	// Assuming a "normal" call to recover() inside one of f's deferred functions
  1278  	// invoked for a panic, that is the desired PC for exiting f.
  1279  	f := findfunc(pc)
  1280  	if f.deferreturn == 0 {
  1281  		throw("no deferreturn")
  1282  	}
  1283  	gotoPc := f.entry() + uintptr(f.deferreturn)
  1284  
  1285  	// Unwind the panic stack.
  1286  	for ; p != nil && uintptr(p.startSP) < sp; p = p.link {
  1287  		// Don't allow jumping past a pending Goexit.
  1288  		// Instead, have its _panic.start() call return again.
  1289  		//
  1290  		// TODO(mdempsky): In this case, Goexit will resume walking the
  1291  		// stack where it left off, which means it will need to rewalk
  1292  		// frames that we've already processed.
  1293  		//
  1294  		// There's a similar issue with nested panics, when the inner
  1295  		// panic supersedes the outer panic. Again, we end up needing to
  1296  		// walk the same stack frames.
  1297  		//
  1298  		// These are probably pretty rare occurrences in practice, and
  1299  		// they don't seem any worse than the existing logic. But if we
  1300  		// move the unwinding state into _panic, we could detect when we
  1301  		// run into where the last panic started, and then just pick up
  1302  		// where it left off instead.
  1303  		//
  1304  		// With how subtle defer handling is, this might not actually be
  1305  		// worthwhile though.
  1306  		if p.goexit {
  1307  			gotoPc, sp = p.startPC, uintptr(p.startSP)
  1308  			saveOpenDeferState = false // goexit is unwinding the stack anyway
  1309  			break
  1310  		}
  1311  
  1312  		runningPanicDefers.Add(-1)
  1313  	}
  1314  	gp._panic = p
  1315  
  1316  	if p == nil { // must be done with signal
  1317  		gp.sig = 0
  1318  	}
  1319  
  1320  	if gp.param != nil {
  1321  		throw("unexpected gp.param")
  1322  	}
  1323  	if saveOpenDeferState {
  1324  		// If we're returning to deferreturn and there are more open-coded
  1325  		// defers for it to call, save enough state for it to be able to
  1326  		// pick up where p0 left off.
  1327  		gp.param = unsafe.Pointer(&savedOpenDeferState{
  1328  			retpc: p0.retpc,
  1329  
  1330  			// We need to save deferBitsPtr and slotsPtr too, but those are
  1331  			// stack pointers. To avoid issues around heap objects pointing
  1332  			// to the stack, save them as offsets from SP.
  1333  			deferBitsOffset: uintptr(unsafe.Pointer(p0.deferBitsPtr)) - uintptr(p0.sp),
  1334  			slotsOffset:     uintptr(p0.slotsPtr) - uintptr(p0.sp),
  1335  		})
  1336  	}
  1337  
  1338  	// TODO(mdempsky): Currently, we rely on frames containing "defer"
  1339  	// to end with "CALL deferreturn; RET". This allows deferreturn to
  1340  	// finish running any pending defers in the frame.
  1341  	//
  1342  	// But we should be able to tell whether there are still pending
  1343  	// defers here. If there aren't, we can just jump directly to the
  1344  	// "RET" instruction. And if there are, we don't need an actual
  1345  	// "CALL deferreturn" instruction; we can simulate it with something
  1346  	// like:
  1347  	//
  1348  	//	if usesLR {
  1349  	//		lr = pc
  1350  	//	} else {
  1351  	//		sp -= sizeof(pc)
  1352  	//		*(*uintptr)(sp) = pc
  1353  	//	}
  1354  	//	pc = funcPC(deferreturn)
  1355  	//
  1356  	// So that we effectively tail call into deferreturn, such that it
  1357  	// then returns to the simple "RET" epilogue. That would save the
  1358  	// overhead of the "deferreturn" call when there aren't actually any
  1359  	// pending defers left, and shrink the TEXT size of compiled
  1360  	// binaries. (Admittedly, both of these are modest savings.)
  1361  
  1362  	// Ensure we're recovering within the appropriate stack.
  1363  	if sp != 0 && (sp < gp.stack.lo || gp.stack.hi < sp) {
  1364  		print("recover: ", hex(sp), " not in [", hex(gp.stack.lo), ", ", hex(gp.stack.hi), "]\n")
  1365  		throw("bad recovery")
  1366  	}
  1367  
  1368  	// branch directly to the deferreturn
  1369  	gp.sched.sp = sp
  1370  	gp.sched.pc = gotoPc
  1371  	gp.sched.lr = 0
  1372  	// Restore the bp on platforms that support frame pointers.
  1373  	// N.B. It's fine to not set anything for platforms that don't
  1374  	// support frame pointers, since nothing consumes them.
  1375  	switch {
  1376  	case goarch.IsAmd64 != 0:
  1377  		// on x86, fp actually points one word higher than the top of
  1378  		// the frame since the return address is saved on the stack by
  1379  		// the caller
  1380  		gp.sched.bp = fp - 2*goarch.PtrSize
  1381  	case goarch.IsArm64 != 0:
  1382  		// on arm64, the architectural bp points one word higher
  1383  		// than the sp. fp is totally useless to us here, because it
  1384  		// only gets us to the caller's fp.
  1385  		gp.sched.bp = sp - goarch.PtrSize
  1386  	}
  1387  	gogo(&gp.sched)
  1388  }
  1389  
  1390  // fatalthrow implements an unrecoverable runtime throw. It freezes the
  1391  // system, prints stack traces starting from its caller, and terminates the
  1392  // process.
  1393  //
  1394  //go:nosplit
  1395  func fatalthrow(t throwType) {
  1396  	pc := sys.GetCallerPC()
  1397  	sp := sys.GetCallerSP()
  1398  	gp := getg()
  1399  
  1400  	if gp.m.throwing == throwTypeNone {
  1401  		gp.m.throwing = t
  1402  	}
  1403  
  1404  	// Switch to the system stack to avoid any stack growth, which may make
  1405  	// things worse if the runtime is in a bad state.
  1406  	systemstack(func() {
  1407  		if isSecureMode() {
  1408  			exit(2)
  1409  		}
  1410  
  1411  		startpanic_m()
  1412  
  1413  		if dopanic_m(gp, pc, sp, nil) {
  1414  			// crash uses a decent amount of nosplit stack and we're already
  1415  			// low on stack in throw, so crash on the system stack (unlike
  1416  			// fatalpanic).
  1417  			crash()
  1418  		}
  1419  
  1420  		exit(2)
  1421  	})
  1422  
  1423  	*(*int)(nil) = 0 // not reached
  1424  }
  1425  
  1426  // fatalpanic implements an unrecoverable panic. It is like fatalthrow, except
  1427  // that if msgs != nil, fatalpanic also prints panic messages and decrements
  1428  // runningPanicDefers once main is blocked from exiting.
  1429  //
  1430  //go:nosplit
  1431  func fatalpanic(msgs *_panic) {
  1432  	pc := sys.GetCallerPC()
  1433  	sp := sys.GetCallerSP()
  1434  	gp := getg()
  1435  	var docrash bool
  1436  	// Switch to the system stack to avoid any stack growth, which
  1437  	// may make things worse if the runtime is in a bad state.
  1438  	systemstack(func() {
  1439  		if startpanic_m() && msgs != nil {
  1440  			// There were panic messages and startpanic_m
  1441  			// says it's okay to try to print them.
  1442  
  1443  			// startpanic_m set panicking, which will
  1444  			// block main from exiting, so now OK to
  1445  			// decrement runningPanicDefers.
  1446  			runningPanicDefers.Add(-1)
  1447  
  1448  			printpanics(msgs)
  1449  		}
  1450  
  1451  		// If this panic is the result of a synctest bubble deadlock,
  1452  		// print stacks for the goroutines in the bubble.
  1453  		var bubble *synctestBubble
  1454  		if de, ok := msgs.arg.(synctestDeadlockError); ok {
  1455  			bubble = de.bubble
  1456  		}
  1457  
  1458  		docrash = dopanic_m(gp, pc, sp, bubble)
  1459  	})
  1460  
  1461  	if docrash {
  1462  		// By crashing outside the above systemstack call, debuggers
  1463  		// will not be confused when generating a backtrace.
  1464  		// Function crash is marked nosplit to avoid stack growth.
  1465  		crash()
  1466  	}
  1467  
  1468  	systemstack(func() {
  1469  		exit(2)
  1470  	})
  1471  
  1472  	*(*int)(nil) = 0 // not reached
  1473  }
  1474  
  1475  // startpanic_m prepares for an unrecoverable panic.
  1476  //
  1477  // It returns true if panic messages should be printed, or false if
  1478  // the runtime is in bad shape and should just print stacks.
  1479  //
  1480  // It must not have write barriers even though the write barrier
  1481  // explicitly ignores writes once dying > 0. Write barriers still
  1482  // assume that g.m.p != nil, and this function may not have P
  1483  // in some contexts (e.g. a panic in a signal handler for a signal
  1484  // sent to an M with no P).
  1485  //
  1486  //go:nowritebarrierrec
  1487  func startpanic_m() bool {
  1488  	gp := getg()
  1489  	if mheap_.cachealloc.size == 0 { // very early
  1490  		print("runtime: panic before malloc heap initialized\n")
  1491  	}
  1492  	// Disallow malloc during an unrecoverable panic. A panic
  1493  	// could happen in a signal handler, or in a throw, or inside
  1494  	// malloc itself. We want to catch if an allocation ever does
  1495  	// happen (even if we're not in one of these situations).
  1496  	gp.m.mallocing++
  1497  
  1498  	// If we're dying because of a bad lock count, set it to a
  1499  	// good lock count so we don't recursively panic below.
  1500  	if gp.m.locks < 0 {
  1501  		gp.m.locks = 1
  1502  	}
  1503  
  1504  	switch gp.m.dying {
  1505  	case 0:
  1506  		// Setting dying >0 has the side-effect of disabling this G's writebuf.
  1507  		gp.m.dying = 1
  1508  		panicking.Add(1)
  1509  		lock(&paniclk)
  1510  		if debug.schedtrace > 0 || debug.scheddetail > 0 {
  1511  			schedtrace(true)
  1512  		}
  1513  		freezetheworld()
  1514  		return true
  1515  	case 1:
  1516  		// Something failed while panicking.
  1517  		// Just print a stack trace and exit.
  1518  		gp.m.dying = 2
  1519  		print("panic during panic\n")
  1520  		return false
  1521  	case 2:
  1522  		// This is a genuine bug in the runtime, we couldn't even
  1523  		// print the stack trace successfully.
  1524  		gp.m.dying = 3
  1525  		print("stack trace unavailable\n")
  1526  		exit(4)
  1527  		fallthrough
  1528  	default:
  1529  		// Can't even print! Just exit.
  1530  		exit(5)
  1531  		return false // Need to return something.
  1532  	}
  1533  }
  1534  
  1535  var didothers bool
  1536  var deadlock mutex
  1537  
  1538  // gp is the crashing g running on this M, but may be a user G, while getg() is
  1539  // always g0.
  1540  // If bubble is non-nil, print the stacks for goroutines in this group as well.
  1541  func dopanic_m(gp *g, pc, sp uintptr, bubble *synctestBubble) bool {
  1542  	if gp.sig != 0 {
  1543  		signame := signame(gp.sig)
  1544  		if signame != "" {
  1545  			print("[signal ", signame)
  1546  		} else {
  1547  			print("[signal ", hex(gp.sig))
  1548  		}
  1549  		print(" code=", hex(gp.sigcode0), " addr=", hex(gp.sigcode1), " pc=", hex(gp.sigpc), "]\n")
  1550  	}
  1551  
  1552  	level, all, docrash := gotraceback()
  1553  	if level > 0 {
  1554  		if gp != gp.m.curg {
  1555  			all = true
  1556  		}
  1557  		if gp != gp.m.g0 {
  1558  			print("\n")
  1559  			goroutineheader(gp)
  1560  			traceback(pc, sp, 0, gp)
  1561  		} else if level >= 2 || gp.m.throwing >= throwTypeRuntime {
  1562  			print("\nruntime stack:\n")
  1563  			traceback(pc, sp, 0, gp)
  1564  		}
  1565  		if !didothers {
  1566  			if all {
  1567  				didothers = true
  1568  				tracebackothers(gp)
  1569  			} else if bubble != nil {
  1570  				// This panic is caused by a synctest bubble deadlock.
  1571  				// Print stacks for goroutines in the deadlocked bubble.
  1572  				tracebacksomeothers(gp, func(other *g) bool {
  1573  					return bubble == other.bubble
  1574  				})
  1575  			}
  1576  		}
  1577  
  1578  	}
  1579  	unlock(&paniclk)
  1580  
  1581  	if panicking.Add(-1) != 0 {
  1582  		// Some other m is panicking too.
  1583  		// Let it print what it needs to print.
  1584  		// Wait forever without chewing up cpu.
  1585  		// It will exit when it's done.
  1586  		lock(&deadlock)
  1587  		lock(&deadlock)
  1588  	}
  1589  
  1590  	printDebugLog()
  1591  
  1592  	return docrash
  1593  }
  1594  
  1595  // canpanic returns false if a signal should throw instead of
  1596  // panicking.
  1597  //
  1598  //go:nosplit
  1599  func canpanic() bool {
  1600  	gp := getg()
  1601  	mp := acquirem()
  1602  
  1603  	// Is it okay for gp to panic instead of crashing the program?
  1604  	// Yes, as long as it is running Go code, not runtime code,
  1605  	// and not stuck in a system call.
  1606  	if gp != mp.curg {
  1607  		releasem(mp)
  1608  		return false
  1609  	}
  1610  	// N.B. mp.locks != 1 instead of 0 to account for acquirem.
  1611  	if mp.locks != 1 || mp.mallocing != 0 || mp.throwing != throwTypeNone || mp.preemptoff != "" || mp.dying != 0 {
  1612  		releasem(mp)
  1613  		return false
  1614  	}
  1615  	status := readgstatus(gp)
  1616  	if status&^_Gscan != _Grunning || gp.syscallsp != 0 {
  1617  		releasem(mp)
  1618  		return false
  1619  	}
  1620  	if GOOS == "windows" && mp.libcallsp != 0 {
  1621  		releasem(mp)
  1622  		return false
  1623  	}
  1624  	releasem(mp)
  1625  	return true
  1626  }
  1627  
  1628  // shouldPushSigpanic reports whether pc should be used as sigpanic's
  1629  // return PC (pushing a frame for the call). Otherwise, it should be
  1630  // left alone so that LR is used as sigpanic's return PC, effectively
  1631  // replacing the top-most frame with sigpanic. This is used by
  1632  // preparePanic.
  1633  func shouldPushSigpanic(gp *g, pc, lr uintptr) bool {
  1634  	if pc == 0 {
  1635  		// Probably a call to a nil func. The old LR is more
  1636  		// useful in the stack trace. Not pushing the frame
  1637  		// will make the trace look like a call to sigpanic
  1638  		// instead. (Otherwise the trace will end at sigpanic
  1639  		// and we won't get to see who faulted.)
  1640  		return false
  1641  	}
  1642  	// If we don't recognize the PC as code, but we do recognize
  1643  	// the link register as code, then this assumes the panic was
  1644  	// caused by a call to non-code. In this case, we want to
  1645  	// ignore this call to make unwinding show the context.
  1646  	//
  1647  	// If we running C code, we're not going to recognize pc as a
  1648  	// Go function, so just assume it's good. Otherwise, traceback
  1649  	// may try to read a stale LR that looks like a Go code
  1650  	// pointer and wander into the woods.
  1651  	if gp.m.incgo || findfunc(pc).valid() {
  1652  		// This wasn't a bad call, so use PC as sigpanic's
  1653  		// return PC.
  1654  		return true
  1655  	}
  1656  	if findfunc(lr).valid() {
  1657  		// This was a bad call, but the LR is good, so use the
  1658  		// LR as sigpanic's return PC.
  1659  		return false
  1660  	}
  1661  	// Neither the PC or LR is good. Hopefully pushing a frame
  1662  	// will work.
  1663  	return true
  1664  }
  1665  
  1666  // isAbortPC reports whether pc is the program counter at which
  1667  // runtime.abort raises a signal.
  1668  //
  1669  // It is nosplit because it's part of the isgoexception
  1670  // implementation.
  1671  //
  1672  //go:nosplit
  1673  func isAbortPC(pc uintptr) bool {
  1674  	f := findfunc(pc)
  1675  	if !f.valid() {
  1676  		return false
  1677  	}
  1678  	return f.funcID == abi.FuncID_abort
  1679  }
  1680  

View as plain text