Source file src/runtime/cgo/library.go

     1  // Copyright 2026 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  //go:build goexperiment.cgobindings
     6  
     7  package cgo
     8  
     9  import (
    10  	"errors"
    11  	"sync"
    12  	"unsafe"
    13  )
    14  
    15  // Library is a C shared library loaded at run time.
    16  //
    17  // Library is meant to be embedded in a struct type declared with a
    18  // //cgo:dynload pragma, whose methods, bound with //cgo:func and //cgo:var
    19  // pragmas, call functions and access variables in the library. See the
    20  // cgo command documentation for details.
    21  //
    22  // The zero value of Library is not usable; use [Open] to load a library.
    23  // For now, a library is never unloaded.
    24  type Library struct {
    25  	handle uintptr // dlopen or LoadLibrary handle; 0 if not loaded by Open
    26  
    27  	// syms holds the addresses of the symbols that cmd/cgo registered for
    28  	// the type embedding the Library, indexed by a per-type symbol index
    29  	// assigned by cmd/cgo. Open resolves all of them before it returns, and
    30  	// they are never written again.
    31  	syms []unsafe.Pointer
    32  }
    33  
    34  func (lib *Library) library() *Library { return lib }
    35  
    36  // Open loads the C shared library at path and returns a new *T for it.
    37  //
    38  // T must be a struct type that embeds Library, normally one declared with
    39  // a //cgo:dynload pragma. Open resolves all of the symbols bound to T's
    40  // methods, and fails if any of them is missing from the library. Each call
    41  // to Open returns a new instance, with its own symbol table, even if the
    42  // same library is opened more than once. On Unix, the library is loaded
    43  // with RTLD_NOW | RTLD_LOCAL, so its symbols are bound eagerly and are not
    44  // added to the global symbol namespace.
    45  // For now, libraries are never unloaded.
    46  func Open[T any, PT interface {
    47  	*T
    48  	library() *Library
    49  }](path string) (PT, error) {
    50  	if path == "" {
    51  		return nil, errors.New("cgo: Open: empty library path")
    52  	}
    53  	p := PT(new(T))
    54  	lib := p.library()
    55  	if lib == nil {
    56  		return nil, errors.New("cgo: Open: type must embed cgo.Library by value")
    57  	}
    58  	h, err := dlopen(path)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  	names := registeredSymbols(any((*T)(nil)))
    63  	syms := make([]unsafe.Pointer, len(names))
    64  	for i, name := range names {
    65  		addr, errMsg := dlsym(h, name)
    66  		if addr == nil {
    67  			return nil, errors.New("cgo: Open " + path + ": cannot resolve symbol " + name + ": " + errMsg)
    68  		}
    69  		syms[i] = addr
    70  	}
    71  	lib.handle = h
    72  	lib.syms = syms
    73  	return p, nil
    74  }
    75  
    76  var (
    77  	librariesMu sync.Mutex
    78  	libraries   map[any][]string // (*T)(nil) -> T's symbol names
    79  )
    80  
    81  // registerLibrary records the names of the symbols bound to the methods of
    82  // the type T embedding Library, where typ is (*T)(nil). The index of a name
    83  // in syms is the index that cmd/cgo assigned to the symbol, which is passed
    84  // to librarySymbol.
    85  //
    86  // registerLibrary is called by code generated by cmd/cgo, from package
    87  // initialization.
    88  //
    89  //go:linkname registerLibrary
    90  func registerLibrary(typ any, syms []string) {
    91  	librariesMu.Lock()
    92  	defer librariesMu.Unlock()
    93  	if libraries == nil {
    94  		libraries = make(map[any][]string)
    95  	}
    96  	libraries[typ] = syms
    97  }
    98  
    99  // registeredSymbols returns the symbol names registered for typ.
   100  func registeredSymbols(typ any) []string {
   101  	librariesMu.Lock()
   102  	defer librariesMu.Unlock()
   103  	return libraries[typ]
   104  }
   105  
   106  // librarySymbol returns the address of the symbol with the given index in
   107  // lib, as resolved by Open. It panics if lib was not returned by Open.
   108  //
   109  // librarySymbol is called by code generated by cmd/cgo.
   110  //
   111  //go:linkname librarySymbol
   112  func librarySymbol(lib *Library, index int) unsafe.Pointer {
   113  	if lib.handle == 0 {
   114  		panic("cgo: use of Library not returned by cgo.Open")
   115  	}
   116  	if uint(index) >= uint(len(lib.syms)) {
   117  		panic("cgo: internal error: bad symbol index")
   118  	}
   119  	return lib.syms[index]
   120  }
   121  

View as plain text