-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdl_posix.go
144 lines (109 loc) · 2.13 KB
/
dl_posix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// +build darwin linux
package dl
// #include <dlfcn.h>
// #include <stdlib.h>
import "C"
import (
"runtime"
"sync"
"syscall"
"unsafe"
)
type dylib struct {
mutex sync.RWMutex
handle unsafe.Pointer
}
func open(path string, mode Mode) (lib *dylib, err error) {
var handle unsafe.Pointer
var flags int
if (mode & Lazy) == 0 && (mode & Now) == 0 {
mode |= Now
}
if (mode & Lazy) != 0 {
flags |= C.RTLD_LAZY
}
if (mode & Now) != 0 {
flags |= C.RTLD_NOW
}
if (mode & Global) != 0 {
flags |= C.RTLD_GLOBAL
}
if (mode & Local) != 0 {
flags |= C.RTLD_LOCAL
}
if handle, err = dlopen(path, flags); err != nil {
return
}
lib = &dylib{
handle: handle,
}
runtime.SetFinalizer(lib, (*dylib).close)
return
}
func (lib *dylib) Close() (err error) {
lib.mutex.Lock()
defer lib.mutex.Unlock()
return lib.close()
}
func (lib *dylib) Symbol(name string) (addr uintptr, err error) {
var handle unsafe.Pointer
var sym unsafe.Pointer
lib.mutex.RLock()
defer lib.mutex.RUnlock()
if handle = lib.handle; handle == nil {
err= syscall.EINVAL
return
}
if sym, err = dlsym(handle, name); err != nil {
return
}
addr = uintptr(sym)
return
}
func (lib *dylib) close() (err error) {
var handle unsafe.Pointer
if handle, lib.handle = lib.handle, nil; handle != nil {
err = dlclose(handle)
} else {
err = syscall.EINVAL
}
return
}
var dlmtx sync.Mutex
func dlopen(path string, flags int) (lib unsafe.Pointer, err error) {
var f = C.int(flags)
var s *C.char
if len(path) != 0 {
s = C.CString(path)
defer C.free(unsafe.Pointer(s))
}
dlmtx.Lock()
defer dlmtx.Unlock()
if lib = C.dlopen(s, f); lib == nil {
err = dlerror()
}
return
}
func dlclose(lib unsafe.Pointer) (err error) {
dlmtx.Lock()
defer dlmtx.Unlock()
if C.dlclose(lib) != 0 {
err = dlerror()
}
return
}
func dlsym(lib unsafe.Pointer, name string) (addr unsafe.Pointer, err error) {
var s = C.CString(name)
defer C.free(unsafe.Pointer(s))
dlmtx.Lock()
defer dlmtx.Unlock()
if addr = C.dlsym(lib, s); addr == nil {
err = dlerror()
}
return
}
func dlerror() error {
return &Error{
Message: C.GoString(C.dlerror()),
}
}