Source file
src/runtime/cgo/library_unix.go
1
2
3
4
5
6
7 package cgo
8
9 import (
10 "errors"
11 "internal/stringslite"
12 "runtime"
13 "sync"
14 "unsafe"
15 )
16
17
18
19 var dlMu sync.Mutex
20
21
22 func cStringToGo(p uintptr) string {
23 if p == 0 {
24 return ""
25 }
26 var n int
27 for *(*byte)(unsafe.Pointer(p + uintptr(n))) != 0 {
28 n++
29 }
30 return string(unsafe.Slice((*byte)(unsafe.Pointer(p)), n))
31 }
32
33 func dlerrorLocked() string {
34 return cStringToGo(asmcgocall(uintptr(libc_dlerror), 0, 0, 0, 0, 0, 0))
35 }
36
37 func dlopen(path string) (uintptr, error) {
38 if stringslite.IndexByte(path, 0) >= 0 {
39 return 0, errors.New("cgo: dlopen: path contains NUL byte")
40 }
41 cpath := append([]byte(path), 0)
42 dlMu.Lock()
43 defer dlMu.Unlock()
44 runtime.LockOSThread()
45 defer runtime.UnlockOSThread()
46 tsanAcquire()
47 defer tsanRelease()
48
49 asmcgocall(uintptr(libc_dlerror), 0, 0, 0, 0, 0, 0)
50 h := cgocall(uintptr(libc_dlopen), uintptr(unsafe.Pointer(&cpath[0])), dlopenFlags, 0, 0, 0, 0)
51 runtime.KeepAlive(cpath)
52 if h == 0 {
53 msg := dlerrorLocked()
54 if msg == "" {
55 msg = path + ": unknown dlopen error"
56 }
57 return 0, errors.New("cgo: dlopen: " + msg)
58 }
59 return h, nil
60 }
61
62 func dlsym(h uintptr, name string) (unsafe.Pointer, string) {
63 if stringslite.IndexByte(name, 0) >= 0 {
64 return nil, "symbol name contains NUL byte"
65 }
66 cname := append([]byte(name), 0)
67 dlMu.Lock()
68 defer dlMu.Unlock()
69 runtime.LockOSThread()
70 defer runtime.UnlockOSThread()
71 tsanAcquire()
72 defer tsanRelease()
73
74 asmcgocall(uintptr(libc_dlerror), 0, 0, 0, 0, 0, 0)
75 ret := cgocall(uintptr(libc_dlsym), h, uintptr(unsafe.Pointer(&cname[0])), 0, 0, 0, 0)
76 runtime.KeepAlive(cname)
77 if ret == 0 {
78 msg := dlerrorLocked()
79 if msg == "" {
80 msg = "unknown error"
81 }
82 return nil, msg
83 }
84 return *(*unsafe.Pointer)(unsafe.Pointer(&ret)), ""
85 }
86
View as plain text