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 in the panic, and the collection from the deferred
    36  // call must not reach the argument through it.
    37  //
    38  //go:noinline
    39  func panicFrameF(w panicFrameBig) {
    40  	defer func() {
    41  		runtime.GC()
    42  		runtime.GC()
    43  	}()
    44  	panicFrameCall(func() { panicFrameUse(w.p) })
    45  	panicFrameSink = nil
    46  	runtime.GC()
    47  	runtime.GC()
    48  	runtime.Goexit()
    49  }
    50  
    51  func GCPanicFramePointer() {
    52  	for i := 0; i < 200; i++ {
    53  		done := make(chan struct{})
    54  		go func() {
    55  			defer close(done)
    56  			p := new([4]int)
    57  			p[0] = i
    58  			panicFrameSink = p
    59  			panicFrameF(panicFrameBig{p: p})
    60  		}()
    61  		<-done
    62  	}
    63  	fmt.Println("OK")
    64  }
    65  

View as plain text