Text file src/cmd/go/testdata/script/cgo_binding.txt

     1  # Test building and running a cgo package using //cgo:func pragmas without a
     2  # C compiler toolchain.
     3  
     4  env GOEXPERIMENT=$GOEXPERIMENT,runtimecgopurego,cgobindings
     5  [!GOEXPERIMENT:cgobindings] skip
     6  
     7  env CGO_ENABLED=bindings
     8  # Make any use of the C compiler or external linker by the go command fail.
     9  # Targets that require external linking for cgo (cgolinkext) need the real
    10  # C toolchain to link, so CC is left alone there. (The script's cc command
    11  # always runs the test's C compiler, regardless of $CC.)
    12  [!GOOS:windows] [!cgolinkext] env CC=/bin/false
    13  [GOOS:windows] env CC=nonexistent-cc
    14  
    15  # A binding package is built without a C compiler, so it may not also contain
    16  # C files (or other sources needing a C compiler), under both
    17  # CGO_ENABLED=bindings and CGO_ENABLED=1. Without them, a binding package
    18  # calling libc works.
    19  cd withcfile
    20  ! go build .
    21  stderr 'source files requiring a C compiler not allowed in a package using cgo binding pragmas: cfile.c$'
    22  env CGO_ENABLED=1
    23  ! go build .
    24  stderr 'source files requiring a C compiler not allowed in a package using cgo binding pragmas: cfile.c$'
    25  rm cfile.c
    26  go run .
    27  stdout '^abs=7 cabs=7 strlen=5$'
    28  stdout '^builtins=hi!,hi,abcd,xyz$'
    29  env CGO_ENABLED=bindings
    30  go run .
    31  stdout '^abs=7 cabs=7 strlen=5$'
    32  stdout '^builtins=hi!,hi,abcd,xyz$'
    33  
    34  # Building with CGO_ENABLED=bindings requires the cgobindings experiment, but
    35  # commands that do not build, like go env and go version, still work.
    36  env origGOEXPERIMENT=$GOEXPERIMENT
    37  env GOEXPERIMENT=nocgobindings
    38  go env CGO_ENABLED
    39  stdout '^bindings$'
    40  go version
    41  ! go build .
    42  stderr '^go: CGO_ENABLED=bindings requires GOEXPERIMENT=cgobindings$'
    43  env GOEXPERIMENT=$origGOEXPERIMENT
    44  
    45  # Verify build constraints across CGO_ENABLED=bindings, 1, and 0:
    46  # //go:build cgobindings and cgo || cgobindings files (Go + asm) are selected
    47  # in bindings and 1 modes, !cgo && !cgobindings fallbacks and their imports
    48  # are selected only in 0 mode, and the cgo tag is false in bindings mode.
    49  cd ../dual
    50  go list -f '{{.CgoFiles}}' .
    51  stdout '^\[binding\.go\]$'
    52  go list -deps .
    53  ! stdout 'dual/nocgoonly'
    54  go list -f '{{.IgnoredGoFiles}}' .
    55  stdout 'cgo_only\.go'
    56  go run .
    57  stdout '^mode=binding-helper abs=128$'
    58  
    59  env CGO_ENABLED=1
    60  go list -f '{{.CgoFiles}}' .
    61  stdout '^\[binding\.go\]$'
    62  go list -f '{{.GoFiles}}' .
    63  stdout 'cgo_only\.go'
    64  go run .
    65  stdout '^mode=binding-helper abs=128$'
    66  
    67  env CGO_ENABLED=0
    68  go list -f '{{.CgoFiles}}' .
    69  stdout '^\[\]$'
    70  go list -deps .
    71  stdout 'dual/nocgoonly'
    72  go run .
    73  stdout '^mode=nocgo-fallback$'
    74  env CGO_ENABLED=bindings
    75  
    76  # Bound functions may only use types with C equivalents.
    77  cd ../badtype
    78  ! go build .
    79  stderr '//cgo:func Puts: parameter type string cannot be passed to C: it contains a Go string'
    80  
    81  # Arguments that might contain Go pointers get cgocheck pointer checks, as in
    82  # traditional cgo. Calls in the package check only the memory that &x, &a[i],
    83  # and a[i:j] arguments refer to; indirect calls check the whole allocation.
    84  cd ../checks
    85  go run . narrow
    86  stdout '^narrow ok$'
    87  ! go run . unpinned
    88  stderr 'argument of cgo function has Go pointer to unpinned Go pointer'
    89  go run . pinned
    90  stdout '^pinned ok$'
    91  ! go run . indirect
    92  stderr 'argument of cgo function has Go pointer to unpinned Go pointer'
    93  env GODEBUG=cgocheck=0
    94  go run . unpinned
    95  stdout '^unpinned ok$'
    96  env GODEBUG=
    97  
    98  # The remaining tests compile a C shared library and static object with the
    99  # script's cc command, which uses the test's C compiler rather than $CC.
   100  [!GOOS:darwin] [!GOOS:linux] stop
   101  [!exec:cc] stop
   102  
   103  cd ../p
   104  cc -fPIC -shared -o libx.so ../c/c.c
   105  [GOOS:linux] env LD_LIBRARY_PATH=.
   106  go run .
   107  stdout '^add=30$'
   108  stdout '^addFloat=6.25$'
   109  stdout '^sumTen=55$'
   110  stdout '^packedScalars=-100996$'
   111  stdout '^packedFloats=-391$'
   112  stdout '^ptr=42$'
   113  stdout '^strlen=5$'
   114  
   115  # A static symbol is resolved at link time from a .syso file. Host objects
   116  # in non-standard packages make cmd/link default to external linking, so
   117  # request internal linking explicitly, which works with CC=/bin/false.
   118  # Targets that require external linking (cgolinkext) link with the real C
   119  # toolchain, since CC was not overridden for them above.
   120  cd ../s
   121  cc -fPIC -c -o static.syso ../c/static.c
   122  [!cgolinkext] go run -ldflags=-linkmode=internal .
   123  [cgolinkext] go run .
   124  stdout '^static=42$'
   125  stdout '^counter=42$'
   126  
   127  -- c/c.c --
   128  int Add(int a, int b) { return a + b; }
   129  double AddFloat(float a, double b) { return (double)a + b; }
   130  long long SumTen(
   131  	long long a1, long long a2, long long a3, long long a4, long long a5,
   132  	long long a6, long long a7, long long a8, long long a9, long long a10
   133  ) {
   134  	return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10;
   135  }
   136  long long PackedScalars(
   137  	long long r0, long long r1, long long r2, long long r3,
   138  	long long r4, long long r5, long long r6, long long r7,
   139  	signed char a, short b, signed char c, _Bool d, int e, long long f, unsigned char g
   140  ) {
   141  	if (r0 != 1 || r1 != 2 || r2 != 3 || r3 != 4 || r4 != 5 || r5 != 6 || r6 != 7 || r7 != 8)
   142  		return -1;
   143  	if (a != -5 || b != -1234 || c != 42 || !d || e != -100000 || f != 0x1122334455667788LL || g != 200)
   144  		return -2;
   145  	return (long long)a + (long long)b + (long long)c + (d ? 1 : 0) + (long long)e + (long long)g;
   146  }
   147  int PackedFloats(
   148  	int r0, int r1, int r2, int r3,
   149  	int r4, int r5, int r6, int r7,
   150  	float f0, float f1, float f2, float f3,
   151  	float f4, float f5, float f6, float f7,
   152  	short s, float f8, signed char b
   153  ) {
   154  	if (r0 != 1 || r1 != 2 || r2 != 3 || r3 != 4 || r4 != 5 || r5 != 6 || r6 != 7 || r7 != 8)
   155  		return -1;
   156  	if (f0 != 1.0f || f1 != 2.0f || f2 != 3.0f || f3 != 4.0f || f4 != 5.0f || f5 != 6.0f || f6 != 7.0f || f7 != 8.0f)
   157  		return -2;
   158  	if (s != -321 || f8 != 3.5f || b != -77)
   159  		return -3;
   160  	return (int)s + (int)(f8 * 2.0f) + (int)b;
   161  }
   162  void WritePtr(int *p, int val) { *p = val; }
   163  
   164  -- c/static.c --
   165  int StaticTwice(int x) { return 2 * x; }
   166  int StaticCounter = 40;
   167  
   168  -- p/go.mod --
   169  module p
   170  
   171  go 1.28
   172  
   173  -- p/binding.go --
   174  package main
   175  
   176  // #cgo LDFLAGS: ./libx.so
   177  import "C"
   178  
   179  //cgo:func Add C.Add "libx.so"
   180  //cgo:func AddFloat AddFloat "libx.so"
   181  //cgo:func SumTen SumTen "libx.so"
   182  //cgo:func PackedScalars PackedScalars "libx.so"
   183  //cgo:func PackedFloats PackedFloats "libx.so"
   184  //cgo:func WritePtr WritePtr "libx.so"
   185  
   186  func Add(a int32, b int32) int32
   187  
   188  func AddFloat(a float32, b float64) float64
   189  
   190  func SumTen(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 int64) int64
   191  
   192  func PackedScalars(
   193  	r0, r1, r2, r3, r4, r5, r6, r7 int64,
   194  	a int8, b int16, c int8, d bool, e int32, f int64, g uint8,
   195  ) int64
   196  
   197  func PackedFloats(
   198  	r0, r1, r2, r3, r4, r5, r6, r7 int32,
   199  	f0, f1, f2, f3, f4, f5, f6, f7 float32,
   200  	s int16, f8 float32, b int8,
   201  ) int32
   202  
   203  func WritePtr(p *int32, val int32)
   204  
   205  func Strlen(s *byte) uintptr
   206  
   207  -- p/main.go --
   208  package main
   209  
   210  import "fmt"
   211  import "C"
   212  
   213  // Pragmas may appear in any file that imports "C".
   214  //cgo:func Strlen strlen libc
   215  
   216  func main() {
   217  	fmt.Printf("add=%d\n", Add(10, 20)+int32(C.Add(0, 0)))
   218  	fmt.Printf("addFloat=%.2f\n", AddFloat(2.5, 3.75))
   219  	fmt.Printf("sumTen=%d\n", SumTen(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
   220  	fmt.Printf("packedScalars=%d\n", PackedScalars(1, 2, 3, 4, 5, 6, 7, 8, -5, -1234, 42, true, -100000, 0x1122334455667788, 200))
   221  	fmt.Printf("packedFloats=%d\n", PackedFloats(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, -321, 3.5, -77))
   222  	var v int32
   223  	WritePtr(&v, 42)
   224  	fmt.Printf("ptr=%d\n", v)
   225  	fmt.Printf("strlen=%d\n", Strlen(&[]byte("hello\x00")[0]))
   226  }
   227  
   228  -- s/go.mod --
   229  module s
   230  
   231  go 1.28
   232  
   233  -- s/main.go --
   234  package main
   235  
   236  import "C"
   237  import "fmt"
   238  
   239  //cgo:func StaticTwice StaticTwice static
   240  //cgo:var counter StaticCounter static
   241  
   242  func StaticTwice(x int32) int32
   243  
   244  var counter int32
   245  
   246  func main() {
   247  	fmt.Printf("static=%d\n", StaticTwice(21))
   248  	counter += 2
   249  	fmt.Printf("counter=%d\n", counter)
   250  }
   251  
   252  -- withcfile/go.mod --
   253  module withcfile
   254  
   255  go 1.28
   256  
   257  -- withcfile/cfile.c --
   258  int unused;
   259  
   260  -- withcfile/binding.go --
   261  package main
   262  
   263  import "C"
   264  
   265  // Pragmas may appear in any file that imports "C".
   266  //cgo:func Strlen strlen libc
   267  
   268  -- withcfile/main.go --
   269  package main
   270  
   271  // #include <stdlib.h>
   272  import "C"
   273  import (
   274  	"fmt"
   275  	"unsafe"
   276  )
   277  
   278  //cgo:func Abs C.abs libc
   279  //cgo:func Free free libc
   280  func Abs(int32) int32
   281  func Free(unsafe.Pointer)
   282  
   283  func Strlen(s *byte) uintptr
   284  
   285  func main() {
   286  	fmt.Printf("abs=%d cabs=%d strlen=%d\n", Abs(-7), C.abs(-7), Strlen(&[]byte("hello\x00")[0]))
   287  	cs := C.CString("hi!")
   288  	defer Free(unsafe.Pointer(cs))
   289  	cb := C.CBytes([]byte("abcd"))
   290  	defer Free(cb)
   291  	pm := C.malloc(4)
   292  	defer Free(pm)
   293  	*(*[4]byte)(pm) = [4]byte{'x', 'y', 'z', 0}
   294  	fmt.Printf("builtins=%s,%s,%s,%s\n", C.GoString(cs), C.GoStringN(cs, 2), string(C.GoBytes(cb, 4)), C.GoString((*C.char)(pm)))
   295  }
   296  
   297  -- dual/go.mod --
   298  module dual
   299  
   300  go 1.28
   301  
   302  -- dual/nocgoonly/nocgoonly.go --
   303  //go:build !cgo && !cgobindings
   304  
   305  package nocgoonly
   306  
   307  func Label() string { return "nocgo" }
   308  
   309  -- dual/a_nocgo.go --
   310  //go:build !cgo && !cgobindings
   311  
   312  package main
   313  
   314  import "dual/nocgoonly"
   315  
   316  func mode() string {
   317  	if asmSuffix() != 7 {
   318  		panic("unexpected asmSuffix")
   319  	}
   320  	return nocgoonly.Label() + "-fallback"
   321  }
   322  
   323  -- dual/nocgo_asm.go --
   324  //go:build !cgo && !cgobindings && (amd64 || arm64)
   325  
   326  package main
   327  
   328  func asmSuffix() int
   329  
   330  -- dual/nocgo_amd64.s --
   331  //go:build !cgo && !cgobindings
   332  
   333  #include "textflag.h"
   334  
   335  TEXT ·asmSuffix(SB),NOSPLIT,$0-8
   336  	MOVQ $7, ret+0(FP)
   337  	RET
   338  
   339  -- dual/nocgo_arm64.s --
   340  //go:build !cgo && !cgobindings
   341  
   342  #include "textflag.h"
   343  
   344  TEXT ·asmSuffix(SB),NOSPLIT,$0-8
   345  	MOVD $7, R0
   346  	MOVD R0, ret+0(FP)
   347  	RET
   348  
   349  -- dual/nocgo_other.go --
   350  //go:build !cgo && !cgobindings && !amd64 && !arm64
   351  
   352  package main
   353  
   354  func asmSuffix() int { return 7 }
   355  
   356  -- dual/cgo_only.go --
   357  //go:build cgo
   358  
   359  package main
   360  
   361  const _cgoTagEnabled = true
   362  
   363  -- dual/binding.go --
   364  //go:build cgobindings
   365  
   366  package main
   367  
   368  import "C"
   369  
   370  //cgo:func Abs abs libc
   371  func Abs(int32) int32
   372  
   373  -- dual/helper_cgo.go --
   374  //go:build cgo || cgobindings
   375  
   376  package main
   377  
   378  import "fmt"
   379  
   380  func mode() string {
   381  	return fmt.Sprintf("binding-helper abs=%d", Abs(-120)+cgoAsmBonus())
   382  }
   383  
   384  -- dual/cgo_asm.go --
   385  //go:build (cgo || cgobindings) && (amd64 || arm64)
   386  
   387  package main
   388  
   389  func cgoAsmBonus() int32
   390  
   391  -- dual/cgo_amd64.s --
   392  //go:build cgo || cgobindings
   393  
   394  #include "textflag.h"
   395  
   396  TEXT ·cgoAsmBonus(SB),NOSPLIT,$0-4
   397  	MOVL $8, ret+0(FP)
   398  	RET
   399  
   400  -- dual/cgo_arm64.s --
   401  //go:build cgo || cgobindings
   402  
   403  #include "textflag.h"
   404  
   405  TEXT ·cgoAsmBonus(SB),NOSPLIT,$0-4
   406  	MOVD $8, R0
   407  	MOVW R0, ret+0(FP)
   408  	RET
   409  
   410  -- dual/cgo_other.go --
   411  //go:build (cgo || cgobindings) && !amd64 && !arm64
   412  
   413  package main
   414  
   415  func cgoAsmBonus() int32 { return 8 }
   416  
   417  -- dual/main.go --
   418  package main
   419  
   420  import "fmt"
   421  
   422  func main() {
   423  	fmt.Printf("mode=%s\n", mode())
   424  }
   425  
   426  -- badtype/go.mod --
   427  module badtype
   428  
   429  go 1.28
   430  
   431  -- badtype/main.go --
   432  package main
   433  
   434  import "C"
   435  
   436  //cgo:func Puts puts libc
   437  func Puts(s string) int32
   438  
   439  func main() {
   440  	Puts("hello")
   441  }
   442  
   443  -- checks/go.mod --
   444  module checks
   445  
   446  go 1.28
   447  
   448  -- checks/main.go --
   449  package main
   450  
   451  import "C"
   452  
   453  import (
   454  	"fmt"
   455  	"os"
   456  	"runtime"
   457  	"unsafe"
   458  )
   459  
   460  //cgo:func Memset C.memset libc
   461  func Memset(p unsafe.Pointer, c int32, n uintptr) unsafe.Pointer
   462  
   463  type S struct {
   464  	p *int32
   465  }
   466  
   467  type conn struct {
   468  	buf    *int32 // an unpinned Go pointer
   469  	outLen int32
   470  }
   471  
   472  func main() {
   473  	switch os.Args[1] {
   474  	case "narrow":
   475  		// Only c.outLen is checked, not the rest of c.
   476  		c := &conn{buf: new(int32)}
   477  		Memset(unsafe.Pointer(&c.outLen), 0, 4)
   478  		C.memset(unsafe.Pointer(&c.outLen), 0, 4)
   479  		// Only the elements of ss are checked.
   480  		ss := []S{{}, {}}
   481  		other := &struct {
   482  			ss  []S
   483  			buf *int32
   484  		}{ss, new(int32)}
   485  		Memset(unsafe.Pointer(&other.ss[1]), 0, 0)
   486  	case "unpinned":
   487  		Memset(unsafe.Pointer(&S{p: new(int32)}), 0, 0)
   488  	case "pinned":
   489  		var pinner runtime.Pinner
   490  		s := &S{p: new(int32)}
   491  		pinner.Pin(s.p)
   492  		Memset(unsafe.Pointer(s), 0, 0)
   493  		pinner.Unpin()
   494  	case "indirect":
   495  		// Without the call site, the wrapper checks all of c.
   496  		c := &conn{buf: new(int32)}
   497  		f := Memset
   498  		f(unsafe.Pointer(&c.outLen), 0, 4)
   499  	}
   500  	fmt.Printf("%s ok\n", os.Args[1])
   501  }
   502  

View as plain text