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

View as plain text