blob: aa7c7f516cf96ef38dc7ab1b8617e7cbf5b246e7 [file] [log] [blame]
Patrice Arruda748609c2020-06-25 12:12:21 -07001// errorcheck -0 -m -l
Dan Willemsen09eb3b12015-09-16 14:34:17 -07002
Dan Willemsen38f2dba2016-07-08 14:54:35 -07003// Copyright 2015 The Go Authors. All rights reserved.
Dan Willemsen09eb3b12015-09-16 14:34:17 -07004// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file.
6
7// Test escape analysis for function parameters.
8
9// In this test almost everything is BAD except the simplest cases
10// where input directly flows to output.
11
12package foo
13
Dan Willemsenbc60c3c2021-12-15 01:09:00 -080014func f(buf []byte) []byte { // ERROR "leaking param: buf to result ~r0 level=0$"
Dan Willemsen09eb3b12015-09-16 14:34:17 -070015 return buf
16}
17
18func g(*byte) string
19
20func h(e int) {
21 var x [32]byte // ERROR "moved to heap: x$"
Colin Cross430342c2019-09-07 08:36:04 -070022 g(&f(x[:])[0])
Dan Willemsen09eb3b12015-09-16 14:34:17 -070023}
24
25type Node struct {
26 s string
27 left, right *Node
28}
29
30func walk(np **Node) int { // ERROR "leaking param content: np"
31 n := *np
32 w := len(n.s)
33 if n == nil {
34 return 0
35 }
Colin Cross430342c2019-09-07 08:36:04 -070036 wl := walk(&n.left)
37 wr := walk(&n.right)
Dan Willemsen09eb3b12015-09-16 14:34:17 -070038 if wl < wr {
Colin Cross430342c2019-09-07 08:36:04 -070039 n.left, n.right = n.right, n.left // ERROR "ignoring self-assignment"
Dan Willemsen09eb3b12015-09-16 14:34:17 -070040 wl, wr = wr, wl
41 }
42 *np = n
43 return w + wl + wr
44}
45
46// Test for bug where func var f used prototype's escape analysis results.
Patrice Arruda748609c2020-06-25 12:12:21 -070047func prototype(xyz []string) {} // ERROR "xyz does not escape"
Dan Willemsen09eb3b12015-09-16 14:34:17 -070048func bar() {
49 var got [][]string
50 f := prototype
51 f = func(ss []string) { got = append(got, ss) } // ERROR "leaking param: ss" "func literal does not escape"
52 s := "string"
Colin Cross1f805522021-05-14 11:10:59 -070053 f([]string{s}) // ERROR "\[\]string{...} escapes to heap"
Dan Willemsen09eb3b12015-09-16 14:34:17 -070054}