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

     1  # Test cgo callbacks (//export) in packages that use cgo binding pragmas.
     2  
     3  env GOEXPERIMENT=$GOEXPERIMENT,runtimecgopurego,cgobindings
     4  [!GOEXPERIMENT:cgobindings] skip
     5  [!GOOS:darwin] [!GOOS:linux] skip
     6  [!GOARCH:amd64] [!GOARCH:arm64] skip
     7  [!exec:cc] skip
     8  
     9  cd p
    10  cc -fPIC -shared -o libcb.so ../c/cb.c
    11  
    12  # Generate the binding file with cgo -gen-binding.
    13  go tool cgo -gen-binding ../gen/bind.go
    14  stdout '^import "C"$'
    15  stdout '^//cgo:type cb_fn C\.cb_fn$'
    16  stdout '^//cgo:func CallMeBack C\.CallMeBack "libcb\.so"$'
    17  stdout '^type cb_fn \*\[0\]byte$'
    18  stdout '^func CallMeBack\(p0 \*\[0\]byte, p1 int32, p2 int32\) int32$'
    19  ! stdout 'GoCallback'
    20  cp stdout binding.go
    21  
    22  # Verify go run works without a C compiler using generated and handwritten bindings.
    23  env CGO_ENABLED=bindings
    24  env CC=/bin/false
    25  [GOOS:linux] env LD_LIBRARY_PATH=.
    26  go run .
    27  stdout 'Callback=300'
    28  
    29  # Verify GODEBUG=cgocheck=1 panic message preserves the full //export function name.
    30  env GODEBUG=cgocheck=1
    31  ! go run . badptr
    32  stderr 'result of Go function GoPtrCallback called from cgo is unpinned Go unsafe pointer'
    33  ! go run . badptr_direct
    34  stderr 'result of Go function GoPtrCallback called from cgo is unpinned Go unsafe pointer'
    35  ! go run . badarg_direct
    36  stderr 'argument of cgo function has Go pointer to unpinned Go pointer'
    37  go run . goodarg_direct
    38  stdout '^GoodArg=99$'
    39  env GODEBUG=
    40  
    41  # Test calling //export functions via C.<name>(...) and passing bound C
    42  # functions (shared library and libc) as C function pointers.
    43  go run . direct_and_fp
    44  stdout '^DirectExp=300,30,555$'
    45  stdout '^CFuncPtr=15,15,42$'
    46  
    47  # Test Go stack growth during a callback invoked from a MayCallback C call
    48  # with a large PassByPtr struct arg and large struct return (exercising
    49  # _cgo_topofstack relocation and G0Off scratch copies).
    50  go run . growstack
    51  stdout 'GrowStack=555'
    52  
    53  # Test packed stack arguments (narrow scalars, float32 HFAs, small/medium
    54  # non-HFA structs, and >16B PassByPtr structs) in both Go->C and C->Go directions.
    55  go run . packed
    56  stdout '^Packed=100,200$'
    57  
    58  # Replace the generated binding with a handwritten one and re-run.
    59  cp ../handwritten.go binding.go
    60  go run .
    61  stdout 'Callback=300'
    62  
    63  # Verify C.<export> and C.<cfunc> in non-call context are neither assignable
    64  # nor addressable (issue #7757).
    65  cd ../badfp
    66  ! go build .
    67  stderr 'badfp\.go:17:.*cannot assign to'
    68  stderr 'badfp\.go:18:.*cannot take address of'
    69  stderr 'badfp\.go:19:.*cannot assign to'
    70  stderr 'badfp\.go:20:.*cannot take address of'
    71  
    72  # Test static (.syso) bound C function used in both call and non-call context.
    73  cd ../staticfp
    74  cc -fPIC -c -o static.syso ../c/static.c
    75  [!cgolinkext] go run -ldflags=-linkmode=internal .
    76  [!cgolinkext] stdout '^StaticFP=42,42$'
    77  
    78  # Test -buildmode=c-archive export header generation (preamble + prototype).
    79  cd ../exp_archive
    80  go build -buildmode=c-archive -o libexp.a .
    81  grep 'typedef struct { int x; } ExpPair;' libexp.h
    82  grep 'extern ExpPair GoDoublePair\(ExpPair p\);' libexp.h
    83  
    84  -- c/cb.c --
    85  #include <stdbool.h>
    86  #include <stdint.h>
    87  
    88  typedef int (*cb_fn)(int, int);
    89  typedef int (*unary_fn)(int);
    90  typedef void* (*ptr_cb_fn)(void);
    91  typedef struct { long long a, b, c, d; } Big4;
    92  typedef struct { uint8_t a, b; } Small2;
    93  typedef struct { int32_t a, b, c; } Medium;
    94  typedef struct { float a, b, c; } Float3;
    95  typedef struct { float a, b; } Float2;
    96  typedef void (*grow_cb_fn)(int);
    97  typedef int64_t (*packed_cb_fn)(
    98  	int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t,
    99  	int8_t, int16_t, int8_t, bool, int32_t, Small2, int16_t, Medium, int8_t, Big4, uint8_t
   100  );
   101  typedef int64_t (*packed_hfa_cb_fn)(
   102  	int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t,
   103  	double, double, double, double, double, double,
   104  	Float3, float, int8_t, Float2
   105  );
   106  
   107  int CallMeBack(cb_fn cb, int a, int b) {
   108  	return cb(a, b);
   109  }
   110  
   111  int CAdd(int a, int b) {
   112  	return a + b;
   113  }
   114  
   115  int CallUnary(unary_fn fn, int x) {
   116  	return fn(x);
   117  }
   118  
   119  void* CallPtrBack(ptr_cb_fn cb) {
   120  	return cb();
   121  }
   122  
   123  Big4 CallGrowStack(grow_cb_fn cb, Big4 in) {
   124  	cb(64);
   125  	Big4 out = { in.a + 1, in.b + 2, in.c + 3, in.d + 4 };
   126  	return out;
   127  }
   128  
   129  int64_t CallPackedBack(
   130  	packed_cb_fn cb,
   131  	int64_t r1, int64_t r2, int64_t r3, int64_t r4, int64_t r5, int64_t r6, int64_t r7,
   132  	int8_t a, int16_t b, int8_t c, bool d, int32_t e, Small2 sm, int16_t f, Medium med, int8_t g, Big4 big, uint8_t h
   133  ) {
   134  	if (r1 != 1 || r2 != 2 || r3 != 3 || r4 != 4 || r5 != 5 || r6 != 6 || r7 != 7)
   135  		return -1;
   136  	if (a != -5 || b != -1234 || c != 42 || !d || e != -100000)
   137  		return -2;
   138  	if (sm.a != 0x12 || sm.b != 0x34 || f != 5678)
   139  		return -3;
   140  	if (med.a != 1001 || med.b != -2002 || med.c != 3003 || g != -99)
   141  		return -4;
   142  	if (big.a != 10 || big.b != 20 || big.c != 30 || big.d != 40 || h != 250)
   143  		return -5;
   144  	Small2 sm2 = { (uint8_t)(sm.a + 1), (uint8_t)(sm.b + 2) };
   145  	Medium med2 = { med.a + 1, med.b + 2, med.c + 3 };
   146  	Big4 big2 = { big.a + 1, big.b + 2, big.c + 3, big.d + 4 };
   147  	return cb(
   148  		10, r1, r2, r3, r4, r5, r6, r7,
   149  		(int8_t)(a + 1), (int16_t)(b + 2), (int8_t)(c + 3), !d, e + 4,
   150  		sm2, (int16_t)(f + 5), med2, (int8_t)(g + 6), big2, (uint8_t)(h - 7)
   151  	);
   152  }
   153  
   154  int64_t CallPackedHFABack(
   155  	packed_hfa_cb_fn cb,
   156  	int64_t r1, int64_t r2, int64_t r3, int64_t r4, int64_t r5, int64_t r6, int64_t r7,
   157  	double f0, double f1, double f2, double f3, double f4, double f5,
   158  	Float3 h3, float fl, int8_t b, Float2 h2
   159  ) {
   160  	if (r1 != 1 || r2 != 2 || r3 != 3 || r4 != 4 || r5 != 5 || r6 != 6 || r7 != 7)
   161  		return -1;
   162  	if (f0 != 1.0 || f1 != 2.0 || f2 != 3.0 || f3 != 4.0 || f4 != 5.0 || f5 != 6.0)
   163  		return -2;
   164  	if (h3.a != 1.5f || h3.b != 2.5f || h3.c != 3.5f || fl != 4.5f || b != -17 || h2.a != 5.5f || h2.b != 6.5f)
   165  		return -3;
   166  	Float3 h3b = { h3.a + 1.0f, h3.b + 1.0f, h3.c + 1.0f };
   167  	Float2 h2b = { h2.a + 1.0f, h2.b + 1.0f };
   168  	return cb(10, r1, r2, r3, r4, r5, r6, r7, f0, f1, f2, f3, f4, f5, h3b, fl + 1.0f, (int8_t)(b + 1), h2b);
   169  }
   170  
   171  -- gen/bind.go --
   172  package main
   173  
   174  // #cgo LDFLAGS: ./libcb.so
   175  // typedef int (*cb_fn)(int, int);
   176  // extern int CallMeBack(cb_fn cb, int a, int b);
   177  import "C"
   178  
   179  //cgo:type cb_fn C.cb_fn
   180  //cgo:func CallMeBack C.CallMeBack "libcb.so"
   181  
   182  -- handwritten.go --
   183  package main
   184  
   185  // #cgo LDFLAGS: ./libcb.so
   186  import "C"
   187  
   188  //cgo:type cb_fn C.cb_fn
   189  //cgo:func CallMeBack C.CallMeBack "libcb.so"
   190  
   191  type cb_fn *[0]byte
   192  
   193  func CallMeBack(p0 cb_fn, p1, p2 int32) int32
   194  
   195  -- p/go.mod --
   196  module p
   197  
   198  go 1.28
   199  
   200  -- p/extra.go --
   201  package main
   202  
   203  import "C"
   204  import "structs"
   205  import "unsafe"
   206  
   207  //cgo:type ptr_cb_fn C.ptr_cb_fn
   208  //cgo:type unary_fn C.unary_fn
   209  //cgo:type grow_cb_fn C.grow_cb_fn
   210  //cgo:type packed_cb_fn C.packed_cb_fn
   211  //cgo:type packed_hfa_cb_fn C.packed_hfa_cb_fn
   212  //cgo:type Big4 C.Big4
   213  //cgo:type Small2 C.Small2
   214  //cgo:type Medium C.Medium
   215  //cgo:type Float3 C.Float3
   216  //cgo:type Float2 C.Float2
   217  //cgo:func CAdd C.CAdd "libcb.so"
   218  //cgo:func CallUnary C.CallUnary "libcb.so"
   219  //cgo:func Abs C.abs libc
   220  //cgo:func CallPtrBack CallPtrBack "libcb.so"
   221  //cgo:func CallGrowStack CallGrowStack "libcb.so"
   222  //cgo:func CallPackedBack CallPackedBack "libcb.so"
   223  //cgo:func CallPackedHFABack CallPackedHFABack "libcb.so"
   224  
   225  type ptr_cb_fn *[0]byte
   226  type unary_fn *[0]byte
   227  type grow_cb_fn *[0]byte
   228  type packed_cb_fn *[0]byte
   229  type packed_hfa_cb_fn *[0]byte
   230  type Big4 struct {
   231  	_          structs.HostLayout
   232  	a, b, c, d int64
   233  }
   234  type Small2 struct {
   235  	_    structs.HostLayout
   236  	a, b uint8
   237  }
   238  type Medium struct {
   239  	_       structs.HostLayout
   240  	a, b, c int32
   241  }
   242  type Float3 struct {
   243  	_       structs.HostLayout
   244  	a, b, c float32
   245  }
   246  type Float2 struct {
   247  	_    structs.HostLayout
   248  	a, b float32
   249  }
   250  
   251  func CAdd(a, b int32) int32
   252  func CallUnary(fn unary_fn, x int32) int32
   253  func Abs(x int32) int32
   254  func CallPtrBack(p0 ptr_cb_fn) unsafe.Pointer
   255  func CallGrowStack(cb grow_cb_fn, in Big4) Big4
   256  func CallPackedBack(
   257  	cb packed_cb_fn,
   258  	r1, r2, r3, r4, r5, r6, r7 int64,
   259  	a int8, b int16, c int8, d bool, e int32, sm Small2, f int16, med Medium, g int8, big Big4, h uint8,
   260  ) int64
   261  func CallPackedHFABack(
   262  	cb packed_hfa_cb_fn,
   263  	r1, r2, r3, r4, r5, r6, r7 int64,
   264  	f0, f1, f2, f3, f4, f5 float64,
   265  	h3 Float3, fl float32, b int8, h2 Float2,
   266  ) int64
   267  
   268  -- p/main.go --
   269  package main
   270  
   271  import (
   272  	"fmt"
   273  	"os"
   274  	"unsafe"
   275  )
   276  
   277  import "C"
   278  
   279  //export GoCallback
   280  func GoCallback(a, b int32) int32 {
   281  	return a + b
   282  }
   283  
   284  //export GoPtrCallback
   285  func GoPtrCallback() unsafe.Pointer {
   286  	x := 42
   287  	return unsafe.Pointer(&x)
   288  }
   289  
   290  func recurseStack(n int32) int32 {
   291  	var buf [1024]byte
   292  	buf[0] = byte(n)
   293  	if n <= 0 {
   294  		return int32(buf[0])
   295  	}
   296  	return int32(buf[0]) + recurseStack(n-1)
   297  }
   298  
   299  //export GoGrowStack
   300  func GoGrowStack(n int32) {
   301  	_ = recurseStack(n)
   302  }
   303  
   304  //export GoGrowStackRet
   305  func GoGrowStackRet(in Big4) Big4 {
   306  	_ = recurseStack(64)
   307  	return Big4{a: in.a + 1, b: in.b + 2, c: in.c + 3, d: in.d + 4}
   308  }
   309  
   310  //export GoTakePtr
   311  func GoTakePtr(p unsafe.Pointer) int32 {
   312  	if p == nil {
   313  		return -1
   314  	}
   315  	return *(*int32)(p)
   316  }
   317  
   318  //export GoPackedCallback
   319  func GoPackedCallback(
   320  	r0, r1, r2, r3, r4, r5, r6, r7 int64,
   321  	a int8, b int16, c int8, d bool, e int32, sm Small2, f int16, med Medium, g int8, big Big4, h uint8,
   322  ) int64 {
   323  	if r0 != 10 || r1 != 1 || r2 != 2 || r3 != 3 || r4 != 4 || r5 != 5 || r6 != 6 || r7 != 7 {
   324  		return -11
   325  	}
   326  	if a != -4 || b != -1232 || c != 45 || d || e != -99996 {
   327  		return -12
   328  	}
   329  	if sm != (Small2{a: 0x13, b: 0x36}) || f != 5683 {
   330  		return -13
   331  	}
   332  	if med != (Medium{a: 1002, b: -2000, c: 3006}) || g != -93 {
   333  		return -14
   334  	}
   335  	if big != (Big4{a: 11, b: 22, c: 33, d: 44}) || h != 243 {
   336  		return -15
   337  	}
   338  	return 100
   339  }
   340  
   341  //export GoPackedHFACallback
   342  func GoPackedHFACallback(
   343  	r0, r1, r2, r3, r4, r5, r6, r7 int64,
   344  	f0, f1, f2, f3, f4, f5 float64,
   345  	h3 Float3, fl float32, b int8, h2 Float2,
   346  ) int64 {
   347  	if r0 != 10 || r1 != 1 || r2 != 2 || r3 != 3 || r4 != 4 || r5 != 5 || r6 != 6 || r7 != 7 {
   348  		return -21
   349  	}
   350  	if f0 != 1 || f1 != 2 || f2 != 3 || f3 != 4 || f4 != 5 || f5 != 6 {
   351  		return -22
   352  	}
   353  	if h3 != (Float3{a: 2.5, b: 3.5, c: 4.5}) || fl != 5.5 || b != -16 || h2 != (Float2{a: 6.5, b: 7.5}) {
   354  		return -23
   355  	}
   356  	return 200
   357  }
   358  
   359  func main() {
   360  	if len(os.Args) > 1 && os.Args[1] == "badptr" {
   361  		_ = CallPtrBack(ptr_cb_fn(C.GoPtrCallback))
   362  		return
   363  	}
   364  	if len(os.Args) > 1 && os.Args[1] == "badptr_direct" {
   365  		_ = C.GoPtrCallback()
   366  		return
   367  	}
   368  	if len(os.Args) > 1 && os.Args[1] == "badarg_direct" {
   369  		type holder struct {
   370  			p   *int32
   371  			val int32
   372  		}
   373  		h := &holder{p: new(int32), val: 99}
   374  		_ = C.GoTakePtr(unsafe.Pointer(h))
   375  		return
   376  	}
   377  	if len(os.Args) > 1 && os.Args[1] == "goodarg_direct" {
   378  		type holder struct {
   379  			p   *int32
   380  			val int32
   381  		}
   382  		h := &holder{p: new(int32), val: 99}
   383  		fmt.Printf("GoodArg=%d\n", C.GoTakePtr(unsafe.Pointer(&h.val)))
   384  		return
   385  	}
   386  	if len(os.Args) > 1 && os.Args[1] == "direct_and_fp" {
   387  		r1 := C.GoCallback(100, 200)
   388  		r2 := (C.GoCallback)(10, 20)
   389  		out := C.GoGrowStackRet(Big4{a: 100, b: 120, c: 150, d: 175})
   390  		fmt.Printf("DirectExp=%d,%d,%d\n", r1, r2, out.a+out.b+out.c+out.d)
   391  		c1 := C.CAdd(7, 8)
   392  		c2 := C.CallMeBack(C.cb_fn(C.CAdd), 7, 8)
   393  		c3 := C.CallUnary(C.unary_fn(C.abs), -42)
   394  		fmt.Printf("CFuncPtr=%d,%d,%d\n", c1, c2, c3)
   395  		return
   396  	}
   397  	if len(os.Args) > 1 && os.Args[1] == "growstack" {
   398  		out := CallGrowStack(grow_cb_fn(C.GoGrowStack), Big4{a: 100, b: 120, c: 150, d: 175})
   399  		fmt.Printf("GrowStack=%d\n", out.a+out.b+out.c+out.d)
   400  		return
   401  	}
   402  	if len(os.Args) > 1 && os.Args[1] == "packed" {
   403  		r1 := CallPackedBack(
   404  			packed_cb_fn(C.GoPackedCallback),
   405  			1, 2, 3, 4, 5, 6, 7,
   406  			-5, -1234, 42, true, -100000, Small2{a: 0x12, b: 0x34}, 5678,
   407  			Medium{a: 1001, b: -2002, c: 3003}, -99, Big4{a: 10, b: 20, c: 30, d: 40}, 250,
   408  		)
   409  		r2 := CallPackedHFABack(
   410  			packed_hfa_cb_fn(C.GoPackedHFACallback),
   411  			1, 2, 3, 4, 5, 6, 7,
   412  			1, 2, 3, 4, 5, 6,
   413  			Float3{a: 1.5, b: 2.5, c: 3.5}, 4.5, -17, Float2{a: 5.5, b: 6.5},
   414  		)
   415  		fmt.Printf("Packed=%d,%d\n", r1, r2)
   416  		return
   417  	}
   418  	fmt.Printf("Callback=%d\n", C.CallMeBack(C.cb_fn(C.GoCallback), 100, 200))
   419  }
   420  
   421  -- c/static.c --
   422  typedef int (*cb_fn)(int, int);
   423  int StaticAdd(int a, int b) { return a + b; }
   424  int CallStaticCb(cb_fn cb, int a, int b) { return cb(a, b); }
   425  
   426  -- badfp/go.mod --
   427  module badfp
   428  
   429  go 1.28
   430  
   431  -- badfp/badfp.go --
   432  package main
   433  
   434  import "C"
   435  
   436  //cgo:func CAdd C.CAdd libc
   437  func CAdd(a, b int32) int32
   438  
   439  //export GoCallback
   440  func GoCallback(a, b int32) int32 {
   441  	return a + b
   442  }
   443  
   444  func main() {
   445  	// Lines 17-20 test non-assignability and non-addressability of
   446  	// C.<export> and C.<cfunc> in non-call context.
   447  	_ = 0
   448  	C.GoCallback = nil
   449  	_ = &C.GoCallback
   450  	C.CAdd = nil
   451  	_ = &C.CAdd
   452  }
   453  
   454  -- staticfp/go.mod --
   455  module staticfp
   456  
   457  go 1.28
   458  
   459  -- staticfp/main.go --
   460  package main
   461  
   462  import "C"
   463  import "fmt"
   464  
   465  //cgo:type cb_fn C.cb_fn
   466  //cgo:func StaticAdd C.StaticAdd static
   467  //cgo:func CallStaticCb C.CallStaticCb static
   468  
   469  type cb_fn *[0]byte
   470  
   471  func StaticAdd(a, b int32) int32
   472  func CallStaticCb(cb cb_fn, a, b int32) int32
   473  
   474  func main() {
   475  	fmt.Printf("StaticFP=%d,%d\n", C.StaticAdd(20, 22), C.CallStaticCb(C.cb_fn(C.StaticAdd), 20, 22))
   476  }
   477  
   478  -- exp_archive/go.mod --
   479  module exp_archive
   480  
   481  go 1.28
   482  
   483  -- exp_archive/exp.go --
   484  package main
   485  
   486  // typedef struct { int x; } ExpPair;
   487  import "C"
   488  import "structs"
   489  
   490  //cgo:type ExpPair ExpPair
   491  
   492  type ExpPair struct {
   493  	_ structs.HostLayout
   494  	x int32
   495  }
   496  
   497  //export GoDoublePair
   498  func GoDoublePair(p ExpPair) ExpPair {
   499  	return ExpPair{x: p.x * 2}
   500  }
   501  
   502  func main() {}
   503  

View as plain text