Source file test/fixedbugs/issue82865.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  // Issue 82865: unsafe.Pointer arithmetic guarded by a nil check must
     8  // not be lifted out of its loop. For a nil base, the lifted value is a
     9  // bad pointer that is live across the calls in the loop.
    10  
    11  package main
    12  
    13  import "unsafe"
    14  
    15  type T struct{ a, b, c, d int }
    16  
    17  type U struct {
    18  	T
    19  	s []int
    20  }
    21  
    22  // sOf returns the s field of the U that t is part of.
    23  func sOf(t *T) *[]int {
    24  	return (*[]int)(unsafe.Add(unsafe.Pointer(t), unsafe.Sizeof(T{})))
    25  }
    26  
    27  //go:noinline
    28  func first(s *[]int) int { return (*s)[0] }
    29  
    30  // grow has a large frame, so calling it on a new goroutine grows
    31  // the stack, which checks the pointers in its callers' frames.
    32  //
    33  //go:noinline
    34  func grow(i int) int {
    35  	var buf [16 << 10]byte
    36  	return use(buf[:], i)
    37  }
    38  
    39  //go:noinline
    40  func use(b []byte, i int) int { return len(b) + i&1 }
    41  
    42  //go:noinline
    43  func sum(t *T, n int) int {
    44  	r := 0
    45  	for i := 0; i < n; i++ {
    46  		if t != nil {
    47  			r += first(sOf(t))
    48  		}
    49  		r += grow(i)
    50  	}
    51  	return r
    52  }
    53  
    54  func main() {
    55  	u := &U{s: []int{1}}
    56  	for range 100 {
    57  		done := make(chan int)
    58  		go func() { done <- sum(nil, 2) + sum(&u.T, 2) }()
    59  		<-done
    60  	}
    61  }
    62  

View as plain text