Source file src/runtime/testdata/testprog/gcpanicframe.go

     1  // Copyright 2026 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 main
     6  
     7  import (
     8  	"fmt"
     9  	"runtime"
    10  )
    11  
    12  func init() {
    13  	register("GCPanicFramePointer", GCPanicFramePointer)
    14  }
    15  
    16  type panicFrameBig struct {
    17  	p   *[4]int
    18  	pad [32]int // keeps the argument off the register path
    19  }
    20  
    21  var (
    22  	panicFrameSink  *[4]int
    23  	panicFrameValue int
    24  )
    25  
    26  //go:noinline
    27  func panicFrameUse(p *[4]int) { panicFrameValue = p[0] }
    28  
    29  //go:noinline
    30  func panicFrameCall(fn func()) { fn() }
    31  
    32  // panicFrameF takes its argument on the stack and lets a closure take its
    33  // address, which makes the argument a stack object. The argument is dead once
    34  // the closure has run, so the first collection frees what it points at. Goexit
    35  // then records this frame and its caller's frame in the panic, and collections
    36  // from the deferred calls in both frames must not reach the argument through
    37  // the panic's fp or sp.
    38  //
    39  //go:noinline
    40  func panicFrameF(w panicFrameBig) {
    41  	defer func() {
    42  		runtime.GC()
    43  		runtime.GC()
    44  	}()
    45  	panicFrameCall(func() { panicFrameUse(w.p) })
    46  	panicFrameSink = nil
    47  	runtime.GC()
    48  	runtime.GC()
    49  	runtime.Goexit()
    50  }
    51  
    52  func GCPanicFramePointer() {
    53  	for i := 0; i < 200; i++ {
    54  		done := make(chan struct{})
    55  		go func() {
    56  			// By the time this deferred call runs, Goexit's panic has
    57  			// moved up to this frame, so the panic's sp is this frame's
    58  			// SP. On amd64 and 386, that is the address of
    59  			// panicFrameF's dead argument. Trigger GCs to make sure GC
    60  			// can't reach the argument through the panic's sp.
    61  			defer func() {
    62  				runtime.GC()
    63  				runtime.GC()
    64  				close(done)
    65  			}()
    66  			p := new([4]int)
    67  			p[0] = i
    68  			panicFrameSink = p
    69  			panicFrameF(panicFrameBig{p: p})
    70  		}()
    71  		<-done
    72  	}
    73  	fmt.Println("OK")
    74  }
    75  

View as plain text