-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathBaseJniExtractor.java
More file actions
368 lines (333 loc) · 11.6 KB
/
Copy pathBaseJniExtractor.java
File metadata and controls
368 lines (333 loc) · 11.6 KB
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
* #%L
* Native library loader for extracting and loading native libraries from Java.
* %%
* Copyright (C) 2010 - 2023 Board of Regents of the University of
* Wisconsin-Madison and Glencoe Software, Inc.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
// This code is derived from Richard van der Hoff's mx-native-loader project:
// http://opensource.mxtelecom.com/maven/repo/com/wapmx/native/mx-native-loader/1.7/
// See NOTICE.txt for details.
// Copyright 2006 MX Telecom Ltd
package org.scijava.nativelib;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Richard van der Hoff (richardv@mxtelecom.com)
*/
public abstract class BaseJniExtractor implements JniExtractor {
private static final Logger LOGGER = LoggerFactory.getLogger(
"org.scijava.nativelib.BaseJniExtractor");
protected static final String JAVA_TMPDIR = "java.io.tmpdir";
protected static final String ALTR_TMPDIR = "."+ NativeLibraryUtil.DELIM + "tmplib";
protected static final String TMP_PREFIX = "nativelib-loader_";
private static final String LEFTOVER_MIN_AGE = "org.scijava.nativelib.leftoverMinAgeMs";
private static final long LEFTOVER_MIN_AGE_DEFAULT = 5 * 60 * 1000; // 5 minutes
private Class<?> libraryJarClass;
/**
* We use a resource path of the form META-INF/lib/${mx.sysinfo}/ This way
* native builds for multiple architectures can be packaged together without
* interfering with each other And by setting mx.sysinfo the jvm can pick the
* native libraries appropriate for itself.
*/
private String[] nativeResourcePaths;
public BaseJniExtractor() throws IOException {
init(null);
}
public BaseJniExtractor(final Class<?> libraryJarClass) throws IOException {
init(libraryJarClass);
}
private void init(final Class<?> libraryJarClass) {
this.libraryJarClass = libraryJarClass;
final String mxSysInfo = MxSysInfo.getMxSysInfo();
if (mxSysInfo != null) {
nativeResourcePaths =
new String[] { "natives/", "META-INF/lib/" + mxSysInfo + "/", "META-INF/lib/" };
}
else {
nativeResourcePaths = new String[] { "natives/", "META-INF/lib/" };
}
// clean up leftover libraries from previous runs
deleteLeftoverFiles();
}
private static boolean deleteRecursively(final File directory) {
if (directory == null) return true;
final File[] list = directory.listFiles();
if (list == null) return true;
for (final File file : list) {
if (file.isFile()) {
if (!file.delete()) return false;
}
else if (file.isDirectory()) {
if (!deleteRecursively(file)) return false;
}
}
return directory.delete();
}
protected static File getTempDir() throws IOException {
// creates a temporary directory for hosting extracted files
// If system tempdir is not available, use tmplib
File tmpDir = new File(System.getProperty(JAVA_TMPDIR, ALTR_TMPDIR));
if (!tmpDir.isDirectory()) {
tmpDir.mkdirs();
if (!tmpDir.isDirectory())
throw new IOException("Unable to create temporary directory " + tmpDir);
}
File tempFile = File.createTempFile(TMP_PREFIX, "");
tempFile.delete();
return tempFile;
}
/**
* this is where native dependencies are extracted to (e.g. tmplib/).
*
* @return native working dir
*/
public abstract File getNativeDir();
/**
* this is where JNI libraries are extracted to (e.g.
* tmplib/classloaderName.1234567890000.0/).
*
* @return jni working dir
*/
public abstract File getJniDir();
@Override
public File extractJni(final String libPath, final String libname)
throws IOException
{
String mappedlibName = System.mapLibraryName(libname);
debug("mappedLib is " + mappedlibName);
/*
* On Darwin, the default mapping is to .jnilib; but we use .dylibs so that library interdependencies are
* handled correctly. if we don't find a .jnilib, try .dylib instead.
*/
URL lib = null;
// if no class specified look for resources in the jar of this class
if (null == libraryJarClass) {
libraryJarClass = this.getClass();
}
// foolproof
String combinedPath = (libPath.equals("") || libPath.endsWith(NativeLibraryUtil.DELIM) ?
libPath : libPath + NativeLibraryUtil.DELIM) + mappedlibName;
lib = libraryJarClass.getClassLoader().getResource(combinedPath);
if (null == lib) {
/*
* On OS X, the default mapping changed from .jnilib to .dylib as of JDK 7, so
* we need to be prepared for the actual library and mapLibraryName disagreeing
* in either direction.
*/
final String altLibName;
if (mappedlibName.endsWith(".jnilib")) {
altLibName =
mappedlibName.substring(0, mappedlibName.length() - 7) + ".dylib";
}
else if (mappedlibName.endsWith(".dylib")) {
altLibName =
mappedlibName.substring(0, mappedlibName.length() - 6) + ".jnilib";
}
else {
altLibName = null;
}
if (altLibName != null) {
lib = getClass().getClassLoader().getResource(libPath + altLibName);
if (lib != null) {
mappedlibName = altLibName;
}
}
}
if (null != lib) {
debug("URL is " + lib.toString());
debug("URL path is " + lib.getPath());
return extractResource(getJniDir(), lib, mappedlibName);
}
debug("Couldn't find resource " + combinedPath);
return null;
}
@Override
public void extractRegistered() throws IOException {
debug("Extracting libraries registered in classloader " +
this.getClass().getClassLoader());
for (final String nativeResourcePath : nativeResourcePaths) {
final Enumeration<URL> resources =
this.getClass().getClassLoader().getResources(
nativeResourcePath + "AUTOEXTRACT.LIST");
while (resources.hasMoreElements()) {
final URL res = resources.nextElement();
extractLibrariesFromResource(res);
}
}
}
private void extractLibrariesFromResource(final URL resource)
throws IOException
{
debug("Extracting libraries listed in " + resource);
BufferedReader reader = null;
try {
URLConnection connection = resource.openConnection();
connection.setUseCaches(false);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
URL lib = null;
for (final String nativeResourcePath : nativeResourcePaths) {
lib =
this.getClass().getClassLoader().getResource(
nativeResourcePath + line);
if (lib != null) break;
}
if (lib != null) {
extractResource(getNativeDir(), lib, line);
}
else {
throw new IOException("Couldn't find native library " + line +
"on the classpath");
}
}
}
finally {
if (reader != null) {
reader.close();
}
}
}
/**
* Extract a resource to the tmp dir (this entry point is used for unit
* testing)
*
* @param dir the directory to extract the resource to
* @param resource the resource on the classpath
* @param outputName the filename to copy to (within the tmp dir)
* @return the extracted file
* @throws IOException
*/
File extractResource(final File dir, final URL resource,
final String outputName) throws IOException
{
InputStream in = null;
try {
URLConnection connection = resource.openConnection();
connection.setUseCaches(false);
in = connection.getInputStream();
// TODO there's also a getResourceAsStream
// make a lib file with exactly the same lib name
final File outfile = new File(getJniDir(), outputName);
debug("Extracting '" + resource + "' to '" +
outfile.getAbsolutePath() + "'");
// copy resource stream to temporary file
FileOutputStream out = null;
try {
out = new FileOutputStream(outfile);
copy(in, out);
} finally {
if (out != null) { out.close(); }
}
// note that this doesn't always work:
outfile.deleteOnExit();
return outfile;
} finally {
if (in != null) { in.close(); }
}
}
/**
* Looks in the temporary directory for leftover versions of temporary shared
* libraries.
* <p>
* If a temporary shared library is in use by another instance it won't
* delete.
* <p>
* An old library will be deleted only if its last modified date is at least
* LEFTOVER_MIN_AGE milliseconds old (default to 5 minutes)
* This was introduced to avoid a possible race condition when two instances (JVMs) run the same unpacking code
* and one of which manage to delete the extracted file of the other before the other gets a chance to load it
* <p>
* Another issue is that createTempFile only guarantees to use the first three
* characters of the prefix, so I could delete a similarly-named temporary
* shared library if I haven't loaded it yet.
*/
void deleteLeftoverFiles() {
final File tmpDirectory = new File(System.getProperty(JAVA_TMPDIR, ALTR_TMPDIR));
final File[] folders = tmpDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return name.startsWith(TMP_PREFIX);
}
});
if (folders == null) return;
long leftoverMinAge = getLeftoverMinAge();
for (final File folder : folders) {
// attempt to delete
long age = System.currentTimeMillis() - folder.lastModified();
if (age < leftoverMinAge) {
debug("Not deleting leftover folder " + folder + ": is " + age + "ms old");
continue;
}
debug("Deleting leftover folder: " + folder);
deleteRecursively(folder);
}
}
long getLeftoverMinAge() {
try {
return Long.parseLong(System.getProperty(LEFTOVER_MIN_AGE, String.valueOf(LEFTOVER_MIN_AGE_DEFAULT)));
} catch (NumberFormatException e) {
error("Cannot load leftover minimal age system property", e);
return LEFTOVER_MIN_AGE_DEFAULT;
}
}
/**
* copy an InputStream to an OutputStream.
*
* @param in InputStream to copy from
* @param out OutputStream to copy to
* @throws IOException if there's an error
*/
static void copy(final InputStream in, final OutputStream out)
throws IOException
{
final byte[] tmp = new byte[8192];
int len = 0;
while (true) {
len = in.read(tmp);
if (len <= 0) {
break;
}
out.write(tmp, 0, len);
}
}
private static void debug(final String message) {
LOGGER.debug(message);
}
private static void error(final String message, final Throwable t) {
LOGGER.error(message, t);
}
}