-
Notifications
You must be signed in to change notification settings - Fork 4
/
base.clj
297 lines (230 loc) · 8.94 KB
/
base.clj
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
(ns tech.jna.base
(:require [clojure.java.io]
[clojure.string :as s]
[clojure.tools.logging :as log])
(:import [com.sun.jna Native NativeLibrary Pointer Function Platform]
[com.sun.jna.ptr PointerByReference]
[java.lang.reflect Method]
[java.io File]))
(set! *warn-on-reflection* true)
(defn- log-load-attempt
[libname pathtype path success?]
(let [log-str (format "Attempting to load %s: %s %s - %s"
libname pathtype path (if success?
"succeeded!"
"failed"))]
(log/info log-str)))
(def native-lib-methods
(->> (.getDeclaredMethods NativeLibrary)
(map (fn [^Method method]
{:name (.getName method)
:method method}))
(group-by :name)))
(def map-shared-libname-native
(-> (get native-lib-methods "mapSharedLibraryName")
first
:method
((fn [^Method method]
(.setAccessible method true)
method))))
(defn map-shared-library-name
[libname]
(.invoke ^Method map-shared-libname-native
NativeLibrary (object-array [libname])))
(def ^:dynamic *library-name->paths* (atom {}))
(defn add-library-path
"Path order has to be explicitly controlled by the user."
[libname path-type path]
(swap! *library-name->paths*
update libname
(fn [existing-paths]
(if-not existing-paths
[[path-type path]]
(->> (conj existing-paths [path-type path])
distinct
vec)))))
(defn clear-library-paths
[libname]
(swap! *library-name->paths* dissoc libname))
(defn library-paths
[libname]
(get @*library-name->paths* libname))
(defn add-resource-path
"Look in resources for library"
[libname & [libpath class-loader]]
(add-library-path libname :resource
{:path (or libpath libname)
;;Uses current thread classloader if non provided.
:class-loader class-loader}))
(defn add-java-library-path-path
[libname & [libpath]]
(add-library-path libname :java-library-path (or libpath libname)))
(defmulti expand-pathtype
(fn [pathtype & _]
pathtype))
(defmethod expand-pathtype :default
[_ path]
path)
;;No mangling, jna takes care of this.
(defmethod expand-pathtype :system
[_ path]
path)
(defmethod expand-pathtype :resource
[_ {:keys [path class-loader]}]
(let [^File file
(try
(if class-loader
(Native/extractFromResourcePath ^String path class-loader)
(Native/extractFromResourcePath ^String path))
(catch Throwable e
(log/infof e "Failed to find library %s as a resource" path)))]
(if file
(.getCanonicalPath file)
path)))
(defmethod expand-pathtype :java-library-path
[_ path]
(let [path (map-shared-library-name path)]
(->> (s/split (System/getProperty "java.library.path") #":")
(map #(str % File/separator path)))))
(defn do-load-library
[libname]
(let [pathtypes (get @*library-name->paths* libname)
pathtypes (if-not (seq pathtypes)
[[:system libname]
[:java-library-path libname]]
pathtypes)
;;Dedup but preserve order
path-order (->> pathtypes
(map first)
distinct)
deduped (->> pathtypes
(group-by first)
(map (fn [[pathtype pathtype-pairs]]
[pathtype (->> pathtype-pairs
(map second)
distinct)]))
(into {}))
paths (->> path-order
(mapcat (fn [pathtype]
(->> (get deduped pathtype)
(mapcat (fn [pathtype-path]
(let [expanded (expand-pathtype pathtype pathtype-path)]
(if (string? expanded)
[[pathtype expanded]]
(map #(vector pathtype %) expanded)))))))))
retval (->> paths
(map (fn [[pathname load-path]]
(try
[pathname load-path
(NativeLibrary/getInstance load-path)]
(catch Throwable _))))
(remove nil?)
first)]
(when-not retval
(throw (ex-info "Failed to load library"
{:libname libname
:paths (let [pathmap (->> (group-by first paths)
(map #(vector (first %)
(mapv second (second %))))
(into {}))]
(->> path-order
(mapv #(vector % (get pathmap %)))))})))
(log/infof "Library %s found at %s" libname [(first retval) (second retval)])
(last retval)))
(def ^:dynamic *loaded-libraries* (atom {}))
(defn load-library
^NativeLibrary [libname]
(if-let [retval (get @*loaded-libraries* libname)]
retval
(let [retval (do-load-library libname)]
(swap! *loaded-libraries* assoc libname retval)
retval)))
(defn jar-native-library-path
"If you want java-library-path setup for you you need to put
native libraries under this location:"
[]
(let [resource-path Platform/RESOURCE_PREFIX
first-dash-idx (.indexOf resource-path "-")]
(str "native"
File/separator
(.substring resource-path 0 first-dash-idx)
File/separator
(.substring resource-path (+ first-dash-idx 1)))))
(defn ensure-type
[item-cls item]
(when-not (instance? item-cls item)
(throw (ex-info "Item is not desired type"
{:item-cls item-cls
:item item})))
item)
(defn set-loaded-library!
[libname native-library]
(ensure-type NativeLibrary native-library)
(swap! *loaded-libraries* assoc libname native-library))
(def do-find-function
(fn [fn-name libname]
(.getFunction ^NativeLibrary (load-library libname) fn-name)))
(defn find-function
^Function [fn-name libname]
(do-find-function fn-name libname))
(defn unsafe-read-byte
[^Pointer byte-ary ^long idx]
(.get (.getByteBuffer byte-ary idx 1) 0))
(defn variable-byte-ptr->string
"Convert a c-string into a string"
[^Pointer ptr-addr]
(if (= 0 (Pointer/nativeValue ptr-addr))
""
(String. ^"[B"
(into-array Byte/TYPE
(take-while #(not= % 0)
(map #(unsafe-read-byte
ptr-addr %)
(range)))))))
(defn char-ptr-ptr->string-vec
"Decode a char** ptr."
[^long num-strings ^Pointer char-ptr-ptr]
(let [base-address (Pointer/nativeValue char-ptr-ptr)]
(->> (range num-strings)
(map (fn [name-idx]
(let [new-ptr (-> (+ (* (long name-idx) Native/POINTER_SIZE)
base-address)
(Pointer.))
char-ptr (case Native/POINTER_SIZE
8 (.getLong new-ptr 0)
4 (.getInt new-ptr 0))]
(variable-byte-ptr->string (Pointer. char-ptr)))))
;;Don't be lazy. the ptr may be released.
vec)))
(defn ensure-ptr-ptr
^PointerByReference [item]
(ensure-type PointerByReference item))
(defn ensure-ptr
^Pointer [item]
(ensure-type Pointer item))
(defn to-typed-fn
^Function [item] item)
(defmacro def-jna-fn
"TVM functions are very regular so the mapping to them can exploit this.
Argpair is of type [symbol type-coersion]."
[libname fn-name docstring rettype & argpairs]
`(defn ~fn-name
~docstring
~(mapv first argpairs)
(let [~'tvm-fn (find-function ~(str fn-name) ~libname)
~'fn-args (object-array ~(mapv (fn [[arg-symbol arg-coersion]]
(when (= arg-symbol arg-coersion)
(throw (ex-info (format "Argument symbol (%s) cannot match coersion (%s)"
arg-symbol arg-coersion)
{})))
`(~arg-coersion ~arg-symbol))
argpairs))]
~(if rettype
`(.invoke (to-typed-fn ~'tvm-fn) ~rettype ~'fn-args)
`(.invoke (to-typed-fn ~'tvm-fn) ~'fn-args)))))
(defn c-library-name
^String []
(Platform/C_LIBRARY_NAME))
(defn math-library-name
^String []
(Platform/MATH_LIBRARY_NAME))