Source file test/fixedbugs/issue82930.go

     1  // run
     2  
     3  // Copyright 2026 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import "runtime"
    10  
    11  // growStack uses about n KiB of stack.
    12  //
    13  //go:noinline
    14  func growStack(n int) {
    15  	var buf [1024]byte
    16  	if n > 0 {
    17  		growStack(n - 1)
    18  	}
    19  	runtime.KeepAlive(&buf)
    20  }
    21  
    22  // The iterators below are not inlined, so the compiler cannot see what
    23  // they do with the loop body, and the body escapes to the heap.
    24  
    25  // growSeq grows the stack before calling yield.
    26  //
    27  //go:noinline
    28  func growSeq() func(func(int) bool) {
    29  	return func(yield func(int) bool) {
    30  		growStack(256)
    31  		yield(0)
    32  	}
    33  }
    34  
    35  // shrinkSeq runs a GC before calling yield. Called on a goroutine that
    36  // has a large stack but uses little of it, the GC shrinks the stack.
    37  //
    38  //go:noinline
    39  func shrinkSeq() func(func(int) bool) {
    40  	return func(yield func(int) bool) {
    41  		runtime.GC()
    42  		yield(0)
    43  	}
    44  }
    45  
    46  func f(seq func() func(func(int) bool)) (r any) {
    47  	defer func() {
    48  		if recover() != nil {
    49  			r = nil // the panic escaped the loop body
    50  		}
    51  	}()
    52  	func() {
    53  		defer func() {
    54  			for range seq() {
    55  				r = recover()
    56  			}
    57  		}()
    58  		panic("boom")
    59  	}()
    60  	return r
    61  }
    62  
    63  func main() {
    64  	// Run each case on a new goroutine, whose stack starts small, so that
    65  	// growStack really grows it.
    66  	ch := make(chan any)
    67  	go func() { ch <- f(growSeq) }()
    68  	if r := <-ch; r != "boom" {
    69  		panic("grow: recover in the loop body did not recover the panic")
    70  	}
    71  
    72  	// Grow the stack first, so that the GC in shrinkSeq finds it mostly
    73  	// unused and shrinks it.
    74  	go func() {
    75  		growStack(256)
    76  		ch <- f(shrinkSeq)
    77  	}()
    78  	if r := <-ch; r != "boom" {
    79  		panic("shrink: recover in the loop body did not recover the panic")
    80  	}
    81  }
    82  

View as plain text