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

View as plain text