Source file
src/cmd/cgo/binding_test.go
1
2
3
4
5 package main
6
7 import (
8 "go/parser"
9 "go/token"
10 "os"
11 "path/filepath"
12 "slices"
13 "strings"
14 "testing"
15 )
16
17 func TestParseAndProcessBinding(t *testing.T) {
18 t.Setenv("GOOS", "darwin")
19 t.Setenv("GOARCH", "arm64")
20 input := `package p
21
22 // #cgo LDFLAGS: ./libx.so
23 import "C"
24 import "structs"
25
26 //cgo:type S C.S
27 //cgo:type T T
28 //cgo:const MY_CONST C.MY_CONST
29 //cgo:const Other OTHER
30 //cgo:var _GlobalX C.GlobalX "libx.so"
31 //cgo:var staticY StaticY static
32 //cgo:func Add C.Add "libx.so"
33 //cgo:func _AddFloat AddFloat "./libx.so"
34 //cgo:func Puts puts libc
35 //cgo:func Strlen strlen libc
36 //cgo:func Helper helper static
37 //cgo:func _PassS PassS "libx.so"
38
39 type S struct {
40 _ structs.HostLayout
41 a int32
42 b int16
43 c int8
44 _ [1]byte
45 }
46
47 type T struct {
48 _ structs.HostLayout
49 x int64
50 }
51
52 const (
53 MY_CONST = 42
54 Other = 7
55 )
56
57 var _GlobalX int32
58
59 var staticY int32
60
61 func Add(a int32, b int32) int32
62
63 func _AddFloat(a float32, b float64) float64
64
65 func Puts(s *int8) int32
66
67 func Strlen(s *int8) uintptr
68
69 func Helper()
70
71 func _PassS(s S, t T) S
72 `
73
74 p := newPackage(nil, token.NewFileSet())
75 entry := p.parseBinding("binding.go", []byte(input))
76
77 if entry.Package != "p" {
78 t.Fatalf("Package = %q, want %q", entry.Package, "p")
79 }
80 if len(entry.LdFlags) != 1 || entry.LdFlags[0] != "./libx.so" {
81 t.Fatalf("LdFlags = %v, want [./libx.so]", entry.LdFlags)
82 }
83 if sType := entry.TypeMap["_Ctype_S"]; sType.Size != 8 || sType.Align != 4 {
84 t.Fatalf("TypeMap[_Ctype_S] = %+v, want struct of size 8 align 4", sType)
85 }
86 if len(entry.TypeGoToC) != 1 || entry.TypeGoToC["S"] != "S" {
87 t.Fatalf("TypeGoToC = %+v, want only S", entry.TypeGoToC)
88 }
89 if len(entry.Vars) != 2 || entry.Vars[0].GoName != "_GlobalX" || entry.Vars[0].CName != "GlobalX" || !entry.Vars[0].BindC ||
90 entry.Vars[1].GoName != "staticY" || !entry.Vars[1].Static || entry.Vars[1].BindC {
91 t.Fatalf("Vars = %+v, want _GlobalX, staticY", entry.Vars)
92 }
93 if len(entry.ConstCToGo) != 1 || entry.ConstCToGo["MY_CONST"] != "MY_CONST" {
94 t.Fatalf("ConstCToGo = %+v, want only MY_CONST", entry.ConstCToGo)
95 }
96 for _, name := range []string{"T", "OTHER", "StaticY", "AddFloat", "puts", "helper", "PassS"} {
97 if !entry.GoOnlyCNames[name] {
98 t.Errorf("GoOnlyCNames[%q] = false, want true", name)
99 }
100 }
101 if len(entry.Funcs) != 6 {
102 t.Fatalf("len(Funcs) = %d, want 6", len(entry.Funcs))
103 }
104 if fn := entry.Funcs[0]; fn.Name != "Add" || fn.CName != "Add" || !fn.BindC || fn.Library != "libx.so" || fn.Ret != "int32" {
105 t.Errorf("Funcs[0] = %+v", fn)
106 }
107 if fn := entry.Funcs[1]; fn.GoName != "_AddFloat" || fn.CName != "AddFloat" || fn.BindC || fn.Library != "libx.so" || fn.Ret != "float64" {
108 t.Errorf("Funcs[1] = %+v", fn)
109 }
110 if fn := entry.Funcs[2]; fn.GoName != "Puts" || fn.CName != "puts" || !fn.LibC || fn.Library != "" || fn.Static {
111 t.Errorf("Funcs[2] = %+v", fn)
112 }
113 if fn := entry.Funcs[4]; fn.GoName != "Helper" || fn.CName != "helper" || !fn.Static || fn.Library != "" || fn.LibC {
114 t.Errorf("Funcs[4] = %+v", fn)
115 }
116
117 tmpDir := t.TempDir()
118 bindingFile := filepath.Join(tmpDir, "binding.go")
119 if err := os.WriteFile(bindingFile, []byte(input), 0644); err != nil {
120 t.Fatal(err)
121 }
122 mainFile := filepath.Join(tmpDir, "main.go")
123 mainSrc := `package p
124
125 // #cgo noescape puts
126 // #cgo nocallback puts
127 import "C"
128
129 //export MyExport
130 func MyExport(a int32) int32 {
131 return a + 1
132 }
133
134 func Call(x int32) int32 {
135 C.GlobalX = C.MY_CONST
136 cs := C.CString("hi")
137 _ = cs
138 _ = C.MyExport
139 staticY = Other
140 _ = C.OTHER
141 return Add(x, 1) + int32(C.Add(C.int(x), 2))
142 }
143 `
144 if err := os.WriteFile(mainFile, []byte(mainSrc), 0644); err != nil {
145 t.Fatal(err)
146 }
147
148 origObjDir := *objDir
149 origGoarch := goarch
150 origGoos := goos
151 *objDir = tmpDir + string(filepath.Separator)
152 goarch = "arm64"
153 goos = "darwin"
154 defer func() {
155 *objDir = origObjDir
156 goarch = origGoarch
157 goos = origGoos
158 }()
159
160 p.processBinding([]string{bindingFile, mainFile})
161
162 gotypesBytes, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_gotypes.go"))
163 if err != nil {
164 t.Fatalf("reading _cgo_gotypes.go: %v", err)
165 }
166 gotypes := string(gotypesBytes)
167 for _, want := range []string{
168 `func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }`,
169 `//go:cgo_export_dynamic MyExport`,
170 `//go:cgo_export_static MyExport`,
171 `//go:linkname __cgofn_MyExport MyExport`,
172 `var _Cfpvar_fp_MyExport unsafe.Pointer = unsafe.Pointer(&__cgofn_MyExport)`,
173 `//go:linkname _cgoexp_`,
174 `_MyExport(a unsafe.Pointer)`,
175 `//go:cgo_import_dynamic _ _ "libx.so"`,
176 `//go:cgo_import_dynamic Add Add`,
177 `//go:cgo_import_dynamic AddFloat AddFloat`,
178 `//go:cgo_import_dynamic puts puts`,
179 `_var__GlobalX GlobalX`,
180 `var _Cvar__GlobalX *int32 = (*int32)(unsafe.Pointer(&__cgo_var__GlobalX))`,
181 `//go:cgo_import_static StaticY`,
182 `//go:linkname __cgo_var_staticY StaticY`,
183 `var _Cvar_staticY *int32 = (*int32)(unsafe.Pointer(&__cgo_var_staticY))`,
184 `type _Ctype_S = S`,
185 `//go:cgo_import_dynamic malloc malloc`,
186 `func _Cfunc_CString`,
187 `var _cgo_trampoline_Add byte`,
188 `func _Cfunc_Add(p0 int32, p1 int32) int32`,
189 `func Add(p0 int32, p1 int32) int32`,
190 `func _AddFloat(p0 float32, p1 float64) float64`,
191 `_Cgo_use(p0)`,
192 `_Cgo_no_callback(true)`,
193 `_Cgo_keepalive(p0)`,
194 `//go:cgo_unsafe_args`,
195 } {
196 if !strings.Contains(gotypes, want) {
197 t.Errorf("_cgo_gotypes.go missing %q:\n%s", want, gotypes)
198 }
199 }
200 for _, notWant := range []string{
201
202 `cgo_import_dynamic helper`,
203
204 `_Cfunc_AddFloat =`,
205 `type _Ctype_T`,
206 } {
207 if strings.Contains(gotypes, notWant) {
208 t.Errorf("_cgo_gotypes.go contains %q:\n%s", notWant, gotypes)
209 }
210 }
211 for line := range strings.SplitSeq(gotypes, "\n") {
212 if strings.Contains(line, "cgo_import_dynamic") && strings.Contains(line, "StaticY") {
213 t.Errorf("_cgo_gotypes.go contains dynamic import for static var StaticY: %q", line)
214 }
215 }
216
217 mainOut, err := os.ReadFile(filepath.Join(tmpDir, "main.cgobinding.go"))
218 if err != nil {
219 t.Fatal(err)
220 }
221 for _, want := range []string{
222 `(*_Cvar__GlobalX) = MY_CONST`,
223 `(*_Cvar_staticY) = Other`,
224 `_Cundef_OTHER`,
225 `_ = _Cgo_ptr(_Cfpvar_fp_MyExport)`,
226 `_Cfunc_Add(int32(x), 2)`,
227 `_Cfunc_CString("hi")`,
228 } {
229 if !strings.Contains(string(mainOut), want) {
230 t.Errorf("main.cgobinding.go missing %q:\n%s", want, mainOut)
231 }
232 }
233
234 trampBytes, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_trampolines.s"))
235 if err != nil {
236 t.Fatalf("reading _cgo_trampolines.s: %v", err)
237 }
238 tramp := string(trampBytes)
239 for _, want := range []string{
240 "_trampoline_Add(SB), NOSPLIT|NOFRAME, $0-0",
241 "CALL\t_cgo_topofstack(SB)",
242 "CALL\tAdd(SB)",
243 "_trampoline__AddFloat(SB), NOSPLIT|NOFRAME, $0-0",
244 "CALL\tAddFloat(SB)",
245 "_trampoline_Helper(SB), NOSPLIT|NOFRAME, $0-0",
246 "TEXT MyExport(SB)",
247 "CALL\tcrosscall2(SB)",
248 "CALL\thelper(SB)",
249 "_trampoline__PassS(SB), NOSPLIT|NOFRAME, $0-0",
250 "CALL\tPassS(SB)",
251 "_trampoline__cgo_malloc(SB), NOSPLIT|NOFRAME, $0-0",
252 "CALL\tmalloc(SB)",
253 } {
254 if !strings.Contains(tramp, want) {
255 t.Errorf("_cgo_trampolines.s missing %q:\n%s", want, tramp)
256 }
257 }
258 }
259
260 func TestBindingLibcAndTargetTypes(t *testing.T) {
261 origGoos := goos
262 origGoarch := goarch
263 defer func() {
264 goos = origGoos
265 goarch = origGoarch
266 }()
267
268 goos = "windows"
269 goarch = "amd64"
270 if gt, _ := primitiveCtypeToGo("_Ctype_long"); gt != "int32" {
271 t.Errorf("windows/amd64 _Ctype_long = %q, want int32", gt)
272 }
273 if gt, _ := primitiveCtypeToGo("_Ctype_ulong"); gt != "uint32" {
274 t.Errorf("windows/amd64 _Ctype_ulong = %q, want uint32", gt)
275 }
276 if gt, _ := primitiveCtypeToGo("_Ctype_size_t"); gt != "uint64" {
277 t.Errorf("windows/amd64 _Ctype_size_t = %q, want uint64", gt)
278 }
279 if dll := windowsDLLName(""); dll != "msvcrt.dll" {
280 t.Errorf("windowsDLLName(\"\") = %q, want msvcrt.dll", dll)
281 }
282
283 goos = "linux"
284 goarch = "amd64"
285 if isStandardC("libsystemd.so.0") {
286 t.Errorf("linux isStandardC(libsystemd.so.0) = true, want false")
287 }
288 if gt, _ := primitiveCtypeToGo("_Ctype_long"); gt != "int64" {
289 t.Errorf("linux/amd64 _Ctype_long = %q, want int64", gt)
290 }
291 if gt, _ := primitiveCtypeToGo("_Ctype_ulong"); gt != "uint64" {
292 t.Errorf("linux/amd64 _Ctype_ulong = %q, want uint64", gt)
293 }
294 if gt, _ := primitiveCtypeToGo("_Ctype_size_t"); gt != "uint64" {
295 t.Errorf("linux/amd64 _Ctype_size_t = %q, want uint64", gt)
296 }
297 if gt, _ := primitiveCtypeToGo("_Ctype_ssize_t"); gt != "int64" {
298 t.Errorf("linux/amd64 _Ctype_ssize_t = %q, want int64", gt)
299 }
300 if gt, _ := primitiveCtypeToGo("_Ctype_uintptr_t"); gt != "uint64" {
301 t.Errorf("linux/amd64 _Ctype_uintptr_t = %q, want uint64", gt)
302 }
303
304 goos = "linux"
305 goarch = "386"
306 if gt, _ := primitiveCtypeToGo("_Ctype_long"); gt != "int32" {
307 t.Errorf("linux/386 _Ctype_long = %q, want int32", gt)
308 }
309 if gt, _ := primitiveCtypeToGo("_Ctype_size_t"); gt != "uint32" {
310 t.Errorf("linux/386 _Ctype_size_t = %q, want uint32", gt)
311 }
312 if gt, _ := primitiveCtypeToGo("_Ctype_ssize_t"); gt != "int32" {
313 t.Errorf("linux/386 _Ctype_ssize_t = %q, want int32", gt)
314 }
315 if gt, _ := primitiveCtypeToGo("_Ctype_uintptr_t"); gt != "uint32" {
316 t.Errorf("linux/386 _Ctype_uintptr_t = %q, want uint32", gt)
317 }
318
319
320 for _, tc := range []struct {
321 os, arch string
322 want string
323 }{
324 {"linux", "arm64", "uint8"},
325 {"linux", "riscv64", "uint8"},
326 {"aix", "ppc64", "uint8"},
327 {"darwin", "arm64", "int8"},
328 {"windows", "arm64", "int8"},
329 {"linux", "amd64", "int8"},
330 } {
331 goos, goarch = tc.os, tc.arch
332 if got, _ := primitiveCtypeToGo("_Ctype_char"); got != tc.want {
333 t.Errorf("%s/%s _Ctype_char = %q, want %q", tc.os, tc.arch, got, tc.want)
334 }
335 }
336
337 tmpDir := t.TempDir()
338 b1 := filepath.Join(tmpDir, "b1.go")
339 b2 := filepath.Join(tmpDir, "b2.go")
340 if err := os.WriteFile(b1, []byte("package p\nimport \"C\"\n//cgo:func cStrlen C.strlen libc\nfunc cStrlen(s *int8) uint64\n"), 0644); err != nil {
341 t.Fatal(err)
342 }
343 if err := os.WriteFile(b2, []byte("package p\nimport \"C\"\nfunc cPuts(s *int8) int32\n//cgo:func cPuts C.puts libc\n"), 0644); err != nil {
344 t.Fatal(err)
345 }
346 origObjDir := *objDir
347 *objDir = tmpDir + string(filepath.Separator)
348 defer func() { *objDir = origObjDir }()
349 goos = "linux"
350 goarch = "amd64"
351 t.Setenv("GOOS", "linux")
352 t.Setenv("GOARCH", "amd64")
353
354 p := newPackage(nil, fset)
355 p.processBinding([]string{b1, b2})
356 gotypesBytes, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_gotypes.go"))
357 if err != nil {
358 t.Fatal(err)
359 }
360 gotypes := string(gotypesBytes)
361 if strings.Contains(gotypes, `cgo_import_dynamic _ _`) {
362 t.Errorf("_cgo_gotypes.go should not import a library for libc symbols:\n%s", gotypes)
363 }
364 if !strings.Contains(gotypes, "//go:cgo_import_dynamic strlen strlen\n") || !strings.Contains(gotypes, "//go:cgo_import_dynamic puts puts\n") {
365 t.Errorf("_cgo_gotypes.go missing 2-arg cgo_import_dynamic:\n%s", gotypes)
366 }
367 }
368
369
370
371
372 func TestBindingVarWindows(t *testing.T) {
373 tmpDir := t.TempDir()
374 bindingFile := filepath.Join(tmpDir, "binding.go")
375 if err := os.WriteFile(bindingFile, []byte(`package p
376
377 import "C"
378
379 //cgo:var _GlobalX C.GlobalX "libx.dll"
380 //cgo:var staticY StaticY static
381
382 var _GlobalX int32
383
384 var staticY int32
385
386 func Set() {
387 C.GlobalX = 1
388 staticY = 2
389 }
390 `), 0644); err != nil {
391 t.Fatal(err)
392 }
393
394 origObjDir, origGoarch, origGoos := *objDir, goarch, goos
395 defer func() { *objDir, goarch, goos = origObjDir, origGoarch, origGoos }()
396 *objDir = tmpDir + string(filepath.Separator)
397 goos, goarch = "windows", "amd64"
398 t.Setenv("GOOS", "windows")
399 t.Setenv("GOARCH", "amd64")
400
401 p := newPackage(nil, token.NewFileSet())
402 p.processBinding([]string{bindingFile})
403
404 gotypesBytes, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_gotypes.go"))
405 if err != nil {
406 t.Fatal(err)
407 }
408 gotypes := string(gotypesBytes)
409 for _, want := range []string{
410 `_var_addr__GlobalX GlobalX`,
411 `//go:linkname _Cvar__GlobalX _cgo_`,
412 "_var_addr__GlobalX\nvar _Cvar__GlobalX *int32\n",
413 `//go:cgo_import_static StaticY`,
414 `//go:linkname __cgo_var_staticY StaticY`,
415 `var _Cvar_staticY *int32 = (*int32)(unsafe.Pointer(&__cgo_var_staticY))`,
416 } {
417 if !strings.Contains(gotypes, want) {
418 t.Errorf("_cgo_gotypes.go missing %q:\n%s", want, gotypes)
419 }
420 }
421 for _, notWant := range []string{`__cgo_var__GlobalX`, `__cgo_var_addr`, `**`} {
422 if strings.Contains(gotypes, notWant) {
423 t.Errorf("_cgo_gotypes.go contains %q:\n%s", notWant, gotypes)
424 }
425 }
426
427 rewritten, err := os.ReadFile(filepath.Join(tmpDir, "binding.cgobinding.go"))
428 if err != nil {
429 t.Fatal(err)
430 }
431 for _, want := range []string{`(*_Cvar__GlobalX) = 1`, `(*_Cvar_staticY) = 2`} {
432 if !strings.Contains(string(rewritten), want) {
433 t.Errorf("binding.cgobinding.go missing %q:\n%s", want, rewritten)
434 }
435 }
436 }
437
438 func TestParseCgoPragma(t *testing.T) {
439 for _, tt := range []struct {
440 src string
441 want cgoPragma
442 ok bool
443 }{
444 {`//cgo:func F C.f "libf.so"`, cgoPragma{Kind: "func", GoName: "F", CName: "f", BindC: true, Library: "libf.so"}, true},
445 {`//cgo:func F f static`, cgoPragma{Kind: "func", GoName: "F", CName: "f", Static: true}, true},
446 {`//cgo:func F f libc`, cgoPragma{Kind: "func", GoName: "F", CName: "f", LibC: true}, true},
447 {`//cgo:func F f "static"`, cgoPragma{Kind: "func", GoName: "F", CName: "f", Library: "static"}, true},
448 {`//cgo:var V C.v libc`, cgoPragma{Kind: "var", GoName: "V", CName: "v", BindC: true, LibC: true}, true},
449 {`//cgo:type T C.struct_t`, cgoPragma{Kind: "type", GoName: "T", CName: "struct_t", BindC: true}, true},
450 {`//cgo:const K K`, cgoPragma{Kind: "const", GoName: "K", CName: "K"}, true},
451 {`//go:noinline`, cgoPragma{}, false},
452 {`// cgo:func F f libc`, cgoPragma{}, false},
453 } {
454 fset := token.NewFileSet()
455 file, err := parser.ParseFile(fset, "x.go", "package p\n"+tt.src+"\n", parser.ParseComments)
456 if err != nil {
457 t.Fatal(err)
458 }
459 got, ok := parseCgoPragma(fset, file.Comments[0].List[0])
460 got.Pos, got.TokPos, got.Text = token.Position{}, 0, ""
461 if ok != tt.ok || got != tt.want {
462 t.Errorf("parseCgoPragma(%q) = %+v, %v; want %+v, %v", tt.src, got, ok, tt.want, tt.ok)
463 }
464 }
465 }
466
467 func TestBindingScopeAndTrimpath(t *testing.T) {
468 origGoos, origGoarch, origObjDir, origTrimpath, origLdflagsSet := goos, goarch, *objDir, *trimpath, ldflagsSet
469 defer func() {
470 goos, goarch, *objDir, *trimpath, ldflagsSet = origGoos, origGoarch, origObjDir, origTrimpath, origLdflagsSet
471 }()
472 goos, goarch = "linux", "amd64"
473 ldflagsSet = false
474 t.Setenv("GOOS", "linux")
475 t.Setenv("GOARCH", "amd64")
476
477 tmpDir := t.TempDir()
478 *objDir = tmpDir + string(filepath.Separator)
479 *trimpath = tmpDir + "=>/virtual"
480
481 src := `package p
482
483 // #cgo LDFLAGS: -L${SRCDIR}/lib -lx
484 import "C"
485
486 //cgo:func Add C.Add "libx.so"
487 func Add(a int32, b int32) int32
488
489 type box struct{ Add int32 }
490
491 func UseC(x int32) int32 { return C.Add(C.int(x), 1) }
492
493 func ShadowParam(C box) int32 { return C.Add }
494
495 func ShadowLocal() int32 {
496 C := box{Add: 3}
497 return C.Add
498 }
499 `
500 srcFile := filepath.Join(tmpDir, "b.go")
501 if err := os.WriteFile(srcFile, []byte(src), 0644); err != nil {
502 t.Fatal(err)
503 }
504
505 p := newPackage(nil, token.NewFileSet())
506 p.processBinding([]string{srcFile})
507
508
509
510
511 wantFlag := "-L" + filepath.ToSlash(tmpDir) + "/lib"
512 if !slices.Equal(p.LdFlags, []string{wantFlag, "-lx"}) {
513 t.Errorf("LdFlags = %q, want %q", p.LdFlags, []string{wantFlag, "-lx"})
514 }
515 spaceDir := filepath.Join(tmpDir, "dir with space")
516 p2 := newPackage(nil, token.NewFileSet())
517 entry2 := p2.parseBindingFiles([]bindingSource{{
518 path: "/virtual/b.go",
519 origPath: filepath.Join(spaceDir, "b.go"),
520 data: []byte(src),
521 }})
522 wantSpace := []string{"-L" + filepath.ToSlash(spaceDir) + "/lib", "-lx"}
523 if !slices.Equal(entry2.LdFlags, wantSpace) {
524 t.Errorf("LdFlags with space in SRCDIR = %q, want %q", entry2.LdFlags, wantSpace)
525 }
526 if filepath.Separator == '/' {
527 bsDir := filepath.Join(tmpDir, `a\b`)
528 p3 := newPackage(nil, token.NewFileSet())
529 entry3 := p3.parseBindingFiles([]bindingSource{{
530 path: "/virtual/b.go",
531 origPath: filepath.Join(bsDir, "b.go"),
532 data: []byte(src),
533 }})
534 wantBS := []string{"-L" + bsDir + "/lib", "-lx"}
535 if !slices.Equal(entry3.LdFlags, wantBS) {
536 t.Errorf("LdFlags with backslash in SRCDIR = %q, want %q", entry3.LdFlags, wantBS)
537 }
538 }
539
540 outBytes, err := os.ReadFile(filepath.Join(tmpDir, "b.cgobinding.go"))
541 if err != nil {
542 t.Fatal(err)
543 }
544 out := string(outBytes)
545 for _, want := range []string{
546 "//line /virtual/b.go:1:1\n",
547 "return _Cfunc_Add(int32(x), 1)",
548 "func ShadowParam(C box) int32 { return C.Add }",
549 "C := box{Add: 3}\n\treturn C.Add",
550 } {
551 if !strings.Contains(out, want) {
552 t.Errorf("b.cgobinding.go missing %q:\n%s", want, out)
553 }
554 }
555 }
556
557 func TestBindingEdgeCases(t *testing.T) {
558 origGoos, origGoarch, origObjDir := goos, goarch, *objDir
559 defer func() {
560 goos, goarch, *objDir = origGoos, origGoarch, origObjDir
561 }()
562 goos, goarch = "linux", "amd64"
563 t.Setenv("GOOS", "linux")
564 t.Setenv("GOARCH", "amd64")
565
566
567
568
569
570 input := `package p
571
572 import "C"
573 import s "structs"
574 import u "unsafe"
575
576 //cgo:type Foo C.Bar
577 //cgo:const N C.N
578 //cgo:const lowerC C.lower_c
579 //cgo:var gVar C.gVar "libx.so"
580 //cgo:func TakeInline TakeInline "libx.so"
581
582 const (
583 _ = iota
584 _
585 _
586 _
587 N = iota
588 lowerC = 2
589 derived = C.lower_c * 2
590 typedN Bar = 4
591 derivedTyped = C.typed_n + 1
592 derivedSizeof = u.Sizeof(Bar(0)) + C.lower_c
593 )
594
595 //cgo:const typedN C.typed_n
596
597 type Foo struct {
598 _ s.HostLayout
599 a int64
600 b int64
601 }
602
603 type Bar int32
604
605 type MyMap map[int32]int32
606
607 var gVar int32
608
609 func TakeInline(x struct{ _ s.HostLayout; buf [C.N]byte; buf2 [derived]byte; buf3 [derivedTyped]byte; buf4 [derivedSizeof]byte; buf5 [int(u.Sizeof(Bar(0))) + int(derivedTyped)]byte; p u.Pointer }, b Bar)
610
611 func Use[gVar any](x gVar) MyMap {
612 return MyMap{gVar: 1}
613 }
614
615 func UseMap() MyMap {
616 return MyMap{gVar: 1}
617 }
618 `
619 tmpDir := t.TempDir()
620 srcFile := filepath.Join(tmpDir, "b.go")
621 if err := os.WriteFile(srcFile, []byte(input), 0644); err != nil {
622 t.Fatal(err)
623 }
624 *objDir = tmpDir + string(filepath.Separator)
625
626 p := newPackage(nil, token.NewFileSet())
627 entry := p.parseBinding(srcFile, []byte(input))
628 if got := entry.TypeMap["_Ctype_Bar"]; got.Size != 16 {
629 t.Fatalf("TypeMap[_Ctype_Bar].Size = %d, want 16", got.Size)
630 }
631 if got := entry.TypeMap["Bar"]; got.Size != 4 {
632 t.Fatalf("TypeMap[Bar].Size = %d, want 4 (must not be overwritten by C.Bar)", got.Size)
633 }
634
635 p.processBinding([]string{srcFile})
636 gotypesBytes, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_gotypes.go"))
637 if err != nil {
638 t.Fatal(err)
639 }
640 gotypes := string(gotypesBytes)
641 for _, want := range []string{
642 `import "structs"`,
643 `_ structs.HostLayout`,
644 `buf [4]byte`,
645 `buf2 [4]byte`,
646 `buf3 [5]byte`,
647 `buf4 [6]byte`,
648 `buf5 [9]byte`,
649 `p unsafe.Pointer`,
650 `_Cgo_use(p0)`,
651 } {
652 if !strings.Contains(gotypes, want) {
653 t.Errorf("_cgo_gotypes.go missing %q:\n%s", want, gotypes)
654 }
655 }
656 rewrittenBytes, err := os.ReadFile(filepath.Join(tmpDir, "b.cgobinding.go"))
657 if err != nil {
658 t.Fatal(err)
659 }
660 rewritten := string(rewrittenBytes)
661 if !strings.Contains(rewritten, "var _ u.Pointer") || !strings.Contains(rewritten, "var _ s.HostLayout") {
662 t.Errorf("b.cgobinding.go missing aliased import keeps:\n%s", rewritten)
663 }
664 if !strings.Contains(rewritten, "func Use[gVar any](x gVar)") {
665 t.Errorf("b.cgobinding.go rewrote shadowed type param gVar:\n%s", rewritten)
666 }
667 if !strings.Contains(rewritten, "return MyMap{(*_Cvar_gVar): 1}") {
668 t.Errorf("b.cgobinding.go did not rewrite key in named map composite lit:\n%s", rewritten)
669 }
670
671
672 for _, exprSrc := range []string{"^1.5", "!1", "&x", "1.5 | 2", "1 << 1.5", "-1", "1.5"} {
673 e, err := parser.ParseExpr(exprSrc)
674 if err != nil {
675 t.Fatalf("ParseExpr(%q): %v", exprSrc, err)
676 }
677 if n, ok := p.evalBindingArrayLen(e, nil); ok {
678 t.Errorf("evalBindingArrayLen(%q) = %d, want invalid", exprSrc, n)
679 }
680 }
681 for _, tc := range []struct {
682 expr string
683 want int64
684 }{
685 {"0", 0},
686 {"4", 4},
687 {"4.0", 4},
688 {"1 + 2*3", 7},
689 } {
690 e, err := parser.ParseExpr(tc.expr)
691 if err != nil {
692 t.Fatalf("ParseExpr(%q): %v", tc.expr, err)
693 }
694 if n, ok := p.evalBindingArrayLen(e, nil); !ok || n != tc.want {
695 t.Errorf("evalBindingArrayLen(%q) = (%d, %v), want (%d, true)", tc.expr, n, ok, tc.want)
696 }
697 }
698 }
699
700 func TestBindingBuiltins(t *testing.T) {
701 origGoos, origGoarch, origObjDir := goos, goarch, *objDir
702 defer func() {
703 goos, goarch, *objDir = origGoos, origGoarch, origObjDir
704 }()
705
706
707
708
709 goos, goarch = "linux", "arm64"
710 t.Setenv("GOOS", "linux")
711 t.Setenv("GOARCH", "arm64")
712 tmpDir := t.TempDir()
713 srcFile := filepath.Join(tmpDir, "b.go")
714 input := `package p
715
716 // #cgo nocallback fast_fn
717 import "C"
718 import "unsafe"
719
720 //cgo:func CString my_cstr "libfoo.so"
721 //cgo:func customMalloc malloc static
722 //cgo:func FastFn fast_fn "libfoo.so"
723
724 func CString(x int32) int32
725 func customMalloc(n uint64) unsafe.Pointer
726 func FastFn(x int32) int32
727
728 func Use() {
729 _ = C.CString("hi")
730 _ = CString(1)
731 _ = customMalloc(8)
732 _ = FastFn(2)
733 }
734 `
735 if err := os.WriteFile(srcFile, []byte(input), 0644); err != nil {
736 t.Fatal(err)
737 }
738 *objDir = tmpDir + string(filepath.Separator)
739
740 p := newPackage(nil, token.NewFileSet())
741 p.processBinding([]string{srcFile})
742
743 gotypesBytes, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_gotypes.go"))
744 if err != nil {
745 t.Fatal(err)
746 }
747 gotypes := string(gotypesBytes)
748 for _, want := range []string{
749 `type _Ctype_char = uint8`,
750 `_libc_malloc malloc`,
751 `func _Cfunc__go_CString(`,
752 `func _Cfunc_CString(`,
753 `//go:cgo_unsafe_args`,
754 `func _cgo_call__go_CString(args _cgo_arg__go_CString) int32`,
755 `_Cgo_keepalive(&args)`,
756 } {
757 if !strings.Contains(gotypes, want) {
758 t.Errorf("_cgo_gotypes.go missing %q:\n%s", want, gotypes)
759 }
760 }
761 }
762
763 func TestDynloadBinding(t *testing.T) {
764 t.Setenv("GOOS", "linux")
765 t.Setenv("GOARCH", "amd64")
766 tmpDir := t.TempDir()
767 src := filepath.Join(tmpDir, "lib.go")
768 if err := os.WriteFile(src, []byte(`package p
769
770 import "C"
771 import cgo "runtime/cgo"
772 import _ "runtime/cgo"
773
774 //cgo:dynload Lib
775 //cgo:func Lib.Compute compute
776 //cgo:var Lib.Counter counter
777 //cgo:func Lib.Reset compute_reset
778
779 //go:noinline
780 func helper() int { return 1 }
781
782 type Lib struct {
783 cgo.Library
784 name string
785 }
786
787 func (*Lib) Compute(a, b int32) int32
788
789 func (*Lib) Counter() *int32
790
791 func (l *Lib) Reset()
792
793 func (l *Lib) Name() string { return l.name }
794 `), 0644); err != nil {
795 t.Fatal(err)
796 }
797 origObjDir, origGoos, origGoarch := *objDir, goos, goarch
798 *objDir = tmpDir + string(filepath.Separator)
799 goos, goarch = "linux", "amd64"
800 defer func() { *objDir, goos, goarch = origObjDir, origGoos, origGoarch }()
801
802 p := newPackage(nil, token.NewFileSet())
803 p.processBinding([]string{src})
804
805 gotypes, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_gotypes.go"))
806 if err != nil {
807 t.Fatal(err)
808 }
809 for _, want := range []string{
810 `//go:linkname _cgo_register_library runtime/cgo.registerLibrary`,
811 `//go:linkname _cgo_library_symbol runtime/cgo.librarySymbol`,
812 `func _cgo_register_libraries() bool {
813 _cgo_register_library((*Lib)(nil), []string{"compute", "counter", "compute_reset"})
814 return true
815 }
816
817 var _ = _cgo_register_libraries()`,
818 `func (_cgo_recv *Lib) Counter() *int32 {
819 return (*int32)(_cgo_library_symbol(&_cgo_recv.Library, 1))
820 }`,
821 `type _cgo_arg__dyn3_Lib_Compute struct {
822 fn uintptr
823 p0 int32`,
824 `func (_cgo_recv *Lib) Compute(p0 int32, p1 int32) int32 {
825 return _Cfunc__dyn3_Lib_Compute(uintptr(_cgo_library_symbol(&_cgo_recv.Library, 0)), p0, p1)
826 }`,
827 `func (_cgo_recv *Lib) Reset() {
828 _Cfunc__dyn3_Lib_Reset(uintptr(_cgo_library_symbol(&_cgo_recv.Library, 2)))
829 }`,
830 } {
831 if !strings.Contains(string(gotypes), want) {
832 t.Errorf("_cgo_gotypes.go missing %q:\n%s", want, gotypes)
833 }
834 }
835 if strings.Contains(string(gotypes), "cgo_import_dynamic") {
836 t.Errorf("_cgo_gotypes.go has dynamic imports for //cgo:dynload symbols:\n%s", gotypes)
837 }
838
839
840
841
842
843 rewritten, err := os.ReadFile(filepath.Join(tmpDir, "lib.cgobinding.go"))
844 if err != nil {
845 t.Fatal(err)
846 }
847 for _, want := range []string{
848 "\nimport _ \"runtime/cgo\"; var _ = _cgo_register_libraries()\n",
849 "\n//go:noinline\nfunc helper() int { return 1 }\n",
850 } {
851 if !strings.Contains(string(rewritten), want) {
852 t.Errorf("lib.cgobinding.go missing %q:\n%s", want, rewritten)
853 }
854 }
855
856 out, err := os.ReadFile(filepath.Join(tmpDir, "lib.cgobinding.go"))
857 if err != nil {
858 t.Fatal(err)
859 }
860 if strings.Contains(string(out), "Compute(a, b int32)") || strings.Contains(string(out), "Counter() *int32") || !strings.Contains(string(out), "Name() string") {
861 t.Errorf("lib.cgobinding.go should keep only unbound methods:\n%s", out)
862 }
863
864 tramp, err := os.ReadFile(filepath.Join(tmpDir, "_cgo_trampolines.s"))
865 if err != nil {
866 t.Fatal(err)
867 }
868 for _, want := range []string{"_trampoline__dyn3_Lib_Compute(SB)", "MOVQ\t0(R12), R11", "CALL\tR11"} {
869 if !strings.Contains(string(tramp), want) {
870 t.Errorf("_cgo_trampolines.s missing %q:\n%s", want, tramp)
871 }
872 }
873 }
874
875 func TestBindingLdflagsPreamble(t *testing.T) {
876 origGoos, origGoarch := goos, goarch
877 defer func() { goos, goarch = origGoos, origGoarch }()
878 t.Setenv("GOOS", "darwin")
879 t.Setenv("GOARCH", "arm64")
880
881 input := `package p
882
883 // #cgo LDFLAGS: -L${SRCDIR}/lib
884 // #cgo darwin LDFLAGS: -lmac
885 // #cgo linux LDFLAGS: -llinux
886 import "C"
887
888 // #cgo LDFLAGS: -lnotpreamble
889
890 //cgo:func F f libc
891 func F()
892 `
893 dir := filepath.Join("some", "dir")
894 p := newPackage(nil, fset)
895 goos, goarch = "darwin", "arm64"
896 entry := p.parseBinding(filepath.Join(dir, "binding.go"), []byte(input))
897 want := []string{"-L" + filepath.ToSlash(dir) + "/lib", "-lmac"}
898 if !slices.Equal(entry.LdFlags, want) {
899 t.Errorf("LdFlags = %q, want %q", entry.LdFlags, want)
900 }
901 }
902
903 func TestDynLibName(t *testing.T) {
904 origGoos := goos
905 defer func() { goos = origGoos }()
906 for _, tt := range []struct {
907 goos, lib, want string
908 }{
909 {"darwin", "/usr/lib/libobjc.A.dylib", "/usr/lib/libobjc.A.dylib"},
910 {"darwin", "@rpath/libfoo.dylib", "@rpath/libfoo.dylib"},
911 {"ios", "@loader_path/../lib/libfoo.dylib", "@loader_path/../lib/libfoo.dylib"},
912 {"darwin", "./libfoo.dylib", "libfoo.dylib"},
913 {"darwin", "lib/libfoo.dylib", "libfoo.dylib"},
914 {"linux", "/usr/lib/libfoo.so.1", "libfoo.so.1"},
915 {"linux", "./libx.so", "libx.so"},
916 } {
917 goos = tt.goos
918 if got := dynLibName(tt.lib); got != tt.want {
919 t.Errorf("%s: dynLibName(%q) = %q, want %q", tt.goos, tt.lib, got, tt.want)
920 }
921 }
922 }
923
924 func TestCTypeError(t *testing.T) {
925 types := map[string]BindingType{
926 "_Ctype_struct_ok": {Name: "_Ctype_struct_ok", Def: "struct { _ structs.HostLayout; a int32; p *byte }"},
927 "_Ctype_struct_bad": {Name: "_Ctype_struct_bad", Def: "struct { _ structs.HostLayout; s []byte }"},
928 "_Ctype_struct_rec": {Name: "_Ctype_struct_rec", Def: "struct { _ structs.HostLayout; next *_Ctype_struct_rec }"},
929 "_Ctype_struct_nohl": {Name: "_Ctype_struct_nohl", Def: "struct { a int32 }"},
930 "_Ctype_struct_opaque": {Name: "_Ctype_struct_opaque", Def: "struct { _ _cgopackage.Incomplete }"},
931 "_Ctype_struct_inner": {Name: "_Ctype_struct_inner", Def: "struct { _ structs.HostLayout; p *_Ctype_struct_nohl }"},
932 }
933 for _, tt := range []struct {
934 typ string
935 want string
936 }{
937 {"int32", ""},
938 {"*int8", ""},
939 {"unsafe.Pointer", ""},
940 {"uintptr", ""},
941 {"bool", ""},
942 {"complex128", ""},
943 {"[0]byte", ""},
944 {"[4]float32", ""},
945 {"struct{}", ""},
946 {"struct { _ structs.HostLayout; x int32; y [2]uint8 }", ""},
947 {"struct { _ structs.HostLayout; s struct { _ structs.HostLayout; x int32 } }", ""},
948 {"[2]struct { _ structs.HostLayout; x int32 }", ""},
949 {"*struct { _ structs.HostLayout; x int32 }", ""},
950 {"**struct { _ structs.HostLayout; x int32 }", ""},
951 {"_Ctype_struct_ok", ""},
952 {"*_Ctype_struct_rec", ""},
953 {"_Ctype_struct_unknown", ""},
954 {"*_Ctype_struct_opaque", ""},
955 {"*struct { _ _cgopackage.Incomplete }", ""},
956 {"string", "Go string"},
957 {"*string", "Go string"},
958 {"[]byte", "Go slice"},
959 {"*[]int32", "Go slice"},
960 {"[2][]byte", "Go slice"},
961 {"map[int32]int32", "Go map"},
962 {"*map[int32]int32", "Go map"},
963 {"chan int32", "Go channel"},
964 {"[3]chan int32", "Go channel"},
965 {"func()", "Go func value"},
966 {"*func()", "Go func value"},
967 {"interface{}", "Go interface"},
968 {"[1]interface{}", "Go interface"},
969 {"any", "Go interface"},
970 {"error", "Go interface"},
971 {"L[int32]", "generic"},
972 {"*M[int32, int64]", "generic"},
973 {"struct { _ structs.HostLayout; s string }", "Go string"},
974 {"struct { _ structs.HostLayout; f func() }", "Go func value"},
975 {"[2]struct { _ structs.HostLayout; m map[int32]int32 }", "Go map"},
976 {"*struct { _ structs.HostLayout; s []byte }", "Go slice"},
977 {"...int32", "variadic"},
978 {"_Ctype_struct_bad", "Go slice"},
979 {"*_Ctype_struct_bad", "Go slice"},
980 {"struct { x int32 }", "structs.HostLayout"},
981 {"struct { _ structs.HostLayout; s struct { x int32 } }", "structs.HostLayout"},
982 {"[2]struct { x int32 }", "structs.HostLayout"},
983 {"*struct { x int32 }", "structs.HostLayout"},
984 {"**struct { x int32 }", "structs.HostLayout"},
985 {"struct { _ structs.HostLayout; p *struct { x int32 } }", "structs.HostLayout"},
986 {"_Ctype_struct_nohl", "structs.HostLayout"},
987 {"*_Ctype_struct_nohl", "structs.HostLayout"},
988 {"_Ctype_struct_inner", "structs.HostLayout"},
989 {"_Ctype_struct_opaque", "incomplete"},
990 {"struct { _ _cgopackage.Incomplete }", "incomplete"},
991 {"[1]_Ctype_struct_opaque", "incomplete"},
992 {"struct { _ structs.HostLayout; o _Ctype_struct_opaque }", "incomplete"},
993 } {
994 got := cTypeError(tt.typ, types)
995 if (got == "") != (tt.want == "") || !strings.Contains(got, tt.want) {
996 t.Errorf("cTypeError(%q) = %q, want error containing %q", tt.typ, got, tt.want)
997 }
998 }
999 }
1000
1001
1002
1003
1004
1005 func TestBindingNamedTypeChecks(t *testing.T) {
1006 origGoos, origGoarch := goos, goarch
1007 defer func() { goos, goarch = origGoos, origGoarch }()
1008 goos, goarch = "linux", "amd64"
1009 t.Setenv("GOOS", "linux")
1010 t.Setenv("GOARCH", "amd64")
1011
1012 input := `package p
1013
1014 import "C"
1015 import "runtime/cgo"
1016 import "structs"
1017
1018 //cgo:type Node C.node
1019 //cgo:type Opaque C.opaque
1020 //cgo:func Walk walk "libx.so"
1021
1022 type Node struct {
1023 _ structs.HostLayout
1024 next *Node
1025 val int32
1026 kids [2]Pair
1027 }
1028
1029 type Pair struct {
1030 _ structs.HostLayout
1031 a, b int32
1032 }
1033
1034 type Opaque struct{ _ cgo.Incomplete }
1035
1036 func Walk(n *Node, o *Opaque, p Pair) int32
1037 `
1038 p := newPackage(nil, token.NewFileSet())
1039 entry := p.parseBinding("binding.go", []byte(input))
1040 if node := entry.TypeMap["Node"]; node.Size != 32 || node.Align != 8 || !node.HasPointers {
1041 t.Errorf("TypeMap[Node] = %+v, want size 32 align 8 with pointers", node)
1042 }
1043 if len(entry.Funcs) != 1 {
1044 t.Fatalf("len(Funcs) = %d, want 1", len(entry.Funcs))
1045 }
1046 for _, tt := range []struct {
1047 typ, want string
1048 }{
1049 {"Node", ""},
1050 {"*Node", ""},
1051 {"*Opaque", ""},
1052 {"[2]Pair", ""},
1053 {"Opaque", "incomplete"},
1054 {"struct { _ structs.HostLayout; o Opaque }", "incomplete"},
1055 } {
1056 if got := cTypeError(tt.typ, entry.TypeMap); (got == "") != (tt.want == "") || !strings.Contains(got, tt.want) {
1057 t.Errorf("cTypeError(%q) = %q, want error containing %q", tt.typ, got, tt.want)
1058 }
1059 }
1060 if got := cDeclTypeError("Opaque", entry.TypeMap); got != "" {
1061 t.Errorf("cDeclTypeError(Opaque) = %q, want no error", got)
1062 }
1063
1064 types := map[string]BindingType{
1065 "Inner": {Name: "Inner", Def: "struct { a int32 }"},
1066 "Outer": {Name: "Outer", Def: "struct { _ structs.HostLayout; in Inner }"},
1067 "PtrOuter": {Name: "PtrOuter", Def: "struct { _ structs.HostLayout; in *Inner }"},
1068 "ArrOuter": {Name: "ArrOuter", Def: "struct { _ structs.HostLayout; in [2]Inner }"},
1069 "Self": {Name: "Self", Def: "struct { _ structs.HostLayout; next *Self; m map[int32]int32 }"},
1070 "Alias": {Name: "Alias", Def: "PtrOuter"},
1071 }
1072 for _, tt := range []struct {
1073 typ, want string
1074 }{
1075 {"Inner", "structs.HostLayout"},
1076 {"*Inner", "structs.HostLayout"},
1077 {"Outer", "structs.HostLayout"},
1078 {"PtrOuter", "structs.HostLayout"},
1079 {"ArrOuter", "structs.HostLayout"},
1080 {"Alias", "structs.HostLayout"},
1081 {"*Self", "Go map"},
1082 } {
1083 if got := cTypeError(tt.typ, types); !strings.Contains(got, tt.want) {
1084 t.Errorf("cTypeError(%q) = %q, want error containing %q", tt.typ, got, tt.want)
1085 }
1086 if got := cDeclTypeError(tt.typ, types); !strings.Contains(got, tt.want) {
1087 t.Errorf("cDeclTypeError(%q) = %q, want error containing %q", tt.typ, got, tt.want)
1088 }
1089 }
1090 }
1091
1092
1093
1094 func TestInspectTypeGoOnly(t *testing.T) {
1095 cfg := getABI("linux", "amd64")
1096 for _, typ := range []string{
1097 "string",
1098 "any",
1099 "error",
1100 "[]byte",
1101 "[2][]int32",
1102 "struct { _ structs.HostLayout; s []byte }",
1103 "map[int32]int32",
1104 "chan int32",
1105 "func()",
1106 "interface{}",
1107 "L[int32]",
1108 "struct { _ structs.HostLayout; m map[int32]int32 }",
1109 "[2]func()",
1110 } {
1111 func() {
1112 defer func() {
1113 if recover() == nil {
1114 t.Errorf("inspectType(%q) did not panic", typ)
1115 }
1116 }()
1117 cfg.inspectType(typ, nil)
1118 }()
1119 }
1120 }
1121
1122 func TestBindingPointerChecks(t *testing.T) {
1123 origGoos, origGoarch, origObjDir := goos, goarch, *objDir
1124 defer func() { goos, goarch, *objDir = origGoos, origGoarch, origObjDir }()
1125 t.Setenv("GOOS", "linux")
1126 t.Setenv("GOARCH", "amd64")
1127
1128 tmpDir := t.TempDir()
1129 write := func(name, src string) string {
1130 path := filepath.Join(tmpDir, name)
1131 if err := os.WriteFile(path, []byte(src), 0644); err != nil {
1132 t.Fatal(err)
1133 }
1134 return path
1135 }
1136 bindings := write("bindings.go", `package p
1137
1138 import "C"
1139 import "unsafe"
1140
1141 //cgo:func Fill C.fill "libx.so"
1142 func Fill(p unsafe.Pointer, n int32) int32
1143
1144 //cgo:func Get get "libx.so"
1145 func Get(pp **int32)
1146
1147 //cgo:func Len C.len "libx.so"
1148 func Len(s *byte) int32
1149
1150 type conn struct {
1151 next *conn
1152 outLen int32
1153 }
1154
1155 func use(c *conn, s []*int32, b []byte) {
1156 n := Fill(unsafe.Pointer(&c.outLen), 4)
1157 _ = n
1158 C.fill(unsafe.Pointer(&s[1]), 1)
1159 Get(&s[0])
1160 defer Get(nil)
1161 go Get(&s[0])
1162 Fill(unsafe.Pointer(c), C.int(Len(&b[0])))
1163 _ = C.len(&b[0])
1164 _ = C.fill(nil, 1)
1165 _ = (C.fill)(unsafe.Pointer(&c.outLen), 4)
1166 f := C.fill
1167 _ = f
1168 g := Fill
1169 _ = g
1170 }
1171 `)
1172 shadow := write("shadow.go", `package p
1173
1174 import "unsafe"
1175
1176 func g(c *conn, Get func(**int32)) {
1177 Get(nil)
1178 Fill(unsafe.Pointer(c), 1)
1179 }
1180 `)
1181 *objDir = tmpDir + string(filepath.Separator)
1182 goos, goarch = "linux", "amd64"
1183 p := newPackage(nil, fset)
1184 p.processBinding([]string{bindings, shadow})
1185
1186 read := func(name string) string {
1187 data, err := os.ReadFile(filepath.Join(tmpDir, name))
1188 if err != nil {
1189 t.Fatal(err)
1190 }
1191 return string(data)
1192 }
1193 gotypes := read("_cgo_gotypes.go")
1194 for _, want := range []string{
1195 "//go:linkname _cgoCheckPointer runtime.cgoCheckPointer\n//go:noescape\nfunc _cgoCheckPointer(interface{}, interface{})\n",
1196 "func _Cgocheck_Fill(p0 unsafe.Pointer, p1 int32) int32 {\n\t_cgoCheckPointer(p0, nil)\n\treturn _Cfunc_Fill(p0, p1)\n}\n",
1197 "func Fill(p0 unsafe.Pointer, p1 int32) int32 {\n\treturn _Cgocheck_Fill(p0, p1)\n}\n",
1198 "func _Cgocheck_Get(p0 **int32) {\n\t_cgoCheckPointer(p0, nil)\n\t_Cfunc_Get(p0)\n}\n",
1199
1200 "func Len(p0 *byte) int32 {\n\treturn _Cfunc_Len(p0)\n}\n",
1201 } {
1202 if !strings.Contains(gotypes, want) {
1203 t.Errorf("_cgo_gotypes.go missing %q:\n%s", want, gotypes)
1204 }
1205 }
1206 if strings.Contains(gotypes, "_Cgocheck_Len") {
1207 t.Errorf("_cgo_gotypes.go has unneeded _Cgocheck_Len:\n%s", gotypes)
1208 }
1209
1210 got := read("bindings.cgobinding.go")
1211 for _, want := range []string{
1212
1213 "func() (_cgoa _cgo_arg_Fill) { _cgoBase0 := &c.outLen; _cgoa.p0 = unsafe.Pointer(_cgoBase0); _cgoa.p1 = 4; _cgoCheckPointer(_cgoBase0, 0 == 0); _cgoa.ret = _Cfunc_Fill(_cgoa.p0, _cgoa.p1); return }().ret\n",
1214
1215
1216 "func() { var _cgoa _cgo_arg_Fill; _cgoIndex0 := &s; _cgoa.p0 = unsafe.Pointer(&(*_cgoIndex0)[1]); _cgoa.p1 = 1; _cgoCheckPointer(_cgoa.p0, *_cgoIndex0); _Cfunc_Fill(_cgoa.p0, _cgoa.p1) }()\n",
1217 "func() { var _cgoa _cgo_arg_Get; _cgoIndex0 := &s; _cgoa.p0 = &(*_cgoIndex0)[0]; _cgoCheckPointer(_cgoa.p0, *_cgoIndex0); _Cfunc_Get(_cgoa.p0) }()\n",
1218
1219 "defer Get(nil)\n",
1220
1221 "go func() func() { var _cgoa _cgo_arg_Get; _cgoIndex0 := &s; _cgoa.p0 = &(*_cgoIndex0)[0]; return func() { _cgoCheckPointer(_cgoa.p0, *_cgoIndex0); _Cfunc_Get(_cgoa.p0) } }()()\n",
1222
1223
1224 "func() { var _cgoa _cgo_arg_Fill; _cgoa.p0 = unsafe.Pointer(c); _cgoa.p1 = int32(Len(&b[0])); _cgoCheckPointer(_cgoa.p0, nil); _Cfunc_Fill(_cgoa.p0, _cgoa.p1) }()\n",
1225 "_ = _Cfunc_Len(&b[0])\n",
1226
1227 "_ = _Cgocheck_Fill(nil, 1)\n",
1228
1229 "_ = func() (_cgoa _cgo_arg_Fill) { _cgoBase0 := &c.outLen; _cgoa.p0 = unsafe.Pointer(_cgoBase0); _cgoa.p1 = 4; _cgoCheckPointer(_cgoBase0, 0 == 0); _cgoa.ret = _Cfunc_Fill(_cgoa.p0, _cgoa.p1); return }().ret\n",
1230
1231 "f := _Cgo_ptr(_Cfpvar_fp_fill)\n",
1232
1233 "g := Fill\n",
1234 } {
1235 if !strings.Contains(got, want) {
1236 t.Errorf("bindings.cgobinding.go missing %q:\n%s", want, got)
1237 }
1238 }
1239
1240
1241
1242
1243 got = read("shadow.cgobinding.go")
1244 for _, want := range []string{
1245 "\tGet(nil)\n",
1246 "func() { var _cgoa _cgo_arg_Fill; _cgoa.p0 = unsafe.Pointer(c); _cgoa.p1 = 1; _cgoCheckPointer(_cgoa.p0, nil); _Cfunc_Fill(_cgoa.p0, _cgoa.p1) }()\n",
1247 } {
1248 if !strings.Contains(got, want) {
1249 t.Errorf("shadow.cgobinding.go missing %q:\n%s", want, got)
1250 }
1251 }
1252 }
1253
1254 func TestBindingHasPointer(t *testing.T) {
1255 types := map[string]BindingType{
1256 "_Ctype_struct_node": {Name: "_Ctype_struct_node", Def: "struct { next *_Ctype_struct_node; v int32 }"},
1257 "_Ctype_struct_flat": {Name: "_Ctype_struct_flat", Def: "struct { a [4]byte; b float64 }"},
1258 }
1259 for _, tt := range []struct {
1260 typ string
1261 want bool
1262 }{
1263 {"int32", false},
1264 {"*byte", false},
1265 {"*[16]float64", false},
1266 {"**byte", true},
1267 {"unsafe.Pointer", true},
1268 {"struct { p *byte }", false},
1269 {"struct { p **byte }", true},
1270 {"*_Ctype_struct_flat", false},
1271 {"*_Ctype_struct_node", true},
1272 {"_Ctype_struct_node", true},
1273 {"_Ctype_struct_flat", false},
1274 {"*_Ctype_struct_unknown", true},
1275 } {
1276 if got := bindingHasPointer(tt.typ, types, true); got != tt.want {
1277 t.Errorf("bindingHasPointer(%q, top) = %v, want %v", tt.typ, got, tt.want)
1278 }
1279 }
1280 }
1281
1282
1283
1284 func TestIsAnonCtype(t *testing.T) {
1285 for name, want := range map[string]bool{
1286 "_Ctype_struct___0": true,
1287 "_Ctype_union___12": true,
1288 "_Ctype_class___3": true,
1289 "_Ctype_struct___": false,
1290 "_Ctype_struct___foo": false,
1291 "_Ctype_struct_S": false,
1292 "_Ctype_union_U": false,
1293 "_Ctype_U": false,
1294 "_Ctype_int": false,
1295 } {
1296 if got := isAnonCtype(name); got != want {
1297 t.Errorf("isAnonCtype(%q) = %v, want %v", name, got, want)
1298 }
1299 }
1300 }
1301
1302 func TestBindingFuncPtrAndExportCall(t *testing.T) {
1303 origGoos, origGoarch, origObjDir := goos, goarch, *objDir
1304 defer func() { goos, goarch, *objDir = origGoos, origGoarch, origObjDir }()
1305
1306 src := `package p
1307
1308 import "C"
1309 import "unsafe"
1310
1311 //cgo:func DynFn C.dyn_fn "libx.so"
1312 //cgo:func StaticFn C.static_fn static
1313 //cgo:func UnusedFn C.unused_fn static
1314
1315 func DynFn(a int32) int32
1316 func StaticFn(a int32) int32
1317 func UnusedFn(a int32) int32
1318
1319 //export ExpBoth
1320 func ExpBoth(a int32) int32 { return a + 1 }
1321
1322 //export ExpPtr
1323 func ExpPtr(p unsafe.Pointer) int32 { return 0 }
1324
1325 //export ExpFPOnly
1326 func ExpFPOnly(a int32) int32 { return a + 2 }
1327
1328 type box struct{ x int32 }
1329
1330 func Use(b *box) {
1331 _ = C.dyn_fn(1)
1332 _ = C.dyn_fn
1333 _ = C.static_fn
1334 _ = C.ExpBoth
1335 _ = C.ExpBoth(2)
1336 _ = (C.ExpBoth)(3)
1337 _ = C.ExpPtr(unsafe.Pointer(&b.x))
1338 _ = C.ExpPtr(nil)
1339 _ = C.ExpFPOnly
1340 }
1341 `
1342 run := func(targetOS, targetArch string) (gotypes, rewritten, tramp string) {
1343 t.Helper()
1344 tmpDir := t.TempDir()
1345 srcFile := filepath.Join(tmpDir, "p.go")
1346 if err := os.WriteFile(srcFile, []byte(src), 0644); err != nil {
1347 t.Fatal(err)
1348 }
1349 *objDir = tmpDir + string(filepath.Separator)
1350 goos, goarch = targetOS, targetArch
1351 t.Setenv("GOOS", targetOS)
1352 t.Setenv("GOARCH", targetArch)
1353
1354 p := newPackage(nil, token.NewFileSet())
1355 p.processBinding([]string{srcFile})
1356
1357 read := func(name string) string {
1358 b, err := os.ReadFile(filepath.Join(tmpDir, name))
1359 if err != nil {
1360 t.Fatalf("%s/%s: reading %s: %v", targetOS, targetArch, name, err)
1361 }
1362 return string(b)
1363 }
1364 return read("_cgo_gotypes.go"), read("p.cgobinding.go"), read("_cgo_trampolines.s")
1365 }
1366
1367 gotypes, rewritten, tramp := run("linux", "amd64")
1368 for _, want := range []string{
1369 `func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }`,
1370 `//go:cgo_import_static static_fn`,
1371 `//go:linkname __cgo_fp_dyn_fn dyn_fn`,
1372 `var _Cfpvar_fp_dyn_fn unsafe.Pointer = unsafe.Pointer(&__cgo_fp_dyn_fn)`,
1373 `//go:linkname __cgo_fp_static_fn static_fn`,
1374 `var _Cfpvar_fp_static_fn unsafe.Pointer = unsafe.Pointer(&__cgo_fp_static_fn)`,
1375 `var _Cfpvar_fp_ExpBoth unsafe.Pointer = unsafe.Pointer(&__cgofn_ExpBoth)`,
1376 `func _cgo_call_ExpBoth(args _cgo_arg_ExpBoth) int32`,
1377 `func _Cfunc_ExpBoth(p0 int32) int32`,
1378 `func _Cfunc_ExpPtr(p0 unsafe.Pointer) int32`,
1379 `func _Cgocheck_ExpPtr(p0 unsafe.Pointer) int32`,
1380 `var _Cfpvar_fp_ExpFPOnly unsafe.Pointer = unsafe.Pointer(&__cgofn_ExpFPOnly)`,
1381 } {
1382 if !strings.Contains(gotypes, want) {
1383 t.Errorf("linux/amd64 _cgo_gotypes.go missing %q:\n%s", want, gotypes)
1384 }
1385 }
1386 if strings.Count(gotypes, "type _cgo_arg_ExpBoth struct") != 1 {
1387 t.Errorf("linux/amd64 _cgo_gotypes.go has %d definitions of _cgo_arg_ExpBoth, want 1:\n%s",
1388 strings.Count(gotypes, "type _cgo_arg_ExpBoth struct"), gotypes)
1389 }
1390 for _, notWant := range []string{
1391 `_Cfpvar_fp_unused_fn`,
1392 `cgo_import_static unused_fn`,
1393 `func _Cfunc_ExpFPOnly`,
1394 `func ExpBoth(`,
1395 `func ExpPtr(`,
1396 } {
1397 if strings.Contains(gotypes, notWant) {
1398 t.Errorf("linux/amd64 _cgo_gotypes.go contains unexpected %q:\n%s", notWant, gotypes)
1399 }
1400 }
1401 for _, want := range []string{
1402 `_ = _Cfunc_DynFn(1)`,
1403 `_ = _Cgo_ptr(_Cfpvar_fp_dyn_fn)`,
1404 `_ = _Cgo_ptr(_Cfpvar_fp_static_fn)`,
1405 `_ = _Cgo_ptr(_Cfpvar_fp_ExpBoth)`,
1406 `_ = _Cfunc_ExpBoth(2)`,
1407 `_ = (_Cfunc_ExpBoth)(3)`,
1408 `_cgoBase0 := &b.x; _cgoa.p0 = unsafe.Pointer(_cgoBase0); _cgoCheckPointer(_cgoBase0, 0 == 0); _cgoa.ret = _Cfunc_ExpPtr(_cgoa.p0)`,
1409 `_ = _Cgocheck_ExpPtr(nil)`,
1410 `_ = _Cgo_ptr(_Cfpvar_fp_ExpFPOnly)`,
1411 } {
1412 if !strings.Contains(rewritten, want) {
1413 t.Errorf("linux/amd64 p.cgobinding.go missing %q:\n%s", want, rewritten)
1414 }
1415 }
1416 for _, want := range []string{
1417 "TEXT ExpBoth(SB)",
1418 "_trampoline_ExpBoth(SB)",
1419 "CALL\tExpBoth(SB)",
1420 "TEXT ExpPtr(SB)",
1421 "_trampoline_ExpPtr(SB)",
1422 "CALL\tExpPtr(SB)",
1423 "TEXT ExpFPOnly(SB)",
1424 } {
1425 if !strings.Contains(tramp, want) {
1426 t.Errorf("linux/amd64 _cgo_trampolines.s missing %q:\n%s", want, tramp)
1427 }
1428 }
1429 if strings.Contains(tramp, "_trampoline_ExpFPOnly") {
1430 t.Errorf("linux/amd64 _cgo_trampolines.s emitted unused trampoline for ExpFPOnly:\n%s", tramp)
1431 }
1432
1433
1434
1435
1436 winTypes, _, winTramp := run("windows", "amd64")
1437 for _, want := range []string{
1438 "//go:linkname _Cfpvar_fp_dyn_fn dyn_fn\nvar _Cfpvar_fp_dyn_fn unsafe.Pointer\n",
1439 "//go:cgo_import_static static_fn\n",
1440 "//go:linkname __cgo_fp_static_fn static_fn\nvar __cgo_fp_static_fn byte\nvar _Cfpvar_fp_static_fn unsafe.Pointer = unsafe.Pointer(&__cgo_fp_static_fn)\n",
1441 "var _Cfpvar_fp_ExpBoth unsafe.Pointer = unsafe.Pointer(&__cgofn_ExpBoth)\n",
1442 } {
1443 if !strings.Contains(winTypes, want) {
1444 t.Errorf("windows/amd64 _cgo_gotypes.go missing %q:\n%s", want, winTypes)
1445 }
1446 }
1447 if strings.Contains(winTypes, "__cgo_fp_dyn_fn") {
1448 t.Errorf("windows/amd64 _cgo_gotypes.go should link _Cfpvar_fp_dyn_fn directly to IAT slot:\n%s", winTypes)
1449 }
1450 if !strings.Contains(winTramp, "CALL\tExpBoth(SB)") {
1451 t.Errorf("windows/amd64 _cgo_trampolines.s should call //export ExpBoth directly:\n%s", winTramp)
1452 }
1453
1454
1455
1456 aixDir := t.TempDir()
1457 *objDir = aixDir + string(filepath.Separator)
1458 goos, goarch = "aix", "ppc64"
1459 t.Setenv("GOOS", "aix")
1460 t.Setenv("GOARCH", "ppc64")
1461 aixPkg := newPackage(nil, token.NewFileSet())
1462 aixEntry := aixPkg.parseBinding("p.go", []byte(src))
1463 aixEntry.UsedFuncPtrs["dyn_fn"] = true
1464 aixEntry.UsedFuncPtrs["static_fn"] = true
1465 aixPkg.writeGoTypes(aixEntry, nil)
1466 aixBytes, err := os.ReadFile(filepath.Join(aixDir, "_cgo_gotypes.go"))
1467 if err != nil {
1468 t.Fatal(err)
1469 }
1470 aixTypes := string(aixBytes)
1471 for _, want := range []string{
1472 "//go:cgo_import_dynamic __cgo_imp_dyn_fn dyn_fn",
1473 "//go:linkname _Cfpvar_fp_dyn_fn __cgo_imp_dyn_fn\nvar _Cfpvar_fp_dyn_fn unsafe.Pointer\n",
1474 "//go:cgo_import_static static_fn\n",
1475 "//go:linkname __cgo_fp_static_fn static_fn\nvar __cgo_fp_static_fn byte\nvar _Cfpvar_fp_static_fn unsafe.Pointer = unsafe.Pointer(&__cgo_fp_static_fn)\n",
1476 } {
1477 if !strings.Contains(aixTypes, want) {
1478 t.Errorf("aix/ppc64 _cgo_gotypes.go missing %q:\n%s", want, aixTypes)
1479 }
1480 }
1481 if strings.Contains(aixTypes, "__cgo_fp_dyn_fn") {
1482 t.Errorf("aix/ppc64 _cgo_gotypes.go should link _Cfpvar_fp_dyn_fn directly to TOC slot:\n%s", aixTypes)
1483 }
1484 }
1485
View as plain text