-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathNativeBinaryLoader.java
More file actions
501 lines (450 loc) · 22.7 KB
/
NativeBinaryLoader.java
File metadata and controls
501 lines (450 loc) · 22.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/*
* Copyright (c) 2023-2025, The Electrostatic-Sandbox Distributed Simulation Framework, jSnapLoader
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of 'Electrostatic-Sandbox' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* 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 OWNER 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.
*/
package electrostatic4j.snaploader;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.util.Arrays;
import java.util.List;
import java.util.jar.JarFile;
import java.util.logging.Level;
import electrostatic4j.snaploader.filesystem.FileExtractionListener;
import electrostatic4j.snaploader.filesystem.FileExtractor;
import electrostatic4j.snaploader.filesystem.FileLocalizingListener;
import electrostatic4j.snaploader.filesystem.FileLocator;
import electrostatic4j.snaploader.library.LibraryExtractor;
import electrostatic4j.snaploader.library.LibraryLocator;
import electrostatic4j.snaploader.platform.NativeDynamicLibrary;
import electrostatic4j.snaploader.platform.util.NativeVariant;
import electrostatic4j.snaploader.platform.util.PropertiesControllerNamespace;
import electrostatic4j.snaploader.platform.util.PropertiesController;
import electrostatic4j.snaploader.throwable.LoadingRetryExhaustionException;
import electrostatic4j.snaploader.throwable.UnSupportedSystemError;
import electrostatic4j.snaploader.util.CallingStackMetaData;
import electrostatic4j.snaploader.util.SnapLoaderLogger;
/**
* A cross-platform utility for extracting and loading native binaries based on
* the variant properties (OS + ARCH + VM).
*
* @author pavl_g.
*/
public class NativeBinaryLoader {
protected final LibraryInfo libraryInfo;
protected List<NativeDynamicLibrary> registeredLibraries;
protected NativeBinaryLoadingListener nativeBinaryLoadingListener;
protected SystemDetectionListener systemDetectionListener;
protected FileLocalizingListener libraryLocalizingListener;
protected FileExtractionListener libraryExtractionListener;
/**
* An Output stream concrete provider for library extraction.
*/
protected FileExtractor libraryExtractor;
/**
* The native dynamic library object representing the library to extract and load.
*/
protected NativeDynamicLibrary nativeDynamicLibrary;
/**
* Flag for retry loading with clean extract if UnSatisfiedLinkError is thrown.
*/
protected boolean retryWithCleanExtraction;
protected int maxNumberOfLoadingFailure = 2;
protected int numberOfLoadingFailure = 0;
private LoadingCriterion loadingCriterion; // cache the loading criterion for system controller use
/**
* Instantiates a native dynamic library loader to extract and load a system-specific native dynamic library.
*/
public NativeBinaryLoader(final LibraryInfo libraryInfo) {
this.libraryInfo = libraryInfo;
// initialize the system controller object
PropertiesControllerNamespace.systemDirectoryController.initialize();
}
/**
* Instantiates a native dynamic library loader to extract and load a system-specific native dynamic library.
*/
public NativeBinaryLoader(final List<NativeDynamicLibrary> registeredLibraries, final LibraryInfo libraryInfo) {
this(libraryInfo);
this.registeredLibraries = registeredLibraries;
}
public NativeBinaryLoader registerNativeLibraries(NativeDynamicLibrary[] nativeDynamicLibraries) {
this.registeredLibraries = Arrays.asList(nativeDynamicLibraries);
return this;
}
/**
* Initializes the platform-dependent native dynamic library.
*
* @return this instance for chained invocations
* @throws UnSupportedSystemError if the OS is not supported by jSnapLoader
*/
public NativeBinaryLoader initPlatformLibrary() throws UnSupportedSystemError {
final boolean[] isSystemFound = new boolean[]{false};
// search for the compatible library using the predefined predicate
// a predicate is a conditional statement composed of multiple propositions
// representing the complete system variant (OS + ARCH + VM).
registeredLibraries.forEach(nativeDynamicLibrary -> {
if (isSystemFound[0]) {
return;
}
// re-evaluate the library info part
if (libraryInfo != null) {
nativeDynamicLibrary.initWithLibraryInfo(libraryInfo);
}
if (nativeDynamicLibrary.getPlatformPredicate().evaluatePredicate()) {
this.nativeDynamicLibrary = nativeDynamicLibrary;
isSystemFound[0] = true;
}
});
// execute a system found listeners
if (isSystemFound[0]) {
if (systemDetectionListener != null) {
systemDetectionListener.onSystemFound(this, nativeDynamicLibrary);
}
} else {
if (systemDetectionListener != null) {
systemDetectionListener.onSystemNotFound(this);
}
throw new UnSupportedSystemError(NativeVariant.OS_NAME.getProperty(),
NativeVariant.OS_ARCH.getProperty());
}
return this;
}
/**
* Extracts and loads the system and the architecture-specific library from the output jar to a specified directory
* according to a loading criterion (incremental-load or clean-extract). The directory is determined by the selected
* {@link NativeDynamicLibrary} from the registered platform libraries.
*
* <p>
* Note: The default loading action for Android Systems is loading the libraries from the System directories (i.e., /lib/ABI inside the APK
* packages), while the default loading action for other desktop systems is determined by the user through this parameterized function.
* </p>
*
* <p>
* Fallback loading routines can be implemented as needed via {@link NativeBinaryLoadingListener#onLoadingFailure(NativeBinaryLoader, CallingStackMetaData)}
* and are left for the user applications.
* </p>
*
* @param criterion the initial loading criterion, either {@link LoadingCriterion#INCREMENTAL_LOADING}, {@link LoadingCriterion#CLEAN_EXTRACTION}
* or {@link LoadingCriterion#SYSTEM_LOAD} for loading native dlls from system directories.
* @return this instance for chained invocations
* @throws IOException if the library to extract is not present in the jar filesystem
*/
public NativeBinaryLoader loadLibrary(LoadingCriterion criterion) throws Exception {
if (nativeDynamicLibrary == null || libraryInfo == null) {
throw new IllegalArgumentException("Native library data structures cannot be null!");
}
// commands and loads the library from the system directories
if (NativeVariant.Os.isAndroid() || criterion == LoadingCriterion.SYSTEM_LOAD) {
loadSystemBinary(nativeDynamicLibrary);
loadingCriterion = LoadingCriterion.SYSTEM_LOAD;
return this;
}
if (criterion == LoadingCriterion.INCREMENTAL_LOADING && nativeDynamicLibrary.isExtracted()) {
loadBinary(nativeDynamicLibrary, criterion);
loadingCriterion = LoadingCriterion.INCREMENTAL_LOADING;
return this;
}
cleanExtractBinary(nativeDynamicLibrary);
loadingCriterion = LoadingCriterion.CLEAN_EXTRACTION;
return this;
}
/**
* Retrieves the native dynamic library object representing the library to extract and load.
*
* @return an object representing the platform-dependent native dynamic library
*/
public NativeDynamicLibrary getNativeDynamicLibrary() {
return nativeDynamicLibrary;
}
public PropertiesController getSystemDirectoryController() {
return PropertiesControllerNamespace.systemDirectoryController;
}
/**
* Enables the logging for this object, default value is false.
*
* @param loggingEnabled true to enable logging, false otherwise
*/
public NativeBinaryLoader setLoggingEnabled(boolean loggingEnabled) {
SnapLoaderLogger.setLoggingEnabled(loggingEnabled);
return this;
}
/**
* Tests the retry with clean extraction flag, default value is false.
*
* @return true if enabled, false otherwise
*/
public boolean isRetryWithCleanExtraction() {
return retryWithCleanExtraction;
}
/**
* Enables the retry with clean extraction after a load failure, default value is false.
*
* @param retryWithCleanExtraction true to enable the flag, false otherwise
*/
public NativeBinaryLoader setRetryWithCleanExtraction(boolean retryWithCleanExtraction) {
this.retryWithCleanExtraction = retryWithCleanExtraction;
return this;
}
public List<NativeDynamicLibrary> getRegisteredLibraries() {
return registeredLibraries;
}
public NativeBinaryLoadingListener getNativeBinaryLoadingListener() {
return nativeBinaryLoadingListener;
}
public NativeBinaryLoader setNativeBinaryLoadingListener(NativeBinaryLoadingListener nativeBinaryLoadingListener) {
this.nativeBinaryLoadingListener = nativeBinaryLoadingListener;
return this;
}
public SystemDetectionListener getSystemDetectionListener() {
return systemDetectionListener;
}
public NativeBinaryLoader setSystemDetectionListener(SystemDetectionListener systemDetectionListener) {
this.systemDetectionListener = systemDetectionListener;
return this;
}
public FileExtractionListener getLibraryExtractionListener() {
return libraryExtractionListener;
}
public NativeBinaryLoader setLibraryExtractionListener(FileExtractionListener libraryExtractionListener) {
this.libraryExtractionListener = libraryExtractionListener;
return this;
}
public FileLocalizingListener getLibraryLocalizingListener() {
return libraryLocalizingListener;
}
public NativeBinaryLoader setLibraryLocalizingListener(FileLocalizingListener libraryLocalizingListener) {
this.libraryLocalizingListener = libraryLocalizingListener;
return this;
}
public NativeBinaryLoader setMaxNumberOfLoadingFailure(int maxNumberOfLoadingFailure) {
this.maxNumberOfLoadingFailure = Math.abs(maxNumberOfLoadingFailure);
return this;
}
/**
* Loads a native binary from the customized system directories into the process virtual
* address space using the library basename in a platform-dependent way.
*/
protected void loadSystemBinary(NativeDynamicLibrary dynamicLibrary) {
SnapLoaderLogger.log(Level.INFO, getClass().getName(), "loadSystemBinary", "Loading library from the system: "
+ Arrays.toString(PropertiesControllerNamespace.systemDirectoryController.toList()));
try {
// use custom system directories for desktop ONLY!
if (NativeVariant.Os.isDesktop()) {
PropertiesControllerNamespace.systemDirectoryController.iterate(path -> {
final File lib = new File(FileSystems.getDefault()
.getPath(path.toString(),
dynamicLibrary.getLibraryFile()).toString());
if (lib.exists()) {
System.load(lib.getAbsolutePath());
}
return "";
});
} else {
System.loadLibrary(libraryInfo.getBaseName());
}
SnapLoaderLogger.log(Level.INFO, getClass().getName(), "loadSystemBinary", "Successfully loaded library from the system: "
+ libraryInfo.getBaseName());
if (nativeBinaryLoadingListener != null) {
nativeBinaryLoadingListener.onLoadingSuccess(this,
new CallingStackMetaData(Thread.currentThread().getStackTrace()[1], LoadingCriterion.SYSTEM_LOAD));
}
} catch (UnsatisfiedLinkError e) {
SnapLoaderLogger.log(Level.SEVERE, getClass().getName(), "loadSystemBinary", "Cannot load the dynamic library from the system: "
+ libraryInfo.getBaseName(), e);
// fire failure routine for fallback criteria
if (nativeBinaryLoadingListener != null) {
nativeBinaryLoadingListener.onLoadingFailure(this,
new CallingStackMetaData(Thread.currentThread().getStackTrace()[1], LoadingCriterion.SYSTEM_LOAD, e));
}
}
}
/**
* Loads a native binary into the virtual process address space from a specified
* native library data structure defining the directory path.
*
* @param library the platform-specific library to load
* @param loadingCriterion pass the loading criterion condition to the calling stack metadata structure
* @throws IOException in case the binary to be extracted is not found on the specified jar
* @throws LoadingRetryExhaustionException if the number of loading failure exceeds the specified
* number.
*/
protected void loadBinary(NativeDynamicLibrary library, LoadingCriterion loadingCriterion) throws Exception {
try {
System.load(library.getExtractedLibrary());
SnapLoaderLogger.log(Level.INFO, getClass().getName(), "loadBinary", "Successfully loaded library: "
+ library.getExtractedLibrary());
if (nativeBinaryLoadingListener != null) {
nativeBinaryLoadingListener.onLoadingSuccess(this,
new CallingStackMetaData(Thread.currentThread().getStackTrace()[1], loadingCriterion));
}
} catch (final UnsatisfiedLinkError error) {
SnapLoaderLogger.log(Level.SEVERE, getClass().getName(), "loadBinary", "Cannot load the dynamic library: "
+ library.getExtractedLibrary(), error);
if (nativeBinaryLoadingListener != null) {
nativeBinaryLoadingListener.onLoadingFailure(this,
new CallingStackMetaData(Thread.currentThread().getStackTrace()[1], loadingCriterion, error));
}
/* Retry with clean extract */
if (isRetryWithCleanExtraction()) {
if (nativeBinaryLoadingListener != null) {
nativeBinaryLoadingListener.onRetryCriterionExecution(this,
new CallingStackMetaData(Thread.currentThread().getStackTrace()[1], loadingCriterion));
}
// limit the number of retries to maxNumberOfLoadingFailure
if (numberOfLoadingFailure >= maxNumberOfLoadingFailure) {
numberOfLoadingFailure = 0; /* reset the number to zero trials */
throw new LoadingRetryExhaustionException("Library loading retries exceeded the maximum!");
}
++numberOfLoadingFailure;
// Jump call -> Possible Recursive Call
cleanExtractBinary(library);
}
}
}
/**
* Cleanly extracts and loads the native binary to the current [user.dir].
*
* @param library the platform-specific library to extract and load
* @throws IOException in case the binary to be extracted is not found on the specified jar, or an
* interrupted I/O operation has occurred
*/
protected void cleanExtractBinary(NativeDynamicLibrary library) throws Exception {
libraryExtractor = initializeLibraryExtractor(library);
SnapLoaderLogger.log(Level.INFO, getClass().getName(), "cleanExtractBinary",
"File extractor handler initialized!");
/* CLEAR RESOURCES AND RESET OBJECTS ON-EXTRACTION */
libraryExtractor.setExtractionListener(new FileExtractionListener() {
@Override
public void onExtractionCompleted(FileExtractor fileExtractor) {
try {
// free resources
// removes file locks on some OS
libraryExtractor.close();
libraryExtractor = null;
SnapLoaderLogger.log(Level.INFO, getClass().getName(), "cleanExtractBinary",
"Extracted successfully to " + library.getExtractedLibrary());
// load the native binary
loadBinary(library, LoadingCriterion.CLEAN_EXTRACTION);
} catch (Exception e) {
SnapLoaderLogger.log(Level.SEVERE, getClass().getName(), "cleanExtractBinary",
"Error while loading the binary!", e);
}
// bind the extraction lifecycle to the user application
if (libraryExtractionListener != null) {
libraryExtractionListener.onExtractionCompleted(fileExtractor);
}
}
@Override
public void onExtractionFailure(FileExtractor fileExtractor, Throwable throwable) {
SnapLoaderLogger.log(Level.SEVERE, getClass().getName(),
"cleanExtractBinary", "Extraction has failed!", throwable);
// bind the extraction lifecycle to the user application
if (libraryExtractionListener != null) {
libraryExtractionListener.onExtractionFailure(fileExtractor, throwable);
}
}
@Override
public void onExtractionFinalization(FileExtractor fileExtractor, FileLocator fileLocator) {
try {
if (fileExtractor != null &&
fileExtractor.getFileOutputStream() != null) {
fileExtractor.close();
}
} catch (Exception e) {
SnapLoaderLogger.log(Level.SEVERE, getClass().getName(),
"cleanExtractBinary", "Error while closing the resources!", e);
}
// bind the extraction lifecycle to the user application
if (libraryExtractionListener != null) {
libraryExtractionListener.onExtractionFinalization(fileExtractor, fileLocator);
}
}
});
libraryExtractor.extract();
}
/**
* Initializes a filesystem extractor object
* if the filesystem extractor object associated with this loader isn't defined.
*
* @param library the native dynamic library to load
* @return a new FileExtractor object that represents an output stream provider
* @throws IOException if the jar filesystem to be located is not found, or if the extraction destination is not found
*/
protected FileExtractor initializeLibraryExtractor(NativeDynamicLibrary library) throws Exception {
FileExtractor extractor;
if (library.getJarPath() != null) {
// use an extractor with the external jar routine
extractor = new LibraryExtractor(new JarFile(library.getJarPath()), library.getCompressedLibrary(), library.getExtractedLibrary());
} else {
// use an extractor with the classpath routine
extractor = new LibraryExtractor(library.getCompressedLibrary(), library.getExtractedLibrary());
}
extractor.initialize(0);
final LibraryLocator fileLocator = preInitLibraryLocator(extractor);
fileLocator.initialize(0);
return extractor;
}
protected LibraryLocator preInitLibraryLocator(FileExtractor extractor) {
extractor.getFileLocator().setFileLocalizingListener(new FileLocalizingListener() {
@Override
public void onFileLocalizationSuccess(FileLocator locator) {
SnapLoaderLogger.log(Level.INFO, getClass().getName(), "preInitLibraryLocator",
"Locating native libraries has succeeded!");
// bind the library locator lifecycle to the user application
if (libraryLocalizingListener != null) {
libraryLocalizingListener.onFileLocalizationSuccess(locator);
}
}
@Override
public void onFileLocalizationFailure(FileLocator locator, Throwable throwable) {
SnapLoaderLogger.log(Level.SEVERE, getClass().getName(), "preInitLibraryLocator",
"Locating native libraries has failed!", throwable);
try {
extractor.close();
} catch (Exception e) {
SnapLoaderLogger.log(Level.SEVERE, getClass().getName(),
"initializeLibraryExtractor", "File locator closure failed!", e);
}
// bind the library locator lifecycle to the user application
if (libraryLocalizingListener != null) {
libraryLocalizingListener.onFileLocalizationFailure(locator, throwable);
}
// make use of the loader listeners
if (nativeBinaryLoadingListener != null) {
// a file locator and extractor loader is always a CLEAN_EXTRACTION regarding
// the loading criterion
nativeBinaryLoadingListener.onLoadingFailure(NativeBinaryLoader.this,
new CallingStackMetaData(Thread.currentThread().getStackTrace()[1], LoadingCriterion.CLEAN_EXTRACTION, throwable));
}
}
});
return (LibraryLocator) extractor.getFileLocator();
}
}