Source file test/fixedbugs/issue82708.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 82708: the make+copy optimization must not evaluate the
     8  // copy source before the make has checked its length.
     9  
    10  package main
    11  
    12  import (
    13  	"fmt"
    14  	"strings"
    15  )
    16  
    17  var calls int
    18  var sink []int
    19  
    20  //go:noinline
    21  func src() []int {
    22  	calls++
    23  	return []int{1, 2, 3}
    24  }
    25  
    26  //go:noinline
    27  func nilsrc() []int {
    28  	var p *int
    29  	return []int{*p}
    30  }
    31  
    32  func expectMakePanic(name string, f func()) {
    33  	defer func() {
    34  		r := recover()
    35  		if r == nil {
    36  			panic(name + ": no panic")
    37  		}
    38  		if s := fmt.Sprint(r); !strings.Contains(s, "makeslice: len out of range") {
    39  			panic(name + ": wrong panic: " + s)
    40  		}
    41  	}()
    42  	f()
    43  }
    44  
    45  func main() {
    46  	n := -1
    47  
    48  	expectMakePanic("call", func() {
    49  		m := make([]int, n)
    50  		copy(m, src())
    51  		sink = m
    52  	})
    53  	if calls != 0 {
    54  		panic(fmt.Sprintf("src called %d times, want 0", calls))
    55  	}
    56  
    57  	expectMakePanic("nil deref", func() {
    58  		m := make([]int, n)
    59  		copy(m, nilsrc())
    60  		sink = m
    61  	})
    62  
    63  	expectMakePanic("slice expr", func() {
    64  		var s []int
    65  		m := make([]int, n)
    66  		copy(m, s[10:])
    67  		sink = m
    68  	})
    69  
    70  	expectMakePanic("deref", func() {
    71  		var p *[]int
    72  		m := make([]int, n)
    73  		copy(m, *p)
    74  		sink = m
    75  	})
    76  
    77  	expectMakePanic("receive", func() {
    78  		ch := make(chan []int, 1)
    79  		ch <- []int{1}
    80  		defer func() {
    81  			if len(ch) != 1 {
    82  				panic("value received from channel")
    83  			}
    84  		}()
    85  		m := make([]int, n)
    86  		copy(m, <-ch)
    87  		sink = m
    88  	})
    89  }
    90  

View as plain text