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

     1  # Test shared libraries loaded at run time with //cgo:dynload types and
     2  # hand-written bindings.
     3  
     4  env GOEXPERIMENT=$GOEXPERIMENT,runtimecgopurego,cgobindings
     5  [!GOEXPERIMENT:cgobindings] skip
     6  [!GOOS:darwin] [!GOOS:linux] skip
     7  [!GOARCH:amd64] [!GOARCH:arm64] skip
     8  [!exec:cc] skip
     9  
    10  mkdir lib
    11  cc -fPIC -shared -o lib/libmul.so c/mul.c
    12  [GOOS:linux] cc -fPIC -shared -o lib/libadd.so c/add.c -ldl
    13  [!GOOS:linux] cc -fPIC -shared -o lib/libadd.so c/add.c
    14  
    15  cd dyn
    16  env CGO_ENABLED=bindings
    17  env CC=/bin/false
    18  env LIBMUL=$PWD/../lib/libmul.so
    19  env LIBADD=$PWD/../lib/libadd.so
    20  go run .
    21  stdout '^mul: compute=42 counter=7 name=mul$'
    22  stdout '^add: compute=13 counter=7 name=add$'
    23  stdout '^mul: counter=8$'
    24  stdout '^add: counter=7$'
    25  stdout '^local: ok$'
    26  stdout '^missing: ok$'
    27  stdout '^init: ok$'
    28  stdout '^directives: ok$'
    29  stdout '^concurrent: ok$'
    30  
    31  [race] go run -race .
    32  [race] stdout '^concurrent: ok$'
    33  
    34  -- c/mul.c --
    35  int Counter = 7;
    36  int Compute(int a, int b) { return a * b; }
    37  int MulOnlySym(void) { return 123; }
    38  void Bump(void) { Counter++; }
    39  
    40  -- c/add.c --
    41  #define _GNU_SOURCE
    42  #include <dlfcn.h>
    43  
    44  int Counter = 7;
    45  int Compute(int a, int b) { return a + b; }
    46  int GlobalSeesMulOnly(void) { return dlsym(RTLD_DEFAULT, "MulOnlySym") != 0; }
    47  void Bump(void) { Counter++; }
    48  
    49  -- dyn/go.mod --
    50  module dyn
    51  
    52  go 1.28
    53  
    54  -- dyn/a_init.go --
    55  package main
    56  
    57  import (
    58  	"os"
    59  	"runtime/cgo"
    60  )
    61  
    62  // pkgCalc is opened while initializing package variables, and initCalc by
    63  // an init function in a file that is compiled before the code generated by
    64  // cmd/cgo. Open must resolve their symbols in both cases.
    65  var pkgCalc, pkgErr = cgo.Open[Calc](os.Getenv("LIBMUL"))
    66  
    67  var initCalc *Calc
    68  
    69  func init() {
    70  	var err error
    71  	initCalc, err = cgo.Open[Calc](os.Getenv("LIBMUL"))
    72  	if err != nil {
    73  		panic(err)
    74  	}
    75  }
    76  
    77  -- dyn/b_directives.go --
    78  package main
    79  
    80  import _ "embed"
    81  
    82  // The first declarations of a file keep their directives.
    83  
    84  //go:embed data.txt
    85  var data string
    86  
    87  //go:noinline
    88  func dataLen() int { return len(data) }
    89  
    90  -- dyn/c_noimports.go --
    91  package main
    92  
    93  //go:noinline
    94  func two() int { return 2 }
    95  
    96  -- dyn/data.txt --
    97  hello
    98  -- dyn/lib.go --
    99  package main
   100  
   101  import "C"
   102  import "runtime/cgo"
   103  
   104  //cgo:dynload Calc
   105  //cgo:func Calc.Compute Compute
   106  //cgo:func Calc.Bump Bump
   107  //cgo:var Calc.Counter Counter
   108  
   109  // Calc is the API shared by libmul.so and libadd.so.
   110  type Calc struct {
   111  	cgo.Library
   112  	name string
   113  }
   114  
   115  func (*Calc) Compute(a, b int32) int32
   116  
   117  func (*Calc) Bump()
   118  
   119  func (*Calc) Counter() *int32
   120  
   121  //cgo:dynload MulOnly
   122  //cgo:func MulOnly.MulOnlySym MulOnlySym
   123  
   124  // MulOnly is the API only provided by libmul.so.
   125  type MulOnly struct {
   126  	cgo.Library
   127  }
   128  
   129  func (*MulOnly) MulOnlySym() int32
   130  
   131  //cgo:dynload AddOnly
   132  //cgo:func AddOnly.GlobalSeesMulOnly GlobalSeesMulOnly
   133  
   134  // AddOnly is the API only provided by libadd.so.
   135  type AddOnly struct {
   136  	cgo.Library
   137  }
   138  
   139  func (*AddOnly) GlobalSeesMulOnly() int32
   140  
   141  -- dyn/main.go --
   142  package main
   143  
   144  import (
   145  	"fmt"
   146  	"os"
   147  	"runtime/cgo"
   148  	"strings"
   149  	"sync"
   150  )
   151  
   152  func open(path, name string) *Calc {
   153  	c, err := cgo.Open[Calc](path)
   154  	if err != nil {
   155  		panic(err)
   156  	}
   157  	c.name = name
   158  	return c
   159  }
   160  
   161  func main() {
   162  	mul := open(os.Getenv("LIBMUL"), "mul")
   163  	add := open(os.Getenv("LIBADD"), "add")
   164  	for _, c := range []*Calc{mul, add} {
   165  		fmt.Printf("%s: compute=%d counter=%d name=%s\n", c.name, c.Compute(6, 7), *c.Counter(), c.name)
   166  	}
   167  
   168  	// Each instance refers to its own library's variables.
   169  	mul.Bump()
   170  	fmt.Printf("mul: counter=%d\n", *mul.Counter())
   171  	fmt.Printf("add: counter=%d\n", *add.Counter())
   172  
   173  	// Libraries are loaded locally (RTLD_LOCAL), so a symbol exported by
   174  	// libmul.so must not leak into the global symbol namespace seen by
   175  	// libadd.so via dlsym(RTLD_DEFAULT, ...).
   176  	mulOnly, err := cgo.Open[MulOnly](os.Getenv("LIBMUL"))
   177  	if err != nil {
   178  		panic(err)
   179  	}
   180  	if got := mulOnly.MulOnlySym(); got != 123 {
   181  		fmt.Printf("MulOnlySym() = %d, want 123\n", got)
   182  		os.Exit(1)
   183  	}
   184  	addOnly, err := cgo.Open[AddOnly](os.Getenv("LIBADD"))
   185  	if err != nil {
   186  		panic(err)
   187  	}
   188  	if got := addOnly.GlobalSeesMulOnly(); got != 0 {
   189  		fmt.Printf("GlobalSeesMulOnly() = %d, want 0 (RTLD_LOCAL violated)\n", got)
   190  		os.Exit(1)
   191  	}
   192  	fmt.Println("local: ok")
   193  
   194  	// Open resolves all symbols when it loads the library, so it fails if
   195  	// one of them is missing.
   196  	if l, err := cgo.Open[MulOnly](os.Getenv("LIBADD")); err == nil || !strings.Contains(err.Error(), "cannot resolve symbol MulOnlySym") {
   197  		fmt.Printf("Open[MulOnly](libadd.so) = %v, %v, want cannot resolve symbol MulOnlySym error\n", l, err)
   198  		os.Exit(1)
   199  	}
   200  	fmt.Println("missing: ok")
   201  
   202  	if pkgErr != nil || pkgCalc.Compute(2, 3) != 6 || initCalc.Compute(2, 3) != 6 {
   203  		fmt.Printf("Calc opened during initialization: %v\n", pkgErr)
   204  		os.Exit(1)
   205  	}
   206  	fmt.Println("init: ok")
   207  
   208  	if dataLen() != len("hello\n") || two() != 2 {
   209  		fmt.Printf("dataLen() = %d, two() = %d\n", dataLen(), two())
   210  		os.Exit(1)
   211  	}
   212  	fmt.Println("directives: ok")
   213  
   214  	var wg sync.WaitGroup
   215  	errs := make(chan string, 64)
   216  	for i := range 32 {
   217  		wg.Add(1)
   218  		go func() {
   219  			defer wg.Done()
   220  			c, want := mul, int32(i*3)
   221  			if i%2 == 1 {
   222  				c, want = add, int32(i+3)
   223  			}
   224  			if got := c.Compute(int32(i), 3); got != want {
   225  				errs <- fmt.Sprintf("%s.Compute(%d, 3) = %d, want %d", c.name, i, got, want)
   226  			}
   227  		}()
   228  	}
   229  	wg.Wait()
   230  	close(errs)
   231  	for e := range errs {
   232  		fmt.Println(e)
   233  		os.Exit(1)
   234  	}
   235  	fmt.Println("concurrent: ok")
   236  }
   237  

View as plain text