]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/cgo/internal/testerrors/ptr_test.go
149445899fee0b0e2496812e01153283b5f9fb12
[gostls13.git] / src / cmd / cgo / internal / testerrors / ptr_test.go
1 // Copyright 2015 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 // Tests that cgo detects invalid pointer passing at runtime.
6
7 package errorstest
8
9 import (
10         "bytes"
11         "flag"
12         "fmt"
13         "internal/testenv"
14         "os"
15         "os/exec"
16         "path/filepath"
17         "runtime"
18         "strings"
19         "sync/atomic"
20         "testing"
21 )
22
23 var tmp = flag.String("tmp", "", "use `dir` for temporary files and do not clean up")
24
25 // ptrTest is the tests without the boilerplate.
26 type ptrTest struct {
27         name      string   // for reporting
28         c         string   // the cgo comment
29         c1        string   // cgo comment forced into non-export cgo file
30         imports   []string // a list of imports
31         support   string   // supporting functions
32         body      string   // the body of the main function
33         extra     []extra  // extra files
34         fail      bool     // whether the test should fail
35         expensive bool     // whether the test requires the expensive check
36 }
37
38 type extra struct {
39         name     string
40         contents string
41 }
42
43 var ptrTests = []ptrTest{
44         {
45                 // Passing a pointer to a struct that contains a Go pointer.
46                 name: "ptr1",
47                 c:    `typedef struct s1 { int *p; } s1; void f1(s1 *ps) {}`,
48                 body: `C.f1(&C.s1{new(C.int)})`,
49                 fail: true,
50         },
51         {
52                 // Passing a pointer to a struct that contains a Go pointer.
53                 name: "ptr2",
54                 c:    `typedef struct s2 { int *p; } s2; void f2(s2 *ps) {}`,
55                 body: `p := &C.s2{new(C.int)}; C.f2(p)`,
56                 fail: true,
57         },
58         {
59                 // Passing a pointer to an int field of a Go struct
60                 // that (irrelevantly) contains a Go pointer.
61                 name: "ok1",
62                 c:    `struct s3 { int i; int *p; }; void f3(int *p) {}`,
63                 body: `p := &C.struct_s3{i: 0, p: new(C.int)}; C.f3(&p.i)`,
64                 fail: false,
65         },
66         {
67                 // Passing a pointer to a pointer field of a Go struct.
68                 name: "ptrfield",
69                 c:    `struct s4 { int i; int *p; }; void f4(int **p) {}`,
70                 body: `p := &C.struct_s4{i: 0, p: new(C.int)}; C.f4(&p.p)`,
71                 fail: true,
72         },
73         {
74                 // Passing a pointer to a pointer field of a Go
75                 // struct, where the field does not contain a Go
76                 // pointer, but another field (irrelevantly) does.
77                 name: "ptrfieldok",
78                 c:    `struct s5 { int *p1; int *p2; }; void f5(int **p) {}`,
79                 body: `p := &C.struct_s5{p1: nil, p2: new(C.int)}; C.f5(&p.p1)`,
80                 fail: false,
81         },
82         {
83                 // Passing the address of a slice with no Go pointers.
84                 name:    "sliceok1",
85                 c:       `void f6(void **p) {}`,
86                 imports: []string{"unsafe"},
87                 body:    `s := []unsafe.Pointer{nil}; C.f6(&s[0])`,
88                 fail:    false,
89         },
90         {
91                 // Passing the address of a slice with a Go pointer.
92                 name:    "sliceptr1",
93                 c:       `void f7(void **p) {}`,
94                 imports: []string{"unsafe"},
95                 body:    `i := 0; s := []unsafe.Pointer{unsafe.Pointer(&i)}; C.f7(&s[0])`,
96                 fail:    true,
97         },
98         {
99                 // Passing the address of a slice with a Go pointer,
100                 // where we are passing the address of an element that
101                 // is not a Go pointer.
102                 name:    "sliceptr2",
103                 c:       `void f8(void **p) {}`,
104                 imports: []string{"unsafe"},
105                 body:    `i := 0; s := []unsafe.Pointer{nil, unsafe.Pointer(&i)}; C.f8(&s[0])`,
106                 fail:    true,
107         },
108         {
109                 // Passing the address of a slice that is an element
110                 // in a struct only looks at the slice.
111                 name:    "sliceok2",
112                 c:       `void f9(void **p) {}`,
113                 imports: []string{"unsafe"},
114                 support: `type S9 struct { p *int; s []unsafe.Pointer }`,
115                 body:    `i := 0; p := &S9{p:&i, s:[]unsafe.Pointer{nil}}; C.f9(&p.s[0])`,
116                 fail:    false,
117         },
118         {
119                 // Passing the address of a slice of an array that is
120                 // an element in a struct, with a type conversion.
121                 name:    "sliceok3",
122                 c:       `void f10(void* p) {}`,
123                 imports: []string{"unsafe"},
124                 support: `type S10 struct { p *int; a [4]byte }`,
125                 body:    `i := 0; p := &S10{p:&i}; s := p.a[:]; C.f10(unsafe.Pointer(&s[0]))`,
126                 fail:    false,
127         },
128         {
129                 // Passing the address of a slice of an array that is
130                 // an element in a struct, with a type conversion.
131                 name:    "sliceok4",
132                 c:       `typedef void* PV11; void f11(PV11 p) {}`,
133                 imports: []string{"unsafe"},
134                 support: `type S11 struct { p *int; a [4]byte }`,
135                 body:    `i := 0; p := &S11{p:&i}; C.f11(C.PV11(unsafe.Pointer(&p.a[0])))`,
136                 fail:    false,
137         },
138         {
139                 // Passing the address of a static variable with no
140                 // pointers doesn't matter.
141                 name:    "varok",
142                 c:       `void f12(char** parg) {}`,
143                 support: `var hello12 = [...]C.char{'h', 'e', 'l', 'l', 'o'}`,
144                 body:    `parg := [1]*C.char{&hello12[0]}; C.f12(&parg[0])`,
145                 fail:    false,
146         },
147         {
148                 // Passing the address of a static variable with
149                 // pointers does matter.
150                 name:    "var1",
151                 c:       `void f13(char*** parg) {}`,
152                 support: `var hello13 = [...]*C.char{new(C.char)}`,
153                 body:    `parg := [1]**C.char{&hello13[0]}; C.f13(&parg[0])`,
154                 fail:    true,
155         },
156         {
157                 // Storing a Go pointer into C memory should fail.
158                 name: "barrier",
159                 c: `#include <stdlib.h>
160                     char **f14a() { return malloc(sizeof(char*)); }
161                     void f14b(char **p) {}`,
162                 body:      `p := C.f14a(); *p = new(C.char); C.f14b(p)`,
163                 fail:      true,
164                 expensive: true,
165         },
166         {
167                 // Storing a Go pointer into C memory by assigning a
168                 // large value should fail.
169                 name: "barrierstruct",
170                 c: `#include <stdlib.h>
171                     struct s15 { char *a[10]; };
172                     struct s15 *f15() { return malloc(sizeof(struct s15)); }
173                     void f15b(struct s15 *p) {}`,
174                 body:      `p := C.f15(); p.a = [10]*C.char{new(C.char)}; C.f15b(p)`,
175                 fail:      true,
176                 expensive: true,
177         },
178         {
179                 // Storing a Go pointer into C memory using a slice
180                 // copy should fail.
181                 name: "barrierslice",
182                 c: `#include <stdlib.h>
183                     struct s16 { char *a[10]; };
184                     struct s16 *f16() { return malloc(sizeof(struct s16)); }
185                     void f16b(struct s16 *p) {}`,
186                 body:      `p := C.f16(); copy(p.a[:], []*C.char{new(C.char)}); C.f16b(p)`,
187                 fail:      true,
188                 expensive: true,
189         },
190         {
191                 // A very large value uses a GC program, which is a
192                 // different code path.
193                 name: "barriergcprogarray",
194                 c: `#include <stdlib.h>
195                     struct s17 { char *a[32769]; };
196                     struct s17 *f17() { return malloc(sizeof(struct s17)); }
197                     void f17b(struct s17 *p) {}`,
198                 body:      `p := C.f17(); p.a = [32769]*C.char{new(C.char)}; C.f17b(p)`,
199                 fail:      true,
200                 expensive: true,
201         },
202         {
203                 // Similar case, with a source on the heap.
204                 name: "barriergcprogarrayheap",
205                 c: `#include <stdlib.h>
206                     struct s18 { char *a[32769]; };
207                     struct s18 *f18() { return malloc(sizeof(struct s18)); }
208                     void f18b(struct s18 *p) {}
209                     void f18c(void *p) {}`,
210                 imports:   []string{"unsafe"},
211                 body:      `p := C.f18(); n := &[32769]*C.char{new(C.char)}; p.a = *n; C.f18b(p); n[0] = nil; C.f18c(unsafe.Pointer(n))`,
212                 fail:      true,
213                 expensive: true,
214         },
215         {
216                 // A GC program with a struct.
217                 name: "barriergcprogstruct",
218                 c: `#include <stdlib.h>
219                     struct s19a { char *a[32769]; };
220                     struct s19b { struct s19a f; };
221                     struct s19b *f19() { return malloc(sizeof(struct s19b)); }
222                     void f19b(struct s19b *p) {}`,
223                 body:      `p := C.f19(); p.f = C.struct_s19a{[32769]*C.char{new(C.char)}}; C.f19b(p)`,
224                 fail:      true,
225                 expensive: true,
226         },
227         {
228                 // Similar case, with a source on the heap.
229                 name: "barriergcprogstructheap",
230                 c: `#include <stdlib.h>
231                     struct s20a { char *a[32769]; };
232                     struct s20b { struct s20a f; };
233                     struct s20b *f20() { return malloc(sizeof(struct s20b)); }
234                     void f20b(struct s20b *p) {}
235                     void f20c(void *p) {}`,
236                 imports:   []string{"unsafe"},
237                 body:      `p := C.f20(); n := &C.struct_s20a{[32769]*C.char{new(C.char)}}; p.f = *n; C.f20b(p); n.a[0] = nil; C.f20c(unsafe.Pointer(n))`,
238                 fail:      true,
239                 expensive: true,
240         },
241         {
242                 // Exported functions may not return Go pointers.
243                 name: "export1",
244                 c:    `extern unsigned char *GoFn21();`,
245                 support: `//export GoFn21
246                           func GoFn21() *byte { return new(byte) }`,
247                 body: `C.GoFn21()`,
248                 fail: true,
249         },
250         {
251                 // Returning a C pointer is fine.
252                 name: "exportok",
253                 c: `#include <stdlib.h>
254                     extern unsigned char *GoFn22();`,
255                 support: `//export GoFn22
256                           func GoFn22() *byte { return (*byte)(C.malloc(1)) }`,
257                 body: `C.GoFn22()`,
258         },
259         {
260                 // Passing a Go string is fine.
261                 name: "passstring",
262                 c: `#include <stddef.h>
263                     typedef struct { const char *p; ptrdiff_t n; } gostring23;
264                     gostring23 f23(gostring23 s) { return s; }`,
265                 imports: []string{"unsafe"},
266                 body:    `s := "a"; r := C.f23(*(*C.gostring23)(unsafe.Pointer(&s))); if *(*string)(unsafe.Pointer(&r)) != s { panic(r) }`,
267         },
268         {
269                 // Passing a slice of Go strings fails.
270                 name:    "passstringslice",
271                 c:       `void f24(void *p) {}`,
272                 imports: []string{"strings", "unsafe"},
273                 support: `type S24 struct { a [1]string }`,
274                 body:    `s := S24{a:[1]string{strings.Repeat("a", 2)}}; C.f24(unsafe.Pointer(&s.a[0]))`,
275                 fail:    true,
276         },
277         {
278                 // Exported functions may not return strings.
279                 name:    "retstring",
280                 c:       `extern void f25();`,
281                 imports: []string{"strings"},
282                 support: `//export GoStr25
283                           func GoStr25() string { return strings.Repeat("a", 2) }`,
284                 body: `C.f25()`,
285                 c1: `#include <stddef.h>
286                      typedef struct { const char *p; ptrdiff_t n; } gostring25;
287                      extern gostring25 GoStr25();
288                      void f25() { GoStr25(); }`,
289                 fail: true,
290         },
291         {
292                 // Don't check non-pointer data.
293                 // Uses unsafe code to get a pointer we shouldn't check.
294                 // Although we use unsafe, the uintptr represents an integer
295                 // that happens to have the same representation as a pointer;
296                 // that is, we are testing something that is not unsafe.
297                 name: "ptrdata1",
298                 c: `#include <stdlib.h>
299                     void f26(void* p) {}`,
300                 imports: []string{"unsafe"},
301                 support: `type S26 struct { p *int; a [8*8]byte; u uintptr }`,
302                 body:    `i := 0; p := &S26{u:uintptr(unsafe.Pointer(&i))}; q := (*S26)(C.malloc(C.size_t(unsafe.Sizeof(*p)))); *q = *p; C.f26(unsafe.Pointer(q))`,
303                 fail:    false,
304         },
305         {
306                 // Like ptrdata1, but with a type that uses a GC program.
307                 name: "ptrdata2",
308                 c: `#include <stdlib.h>
309                     void f27(void* p) {}`,
310                 imports: []string{"unsafe"},
311                 support: `type S27 struct { p *int; a [32769*8]byte; q *int; u uintptr }`,
312                 body:    `i := 0; p := S27{u:uintptr(unsafe.Pointer(&i))}; q := (*S27)(C.malloc(C.size_t(unsafe.Sizeof(p)))); *q = p; C.f27(unsafe.Pointer(q))`,
313                 fail:    false,
314         },
315         {
316                 // Check deferred pointers when they are used, not
317                 // when the defer statement is run.
318                 name: "defer1",
319                 c:    `typedef struct s28 { int *p; } s28; void f28(s28 *ps) {}`,
320                 body: `p := &C.s28{}; defer C.f28(p); p.p = new(C.int)`,
321                 fail: true,
322         },
323         {
324                 // Check a pointer to a union if the union has any
325                 // pointer fields.
326                 name:    "union1",
327                 c:       `typedef union { char **p; unsigned long i; } u29; void f29(u29 *pu) {}`,
328                 imports: []string{"unsafe"},
329                 body:    `var b C.char; p := &b; C.f29((*C.u29)(unsafe.Pointer(&p)))`,
330                 fail:    true,
331         },
332         {
333                 // Don't check a pointer to a union if the union does
334                 // not have any pointer fields.
335                 // Like ptrdata1 above, the uintptr represents an
336                 // integer that happens to have the same
337                 // representation as a pointer.
338                 name:    "union2",
339                 c:       `typedef union { unsigned long i; } u39; void f39(u39 *pu) {}`,
340                 imports: []string{"unsafe"},
341                 body:    `var b C.char; p := &b; C.f39((*C.u39)(unsafe.Pointer(&p)))`,
342                 fail:    false,
343         },
344         {
345                 // Test preemption while entering a cgo call. Issue #21306.
346                 name:    "preemptduringcall",
347                 c:       `void f30() {}`,
348                 imports: []string{"runtime", "sync"},
349                 body:    `var wg sync.WaitGroup; wg.Add(100); for i := 0; i < 100; i++ { go func(i int) { for j := 0; j < 100; j++ { C.f30(); runtime.GOMAXPROCS(i) }; wg.Done() }(i) }; wg.Wait()`,
350                 fail:    false,
351         },
352         {
353                 // Test poller deadline with cgocheck=2.  Issue #23435.
354                 name:    "deadline",
355                 c:       `#define US31 10`,
356                 imports: []string{"os", "time"},
357                 body:    `r, _, _ := os.Pipe(); r.SetDeadline(time.Now().Add(C.US31 * time.Microsecond))`,
358                 fail:    false,
359         },
360         {
361                 // Test for double evaluation of channel receive.
362                 name:    "chanrecv",
363                 c:       `void f32(char** p) {}`,
364                 imports: []string{"time"},
365                 body:    `c := make(chan []*C.char, 2); c <- make([]*C.char, 1); go func() { time.Sleep(10 * time.Second); panic("received twice from chan") }(); C.f32(&(<-c)[0]);`,
366                 fail:    false,
367         },
368         {
369                 // Test that converting the address of a struct field
370                 // to unsafe.Pointer still just checks that field.
371                 // Issue #25941.
372                 name:    "structfield",
373                 c:       `void f33(void* p) {}`,
374                 imports: []string{"unsafe"},
375                 support: `type S33 struct { p *int; a [8]byte; u uintptr }`,
376                 body:    `s := &S33{p: new(int)}; C.f33(unsafe.Pointer(&s.a))`,
377                 fail:    false,
378         },
379         {
380                 // Test that converting multiple struct field
381                 // addresses to unsafe.Pointer still just checks those
382                 // fields. Issue #25941.
383                 name:    "structfield2",
384                 c:       `void f34(void* p, int r, void* s) {}`,
385                 imports: []string{"unsafe"},
386                 support: `type S34 struct { a [8]byte; p *int; b int64; }`,
387                 body:    `s := &S34{p: new(int)}; C.f34(unsafe.Pointer(&s.a), 32, unsafe.Pointer(&s.b))`,
388                 fail:    false,
389         },
390         {
391                 // Test that second argument to cgoCheckPointer is
392                 // evaluated when a deferred function is deferred, not
393                 // when it is run.
394                 name:    "defer2",
395                 c:       `void f35(char **pc) {}`,
396                 support: `type S35a struct { s []*C.char }; type S35b struct { ps *S35a }`,
397                 body:    `p := &S35b{&S35a{[]*C.char{nil}}}; defer C.f35(&p.ps.s[0]); p.ps = nil`,
398                 fail:    false,
399         },
400         {
401                 // Test that indexing into a function call still
402                 // examines only the slice being indexed.
403                 name:    "buffer",
404                 c:       `void f36(void *p) {}`,
405                 imports: []string{"bytes", "unsafe"},
406                 body:    `var b bytes.Buffer; b.WriteString("a"); C.f36(unsafe.Pointer(&b.Bytes()[0]))`,
407                 fail:    false,
408         },
409         {
410                 // Test that bgsweep releasing a finalizer is OK.
411                 name:    "finalizer",
412                 c:       `// Nothing to declare.`,
413                 imports: []string{"os"},
414                 support: `func open37() { os.Open(os.Args[0]) }; var G37 [][]byte`,
415                 body:    `for i := 0; i < 10000; i++ { G37 = append(G37, make([]byte, 4096)); if i % 100 == 0 { G37 = nil; open37() } }`,
416                 fail:    false,
417         },
418         {
419                 // Test that converting generated struct to interface is OK.
420                 name:    "structof",
421                 c:       `// Nothing to declare.`,
422                 imports: []string{"reflect"},
423                 support: `type MyInt38 int; func (i MyInt38) Get() int { return int(i) }; type Getter38 interface { Get() int }`,
424                 body:    `t := reflect.StructOf([]reflect.StructField{{Name: "MyInt38", Type: reflect.TypeOf(MyInt38(0)), Anonymous: true}}); v := reflect.New(t).Elem(); v.Interface().(Getter38).Get()`,
425                 fail:    false,
426         },
427         {
428                 // Test that a converted address of a struct field results
429                 // in a check for just that field and not the whole struct.
430                 name:    "structfieldcast",
431                 c:       `struct S40i { int i; int* p; }; void f40(struct S40i* p) {}`,
432                 support: `type S40 struct { p *int; a C.struct_S40i }`,
433                 body:    `s := &S40{p: new(int)}; C.f40((*C.struct_S40i)(&s.a))`,
434                 fail:    false,
435         },
436 }
437
438 func TestPointerChecks(t *testing.T) {
439         testenv.MustHaveGoBuild(t)
440         testenv.MustHaveCGO(t)
441         if runtime.GOOS == "windows" {
442                 // TODO: Skip just the cases that fail?
443                 t.Skipf("some tests fail to build on %s", runtime.GOOS)
444         }
445
446         var gopath string
447         var dir string
448         if *tmp != "" {
449                 gopath = *tmp
450                 dir = ""
451         } else {
452                 d, err := os.MkdirTemp("", filepath.Base(t.Name()))
453                 if err != nil {
454                         t.Fatal(err)
455                 }
456                 dir = d
457                 gopath = d
458         }
459
460         exe := buildPtrTests(t, gopath, false)
461         exe2 := buildPtrTests(t, gopath, true)
462
463         // We (TestPointerChecks) return before the parallel subtest functions do,
464         // so we can't just defer os.RemoveAll(dir). Instead we have to wait for
465         // the parallel subtests to finish. This code looks racy but is not:
466         // the add +1 run in serial before testOne blocks. The -1 run in parallel
467         // after testOne finishes.
468         var pending int32
469         for _, pt := range ptrTests {
470                 pt := pt
471                 t.Run(pt.name, func(t *testing.T) {
472                         atomic.AddInt32(&pending, +1)
473                         defer func() {
474                                 if atomic.AddInt32(&pending, -1) == 0 {
475                                         os.RemoveAll(dir)
476                                 }
477                         }()
478                         testOne(t, pt, exe, exe2)
479                 })
480         }
481 }
482
483 func buildPtrTests(t *testing.T, gopath string, cgocheck2 bool) (exe string) {
484
485         src := filepath.Join(gopath, "src", "ptrtest")
486         if err := os.MkdirAll(src, 0777); err != nil {
487                 t.Fatal(err)
488         }
489         if err := os.WriteFile(filepath.Join(src, "go.mod"), []byte("module ptrtest"), 0666); err != nil {
490                 t.Fatal(err)
491         }
492
493         // Prepare two cgo inputs: one for standard cgo and one for //export cgo.
494         // (The latter cannot have C definitions, only declarations.)
495         var cgo1, cgo2 bytes.Buffer
496         fmt.Fprintf(&cgo1, "package main\n\n/*\n")
497         fmt.Fprintf(&cgo2, "package main\n\n/*\n")
498
499         // C code
500         for _, pt := range ptrTests {
501                 cgo := &cgo1
502                 if strings.Contains(pt.support, "//export") {
503                         cgo = &cgo2
504                 }
505                 fmt.Fprintf(cgo, "%s\n", pt.c)
506                 fmt.Fprintf(&cgo1, "%s\n", pt.c1)
507         }
508         fmt.Fprintf(&cgo1, "*/\nimport \"C\"\n\n")
509         fmt.Fprintf(&cgo2, "*/\nimport \"C\"\n\n")
510
511         // Imports
512         did1 := make(map[string]bool)
513         did2 := make(map[string]bool)
514         did1["os"] = true // for ptrTestMain
515         fmt.Fprintf(&cgo1, "import \"os\"\n")
516
517         for _, pt := range ptrTests {
518                 did := did1
519                 cgo := &cgo1
520                 if strings.Contains(pt.support, "//export") {
521                         did = did2
522                         cgo = &cgo2
523                 }
524                 for _, imp := range pt.imports {
525                         if !did[imp] {
526                                 did[imp] = true
527                                 fmt.Fprintf(cgo, "import %q\n", imp)
528                         }
529                 }
530         }
531
532         // Func support and bodies.
533         for _, pt := range ptrTests {
534                 cgo := &cgo1
535                 if strings.Contains(pt.support, "//export") {
536                         cgo = &cgo2
537                 }
538                 fmt.Fprintf(cgo, "%s\nfunc %s() {\n%s\n}\n", pt.support, pt.name, pt.body)
539         }
540
541         // Func list and main dispatch.
542         fmt.Fprintf(&cgo1, "var funcs = map[string]func() {\n")
543         for _, pt := range ptrTests {
544                 fmt.Fprintf(&cgo1, "\t%q: %s,\n", pt.name, pt.name)
545         }
546         fmt.Fprintf(&cgo1, "}\n\n")
547         fmt.Fprintf(&cgo1, "%s\n", ptrTestMain)
548
549         if err := os.WriteFile(filepath.Join(src, "cgo1.go"), cgo1.Bytes(), 0666); err != nil {
550                 t.Fatal(err)
551         }
552         if err := os.WriteFile(filepath.Join(src, "cgo2.go"), cgo2.Bytes(), 0666); err != nil {
553                 t.Fatal(err)
554         }
555
556         exeName := "ptrtest.exe"
557         if cgocheck2 {
558                 exeName = "ptrtest2.exe"
559         }
560         cmd := exec.Command("go", "build", "-o", exeName)
561         cmd.Dir = src
562         cmd.Env = append(os.Environ(), "GOPATH="+gopath)
563         if cgocheck2 {
564                 found := false
565                 for i, e := range cmd.Env {
566                         if strings.HasPrefix(e, "GOEXPERIMENT=") {
567                                 cmd.Env[i] = e + ",cgocheck2"
568                                 found = true
569                         }
570                 }
571                 if !found {
572                         cmd.Env = append(cmd.Env, "GOEXPERIMENT=cgocheck2")
573                 }
574         }
575         out, err := cmd.CombinedOutput()
576         if err != nil {
577                 t.Fatalf("go build: %v\n%s", err, out)
578         }
579
580         return filepath.Join(src, exeName)
581 }
582
583 const ptrTestMain = `
584 func main() {
585         for _, arg := range os.Args[1:] {
586                 f := funcs[arg]
587                 if f == nil {
588                         panic("missing func "+arg)
589                 }
590                 f()
591         }
592 }
593 `
594
595 var csem = make(chan bool, 16)
596
597 func testOne(t *testing.T, pt ptrTest, exe, exe2 string) {
598         t.Parallel()
599
600         // Run the tests in parallel, but don't run too many
601         // executions in parallel, to avoid overloading the system.
602         runcmd := func(cgocheck string) ([]byte, error) {
603                 csem <- true
604                 defer func() { <-csem }()
605                 x := exe
606                 if cgocheck == "2" {
607                         x = exe2
608                         cgocheck = "1"
609                 }
610                 cmd := exec.Command(x, pt.name)
611                 cmd.Env = append(os.Environ(), "GODEBUG=cgocheck="+cgocheck)
612                 return cmd.CombinedOutput()
613         }
614
615         if pt.expensive {
616                 buf, err := runcmd("1")
617                 if err != nil {
618                         t.Logf("%s", buf)
619                         if pt.fail {
620                                 t.Fatalf("test marked expensive, but failed when not expensive: %v", err)
621                         } else {
622                                 t.Errorf("failed unexpectedly with GODEBUG=cgocheck=1: %v", err)
623                         }
624                 }
625
626         }
627
628         cgocheck := ""
629         if pt.expensive {
630                 cgocheck = "2"
631         }
632
633         buf, err := runcmd(cgocheck)
634         if pt.fail {
635                 if err == nil {
636                         t.Logf("%s", buf)
637                         t.Fatalf("did not fail as expected")
638                 } else if !bytes.Contains(buf, []byte("Go pointer")) {
639                         t.Logf("%s", buf)
640                         t.Fatalf("did not print expected error (failed with %v)", err)
641                 }
642         } else {
643                 if err != nil {
644                         t.Logf("%s", buf)
645                         t.Fatalf("failed unexpectedly: %v", err)
646                 }
647
648                 if !pt.expensive {
649                         // Make sure it passes with the expensive checks.
650                         buf, err := runcmd("2")
651                         if err != nil {
652                                 t.Logf("%s", buf)
653                                 t.Fatalf("failed unexpectedly with expensive checks: %v", err)
654                         }
655                 }
656         }
657
658         if pt.fail {
659                 buf, err := runcmd("0")
660                 if err != nil {
661                         t.Logf("%s", buf)
662                         t.Fatalf("failed unexpectedly with GODEBUG=cgocheck=0: %v", err)
663                 }
664         }
665 }