Source file src/runtime/cgo/library_unix_c.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 && unix && (msan || tsan)
     6  
     7  package cgo
     8  
     9  /*
    10  #cgo linux LDFLAGS: -ldl
    11  
    12  #include <dlfcn.h>
    13  #include <stdint.h>
    14  
    15  static uintptr_t
    16  cgo_dlopen(const char *path, char **errp) {
    17  	int flags = RTLD_NOW | RTLD_LOCAL;
    18  	void *h;
    19  
    20  #ifdef _AIX
    21  	flags |= RTLD_MEMBER;
    22  #endif
    23  	*errp = NULL;
    24  	dlerror();
    25  	h = dlopen(path, flags);
    26  	if (h == NULL) {
    27  		*errp = (char *)dlerror();
    28  	}
    29  	return (uintptr_t)h;
    30  }
    31  
    32  static void *
    33  cgo_dlsym(uintptr_t h, const char *name, char **errp) {
    34  	void *p;
    35  
    36  	*errp = NULL;
    37  	dlerror();
    38  	p = dlsym((void *)h, name);
    39  	if (p == NULL) {
    40  		*errp = (char *)dlerror();
    41  	}
    42  	return p;
    43  }
    44  */
    45  import "C"
    46  
    47  import (
    48  	"errors"
    49  	"internal/stringslite"
    50  	"sync"
    51  	"unsafe"
    52  )
    53  
    54  // dlMu serializes dlopen/dlsym/dlerror calls because POSIX does not guarantee
    55  // that dlerror uses thread-local storage (for example on OpenBSD/Solaris).
    56  var dlMu sync.Mutex
    57  
    58  func dlopen(path string) (uintptr, error) {
    59  	if stringslite.IndexByte(path, 0) >= 0 {
    60  		return 0, errors.New("cgo: dlopen: path contains NUL byte")
    61  	}
    62  	cpath := append([]byte(path), 0)
    63  	dlMu.Lock()
    64  	defer dlMu.Unlock()
    65  
    66  	var cErr *C.char
    67  	h := uintptr(C.cgo_dlopen((*C.char)(unsafe.Pointer(&cpath[0])), &cErr))
    68  	if h == 0 {
    69  		msg := ""
    70  		if cErr != nil {
    71  			msg = C.GoString(cErr)
    72  		}
    73  		if msg == "" {
    74  			msg = path + ": unknown dlopen error"
    75  		}
    76  		return 0, errors.New("cgo: dlopen: " + msg)
    77  	}
    78  	return h, nil
    79  }
    80  
    81  func dlsym(h uintptr, name string) (unsafe.Pointer, string) {
    82  	if stringslite.IndexByte(name, 0) >= 0 {
    83  		return nil, "symbol name contains NUL byte"
    84  	}
    85  	cname := append([]byte(name), 0)
    86  	dlMu.Lock()
    87  	defer dlMu.Unlock()
    88  
    89  	var cErr *C.char
    90  	ret := C.cgo_dlsym(C.uintptr_t(h), (*C.char)(unsafe.Pointer(&cname[0])), &cErr)
    91  	if ret == nil {
    92  		msg := ""
    93  		if cErr != nil {
    94  			msg = C.GoString(cErr)
    95  		}
    96  		if msg == "" {
    97  			msg = "unknown error"
    98  		}
    99  		return nil, msg
   100  	}
   101  	return ret, ""
   102  }
   103  

View as plain text