-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInternal.java
More file actions
361 lines (331 loc) · 12.7 KB
/
Copy pathInternal.java
File metadata and controls
361 lines (331 loc) · 12.7 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
/*
* Copyright 2010 ALM Works Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.almworks.sqlite4java;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
final class Internal {
private static final Logger logger = Logger.getLogger("com.almworks.sqlite4java");
private static final String LOG_PREFIX = "[sqlite] ";
private static final String BASE_LIBRARY_NAME = "sqlite4java";
private static final String[] DEBUG_SUFFIXES = {"-d", ""};
private static final String[] RELEASE_SUFFIXES = {"", "-d"};
private static final AtomicInteger lastConnectionNumber = new AtomicInteger(0);
static int nextConnectionNumber() {
return lastConnectionNumber.incrementAndGet();
}
static void recoverableError(Object source, String message, boolean throwAssertion) {
logWarn(source, message);
assert !throwAssertion : source + " " + message;
}
static void log(Level level, Object source, Object message, Throwable exception) {
if (!logger.isLoggable(level)) {
return;
}
StringBuilder builder = new StringBuilder(LOG_PREFIX);
if (source != null) {
if (source instanceof Class) {
String className = ((Class) source).getName();
builder.append(className.substring(className.lastIndexOf('.') + 1));
} else {
builder.append(source);
}
builder.append(": ");
}
if (message != null)
builder.append(message);
logger.log(level, builder.toString(), exception);
}
static void logFine(Object source, Object message) {
log(Level.FINE, source, message, null);
}
static void logInfo(Object source, Object message) {
log(Level.INFO, source, message, null);
}
static void logWarn(Object source, Object message) {
log(Level.WARNING, source, message, null);
}
static boolean isFineLogging() {
return logger.isLoggable(Level.FINE);
}
static Throwable loadLibraryX() {
if (checkLoaded() == null)
return null;
if ("true".equalsIgnoreCase(System.getProperty("sqlite4java.debug"))) {
logger.setLevel(Level.FINE);
}
String classUrl = getClassUrl();
String defaultPath = getDefaultLibPath(classUrl);
String versionSuffix = getVersionSuffix(classUrl);
String forcedPath = getForcedPath();
if (Internal.isFineLogging()) {
logFine(Internal.class, "loading library");
logFine(Internal.class, "java.library.path=" + System.getProperty("java.library.path"));
logFine(Internal.class, "sqlite4java.library.path=" + System.getProperty("sqlite4java.library.path"));
logFine(Internal.class, "cwd=" + new File(".").getAbsolutePath());
logFine(Internal.class, "default path=" + (defaultPath == null ? "null " : new File(defaultPath).getAbsolutePath()));
logFine(Internal.class, "forced path=" + (forcedPath == null ? "null " : new File(forcedPath).getAbsolutePath()));
}
String os = getOs();
String arch = getArch(os);
RuntimeException loadedSignal = new RuntimeException("loaded");
Throwable bestReason = null;
try {
String[] suffixes = SQLite.isDebugBinaryPreferred() ? DEBUG_SUFFIXES : RELEASE_SUFFIXES;
if (versionSuffix != null) {
for (String suffix : suffixes) {
bestReason = tryLoadWithSuffix(suffix + versionSuffix, os, arch, bestReason, loadedSignal, defaultPath, forcedPath);
}
}
for (String suffix : suffixes) {
bestReason = tryLoadWithSuffix(suffix, os, arch, bestReason, loadedSignal, defaultPath, forcedPath);
}
if (bestReason == null)
bestReason = new SQLiteException(SQLiteConstants.WRAPPER_CANNOT_LOAD_LIBRARY, "sqlite4java cannot load native library");
return bestReason;
} catch (RuntimeException e) {
if (e == loadedSignal) {
String msg = getLibraryVersionMessage();
Internal.logInfo(Internal.class, msg);
return null;
} else {
throw e;
}
}
}
private static String getForcedPath() {
String r = System.getProperty(SQLite.LIBRARY_PATH_PROPERTY);
if (r == null || r.length() == 0)
return null;
r = r.replace('\\', File.separatorChar).replace('/', File.separatorChar);
return r;
}
private static String getClassUrl() {
Class c = Internal.class;
String name = c.getName().replace('.', '/') + ".class";
URL url = c.getClassLoader().getResource(name);
if (url == null)
return null;
String classUrl = url.toString();
try {
return URLDecoder.decode(classUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
recoverableError(Internal.class, e.getMessage(), true);
return classUrl;
}
}
private static String getArch(String os) {
String arch = System.getProperty("os.arch");
if (arch == null) {
logWarn(Internal.class, "os.arch is null");
arch = "x86";
} else {
arch = arch.toLowerCase(Locale.US);
if ("win32".equals(os) && "amd64".equals(arch)) {
arch = "x64";
}
}
logFine(Internal.class, "os.arch=" + arch);
return arch;
}
private static String getOs() {
String osname = System.getProperty("os.name");
String os;
if (osname == null) {
logWarn(Internal.class, "os.name is null");
os = "linux";
} else {
osname = osname.toLowerCase(Locale.US);
if (osname.startsWith("mac") || osname.startsWith("darwin") || osname.startsWith("os x")) {
os = "osx";
} else if (osname.startsWith("windows")) {
os = "win32";
} else {
os = "linux";
}
}
logFine(Internal.class, "os.name=" + osname + "; os=" + os);
return os;
}
private static String getDefaultLibPath(String classUrl) {
return getDefaultLibPath(System.getProperty("java.library.path"), classUrl);
}
static String getDefaultLibPath(String libraryPath, String classUrl) {
File jar = getJarFileFromClassUrl(classUrl);
if (jar == null)
return null;
File loadDir = jar.getParentFile();
if (loadDir.getPath().length() == 0 || !loadDir.isDirectory())
return null;
if (libraryPath == null)
libraryPath = "";
boolean contains = false;
char sep = File.pathSeparatorChar;
if (libraryPath.length() > 0) {
int k = 0;
while (k < libraryPath.length()) {
int p = libraryPath.indexOf(sep, k);
if (p < 0) {
p = libraryPath.length();
}
if (loadDir.equals(new File(libraryPath.substring(k, p)))) {
contains = true;
break;
}
k = p + 1;
}
}
String loadPath = loadDir.getPath();
if (contains) {
return null;
} else {
// logFine(Internal.class, "appending to library path: [" + loadPath + "]");
return loadPath;
}
}
private static File getJarFileFromClassUrl(String classUrl) {
if (classUrl == null)
return null;
String s = classUrl;
String prefix = "jar:file:";
if (!s.startsWith(prefix))
return null;
s = s.substring(prefix.length());
int k = s.lastIndexOf('!');
if (k < 0)
return null;
File jar = new File(s.substring(0, k));
if (!jar.isFile())
return null;
return jar;
}
// gets the suffix used in jar file - will check libs with that suffix too - or null
static String getVersionSuffix(String classUrl) {
File jar = getJarFileFromClassUrl(classUrl);
if (jar == null)
return null;
String name = jar.getName();
String lower = name.toLowerCase(Locale.US);
if (!lower.startsWith(BASE_LIBRARY_NAME))
return null;
if (!lower.endsWith(".jar"))
return null;
int f = BASE_LIBRARY_NAME.length();
int t = name.length() - 4; // ".jar".length()
return f + 1 < t && name.charAt(f) == '-' ? name.substring(f, t) : null;
}
private static Throwable tryLoadWithSuffix(String suffix, String os, String arch, Throwable bestReason, RuntimeException loadedSignal, String defaultPath, String forcedPath) {
Throwable t = bestReason;
t = tryLoad(BASE_LIBRARY_NAME + "-" + os + "-" + arch + suffix, t, loadedSignal, defaultPath, forcedPath);
if (arch.equals("x86_64") || arch.equals("x64")) {
t = tryLoad(BASE_LIBRARY_NAME + "-" + os + "-amd64" + suffix, t, loadedSignal, defaultPath, forcedPath);
} else if (arch.equals("powerpc")) {
t = tryLoad(BASE_LIBRARY_NAME + "-" + os + "-ppc" + suffix, t, loadedSignal, defaultPath, forcedPath);
} else if (arch.equals("x86")) {
t = tryLoad(BASE_LIBRARY_NAME + "-" + os + "-i386" + suffix, t, loadedSignal, defaultPath, forcedPath);
} else if (arch.equals("i386")) {
t = tryLoad(BASE_LIBRARY_NAME + "-" + os + "-x86" + suffix, t, loadedSignal, defaultPath, forcedPath);
}
if ("osx".equals(os)) {
t = tryLoad(BASE_LIBRARY_NAME + "-" + os + "-10.4" + suffix, t, loadedSignal, defaultPath, forcedPath);
}
t = tryLoad(BASE_LIBRARY_NAME + "-" + os + suffix, t, loadedSignal, defaultPath, forcedPath);
t = tryLoad(BASE_LIBRARY_NAME + suffix, t, loadedSignal, defaultPath, forcedPath);
return t;
}
private static Throwable tryLoad(String libname, Throwable bestReason, RuntimeException loadedSignal, String defaultPath, String forcedPath) {
Throwable t = bestReason;
if (forcedPath != null) {
t = tryLoadFromPath(libname, t, loadedSignal, forcedPath);
} else {
if (defaultPath != null)
t = tryLoadFromPath(libname, t, loadedSignal, defaultPath);
t = tryLoadFromSystemPath(libname, t, loadedSignal);
}
return t;
}
private static Throwable tryLoadFromPath(String libname, Throwable bestReason, RuntimeException loadedSignal, String path) {
String libFile = System.mapLibraryName(libname);
File lib = new File(new File(path), libFile);
if (!lib.isFile() || !lib.canRead())
return bestReason;
String logname = libname + " from " + lib;
logFine(Internal.class, "trying to load " + logname);
try {
System.load(lib.getAbsolutePath());
} catch (Throwable t) {
logFine(Internal.class, "cannot load " + logname + ": " + t);
return bestLoadFailureReason(bestReason, t);
}
return verifyLoading(bestReason, loadedSignal, logname);
}
private static Throwable tryLoadFromSystemPath(String libname, Throwable bestReason, RuntimeException loadedSignal) {
logFine(Internal.class, "trying to load " + libname);
try {
System.loadLibrary(libname);
} catch (Throwable t) {
logFine(Internal.class, "cannot load " + libname + ": " + t);
return bestLoadFailureReason(bestReason, t);
}
return verifyLoading(bestReason, loadedSignal, libname);
}
private static Throwable verifyLoading(Throwable bestReason, RuntimeException loadedSignal, String logname) {
logInfo(Internal.class, "loaded " + logname);
LinkageError linkError = checkLoaded();
if (linkError == null) {
// done -- exit cycle by throwing exception
throw loadedSignal;
}
logFine(Internal.class, "cannot use " + logname + ": " + linkError);
return bestLoadFailureReason(bestReason, linkError);
}
/**
* This method is used to decide which exception describes the real problem. If the file is simply not found
* (which we gather from the fact that message contains "java.library.path"), then it may or may not be the
* real reason. If there is another exception which has something else to say, it's given the priority.
*/
private static Throwable bestLoadFailureReason(Throwable t1, Throwable t2) {
if (t1 == null)
return t2;
if (t2 == null)
return t1;
String m1 = t1.getMessage();
if (m1 == null || !m1.contains("java.library.path"))
return t1;
String m2 = t2.getMessage();
if (m2 != null && m2.contains("java.library.path"))
return t1;
return t2;
}
private static LinkageError checkLoaded() {
try {
getLibraryVersionMessage();
return null;
} catch (LinkageError e) {
return e;
}
}
private static String getLibraryVersionMessage() {
String version = _SQLiteSwigged.sqlite3_libversion();
String wrapper = _SQLiteManual.wrapper_version();
return "loaded sqlite " + version + ", wrapper " + wrapper;
}
}