/
Native.java
1902 lines (1732 loc) · 77.9 KB
/
Native.java
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2007-2013 Timothy Wall, All Rights Reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* <p/>
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package com.sun.jna;
import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Window;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import com.sun.jna.Callback.UncaughtExceptionHandler;
import com.sun.jna.Structure.FFIType;
/** Provides generation of invocation plumbing for a defined native
* library interface. Also provides various utilities for native operations.
* <p>
* {@link #getTypeMapper} and {@link #getStructureAlignment} are provided
* to avoid having to explicitly pass these parameters to {@link Structure}s,
* which would require every {@link Structure} which requires custom mapping
* or alignment to define a constructor and pass parameters to the superclass.
* To avoid lots of boilerplate, the base {@link Structure} constructor
* figures out these properties based on its enclosing interface.<p>
* <a name=library_loading></a>
* <h2>Library Loading</h2>
* When JNA classes are loaded, the native shared library (jnidispatch) is
* loaded as well. An attempt is made to load it from the any paths defined
* in <code>jna.boot.library.path</code> (if defined), then the system library
* path using {@link System#loadLibrary}, unless <code>jna.nosys=true</code>.
* If not found, the appropriate library will be extracted from the class path
* (into a temporary directory if found within a jar file) and loaded from
* there, unless <code>jna.noclasspath=true</code>. If your system has
* additional security constraints regarding execution or load of files
* (SELinux, for example), you should probably install the native library in
* an accessible location and configure your system accordingly, rather than
* relying on JNA to extract the library from its own jar file.<p/>
* To avoid the automatic unpacking (in situations where you want to force a
* failure if the JNA native library is not properly installed on the system),
* set the system property <code>jna.nounpack=true</code>.
* <p/>
* NOTE: all native functions are provided within this class to ensure that
* all other JNA-provided classes and objects are GC'd and/or
* finalized/disposed before this class is disposed and/or removed from
* memory (most notably Memory and any other class which by default frees its
* resources in a finalizer).<p/>
* <a name=native_library_loading</a>
* <h2>Native Library Loading</h2>
* Native libraries loaded via {@link #loadLibrary(Class)} may be found in
* <a href="NativeLibrary.html#library_search_paths">several locations</a>.
* @see Library
* @author Todd Fast, todd.fast@sun.com
* @author twall@users.sf.net
*/
public final class Native implements Version {
public static final String DEFAULT_ENCODING = "utf8";
// Used by tests, do not remove
private static String nativeLibraryPath = null;
private static Map options = new WeakHashMap();
private static Map libraries = new WeakHashMap();
private static final UncaughtExceptionHandler DEFAULT_HANDLER =
new UncaughtExceptionHandler() {
public void uncaughtException(Callback c, Throwable e) {
System.err.println("JNA: Callback " + c + " threw the following exception:");
e.printStackTrace();
}
};
private static UncaughtExceptionHandler callbackExceptionHandler = DEFAULT_HANDLER;
/** The size of a native pointer (<code>void*</code>) on the current
* platform, in bytes.
*/
public static final int POINTER_SIZE;
/** Size of a native <code>long</code> type, in bytes. */
public static final int LONG_SIZE;
/** Size of a native <code>wchar_t</code> type, in bytes. */
public static final int WCHAR_SIZE;
/** Size of a native <code>size_t</code> type, in bytes. */
public static final int SIZE_T_SIZE;
private static final int TYPE_VOIDP = 0;
private static final int TYPE_LONG = 1;
private static final int TYPE_WCHAR_T = 2;
private static final int TYPE_SIZE_T = 3;
static final int MAX_PADDING;
static {
loadNativeDispatchLibrary();
POINTER_SIZE = sizeof(TYPE_VOIDP);
LONG_SIZE = sizeof(TYPE_LONG);
WCHAR_SIZE = sizeof(TYPE_WCHAR_T);
SIZE_T_SIZE = sizeof(TYPE_SIZE_T);
// Perform initialization of other JNA classes until *after*
// initializing the above final fields
initIDs();
if (Boolean.getBoolean("jna.protected")) {
setProtected(true);
}
String version = getNativeVersion();
if (!VERSION_NATIVE.equals(version)) {
String LS = System.getProperty("line.separator");
throw new Error(LS + LS
+ "There is an incompatible JNA native library installed on this system" + LS
+ (nativeLibraryPath != null
? "(at " + nativeLibraryPath + ")" : System.getProperty("java.library.path"))
+ "." + LS
+ "To resolve this issue you may do one of the following:" + LS
+ " - remove or uninstall the offending library" + LS
+ " - set the system property jna.nosys=true" + LS
+ " - set jna.boot.library.path to include the path to the version of the " + LS
+ " jnidispatch library included with the JNA jar file you are using" + LS);
}
MAX_PADDING = Platform.isSPARC() || Platform.isWindows() || Platform.isARM()
|| Platform.isAIX() || Platform.isAndroid()
|| Platform.isPPC()
? 8 : LONG_SIZE;
}
/** Force a dispose when this class is GC'd. */
private static final Object finalizer = new Object() {
protected void finalize() {
dispose();
}
};
/** Properly dispose of JNA functionality. */
private static void dispose() {
NativeLibrary.disposeAll();
nativeLibraryPath = null;
}
/** Remove any automatically unpacked native library.
This will fail on windows, which disallows removal of any file that is
still in use, so an alternative is required in that case. Mark
the file that could not be deleted, and attempt to delete any
temporaries on next startup.
Do NOT force the class loader to unload the native library, since
that introduces issues with cleaning up any extant JNA bits
(e.g. Memory) which may still need use of the library before shutdown.
*/
static boolean deleteLibrary(File lib) {
if (lib.delete()) {
return true;
}
// Couldn't delete it, mark for later deletion
markTemporaryFile(lib);
return false;
}
private Native() { }
private static native void initIDs();
/** Set whether native memory accesses are protected from invalid
* accesses. This should only be set true when testing or debugging,
* and should not be considered reliable or robust for applications
* where JNA native calls are occurring on multiple threads.
* Protected mode will be automatically set if the
* system property <code>jna.protected</code> has a value of "true"
* when the JNA library is first loaded.<p>
* If not supported by the underlying platform, this setting will
* have no effect.<p>
* NOTE: On platforms which support signals (non-Windows), JNA uses
* signals to trap errors. This may interfere with the JVM's own use of
* signals. When protected mode is enabled, you should make use of the
* jsig library, if available (see <a href="http://download.oracle.com/javase/6/docs/technotes/guides/vm/signal-chaining.html">Signal Chaining</a>).
* In short, set the environment variable <code>LD_PRELOAD</code> to the
* path to <code>libjsig.so</code> in your JRE lib directory
* (usually ${java.home}/lib/${os.arch}/libjsig.so) before launching your
* Java application.
*/
public static synchronized native void setProtected(boolean enable);
/** Returns whether protection is enabled. Check the result of this method
* after calling {@link #setProtected setProtected(true)} to determine
* if this platform supports protecting memory accesses.
*/
public static synchronized native boolean isProtected();
/** This method is obsolete. The last error value is always preserved.
* <p/>
* NOTE: The preferred method of obtaining the last error result is
* to declare your mapped method to throw {@link LastErrorException}.
*
* @deprecated Last error is always preserved
*/
public static void setPreserveLastError(boolean enable) { }
/** Indicates whether the system last error result is preserved
* after every invocation. Always returns <code>true</code><p>
* NOTE: The preferred method of obtaining the last error result is
* to declare your mapped method to throw {@link LastErrorException}.
*
* @deprecated Last error is always preserved
*/
public static boolean getPreserveLastError() { return true; }
/** Utility method to get the native window ID for a Java {@link Window}
* as a <code>long</code> value.
* This method is primarily for X11-based systems, which use an opaque
* <code>XID</code> (usually <code>long int</code>) to identify windows.
* @throws HeadlessException if the current VM is running headless
*/
public static long getWindowID(Window w) throws HeadlessException {
return AWT.getWindowID(w);
}
/** Utility method to get the native window ID for a heavyweight Java
* {@link Component} as a <code>long</code> value.
* This method is primarily for X11-based systems, which use an opaque
* <code>XID</code> (usually <code>long int</code>) to identify windows.
* @throws HeadlessException if the current VM is running headless
*/
public static long getComponentID(Component c) throws HeadlessException {
return AWT.getComponentID(c);
}
/** Utility method to get the native window pointer for a Java
* {@link Window} as a {@link Pointer} value. This method is primarily for
* w32, which uses the <code>HANDLE</code> type (actually
* <code>void *</code>) to identify windows.
* @throws HeadlessException if the current VM is running headless
*/
public static Pointer getWindowPointer(Window w) throws HeadlessException {
return new Pointer(AWT.getWindowID(w));
}
/** Utility method to get the native window pointer for a heavyweight Java
* {@link Component} as a {@link Pointer} value. This method is primarily
* for w32, which uses the <code>HWND</code> type (actually
* <code>void *</code>) to identify windows.
* @throws HeadlessException if the current VM is running headless
*/
public static Pointer getComponentPointer(Component c) throws HeadlessException {
return new Pointer(AWT.getComponentID(c));
}
static native long getWindowHandle0(Component c);
/** Convert a direct {@link Buffer} into a {@link Pointer}.
* @throws IllegalArgumentException if the buffer is not direct.
*/
public static Pointer getDirectBufferPointer(Buffer b) {
long peer = _getDirectBufferPointer(b);
return peer == 0 ? null : new Pointer(peer);
}
private static native long _getDirectBufferPointer(Buffer b);
/** Obtain a Java String from the given native byte array. If there is
* no NUL terminator, the String will comprise the entire array. The
* encoding is obtained from {@link #getDefaultStringEncoding()}.
*/
public static String toString(byte[] buf) {
return toString(buf, getDefaultStringEncoding());
}
/** Obtain a Java String from the given native byte array, using the given
* encoding. If there is no NUL terminator, the String will comprise the
* entire array. If the <code>encoding</code> parameter is null,
* the platform default encoding will be used.
*/
public static String toString(byte[] buf, String encoding) {
String s = null;
if (encoding != null) {
try {
s = new String(buf, encoding);
}
catch(UnsupportedEncodingException e) {
System.err.println("JNA Warning: Encoding '"
+ encoding + "' is unsupported");
}
}
if (s == null) {
System.err.println("JNA Warning: Decoding with fallback " + System.getProperty("file.encoding"));
s = new String(buf);
}
int term = s.indexOf(0);
if (term != -1) {
s = s.substring(0, term);
}
return s;
}
/** Obtain a Java String from the given native wchar_t array. If there is
* no NUL terminator, the String will comprise the entire array.
*/
public static String toString(char[] buf) {
String s = new String(buf);
int term = s.indexOf(0);
if (term != -1) {
s = s.substring(0, term);
}
return s;
}
/** Map a library interface to the current process, providing
* the explicit interface class.
* Native libraries loaded via this method may be found in
* <a href="NativeLibrary.html#library_search_paths">several locations</a>.
* @param interfaceClass
* @return an instance of the requested interface, mapped to the current
* process.
* @throws UnsatisfiedLinkError if the library cannot be found or
* dependent libraries are missing.
*/
public static Object loadLibrary(Class interfaceClass) {
return loadLibrary(null, interfaceClass);
}
/** Map a library interface to the current process, providing
* the explicit interface class. Any options provided for the library are
* cached and associated with the library and any of its defined
* structures and/or functions.
* Native libraries loaded via this method may be found in
* <a href="NativeLibrary.html#library_search_paths">several locations</a>.
* @param interfaceClass
* @param options Map of library options
* @return an instance of the requested interface, mapped to the current
* process.
* @throws UnsatisfiedLinkError if the library cannot be found or
* dependent libraries are missing.
*/
public static Object loadLibrary(Class interfaceClass, Map options) {
return loadLibrary(null, interfaceClass, options);
}
/** Map a library interface to the given shared library, providing
* the explicit interface class.
* If <code>name</code> is null, attempts to map onto the current process.
* Native libraries loaded via this method may be found in
* <a href="NativeLibrary.html#library_search_paths">several locations</a>.
* @param name
* @param interfaceClass
* @return an instance of the requested interface, mapped to the indicated
* native library.
* @throws UnsatisfiedLinkError if the library cannot be found or
* dependent libraries are missing.
*/
public static Object loadLibrary(String name, Class interfaceClass) {
return loadLibrary(name, interfaceClass, Collections.EMPTY_MAP);
}
/** Load a library interface from the given shared library, providing
* the explicit interface class and a map of options for the library.
* If no library options are detected the map is interpreted as a map
* of Java method names to native function names.<p>
* If <code>name</code> is null, attempts to map onto the current process.
* Native libraries loaded via this method may be found in
* <a href="NativeLibrary.html#library_search_paths">several locations</a>.
* @param name
* @param interfaceClass
* @param options Map of library options
* @return an instance of the requested interface, mapped to the indicated
* native library.
* @throws UnsatisfiedLinkError if the library cannot be found or
* dependent libraries are missing.
*/
public static Object loadLibrary(String name,
Class interfaceClass,
Map options) {
Library.Handler handler =
new Library.Handler(name, interfaceClass, options);
ClassLoader loader = interfaceClass.getClassLoader();
Library proxy = (Library)
Proxy.newProxyInstance(loader, new Class[] {interfaceClass},
handler);
cacheOptions(interfaceClass, options, proxy);
return proxy;
}
/** Attempts to force initialization of an instance of the library interface
* by loading a public static field of the requisite type.
* Returns whether an instance variable was instantiated.
* Expects that lock on libraries is already held
*/
private static void loadLibraryInstance(Class cls) {
synchronized(libraries) {
if (cls != null && !libraries.containsKey(cls)) {
try {
Field[] fields = cls.getFields();
for (int i=0;i < fields.length;i++) {
Field field = fields[i];
if (field.getType() == cls
&& Modifier.isStatic(field.getModifiers())) {
// Ensure the field gets initialized by reading it
libraries.put(cls, new WeakReference(field.get(null)));
break;
}
}
}
catch (Exception e) {
throw new IllegalArgumentException("Could not access instance of "
+ cls + " (" + e + ")");
}
}
}
}
/** Find the library interface corresponding to the given class. Checks
* all ancestor classes and interfaces for a declaring class which
* implements {@link Library}.
*/
static Class findEnclosingLibraryClass(Class cls) {
if (cls == null) {
return null;
}
// Check for direct-mapped libraries, which won't necessarily
// implement com.sun.jna.Library.
synchronized(libraries) {
if (options.containsKey(cls)) {
return cls;
}
}
if (Library.class.isAssignableFrom(cls)) {
return cls;
}
if (Callback.class.isAssignableFrom(cls)) {
cls = CallbackReference.findCallbackClass(cls);
}
Class declaring = cls.getDeclaringClass();
Class fromDeclaring = findEnclosingLibraryClass(declaring);
if (fromDeclaring != null) {
return fromDeclaring;
}
return findEnclosingLibraryClass(cls.getSuperclass());
}
/** Return the preferred native library configuration options for the given
* class. First attempts to load any field of the interface type within
* the interface mapping, then checks the cache for any specified library
* options. If none found, a set of library options will be generated
* from the fields (by order of precedence) <code>OPTIONS</code> (a {@link
* Map}), <code>TYPE_MAPPER</code> (a {@link TypeMapper}),
* <code>STRUCTURE_ALIGNMENT</code> (an {@link Integer}), and
* <code>STRING_ENCODING</code> (a {@link String}).
* @see Library
*/
public static Map getLibraryOptions(Class type) {
synchronized(libraries) {
if (options.containsKey(type)) {
return (Map)options.get(type);
}
}
Class mappingClass = findEnclosingLibraryClass(type);
if (mappingClass != null) {
loadLibraryInstance(mappingClass);
}
else {
mappingClass = type;
}
synchronized(libraries) {
if (options.containsKey(mappingClass)) {
Map libraryOptions = (Map)options.get(mappingClass);
options.put(type, libraryOptions);
return libraryOptions;
}
Map libraryOptions = null;
try {
Field field = mappingClass.getField("OPTIONS");
field.setAccessible(true);
libraryOptions = (Map)field.get(null);
}
catch (NoSuchFieldException e) {
libraryOptions = Collections.EMPTY_MAP;
}
catch (Exception e) {
throw new IllegalArgumentException("OPTIONS must be a public field of type java.util.Map ("
+ e + "): " + mappingClass);
}
// Make a clone of the original options
libraryOptions = new HashMap(libraryOptions);
if (!libraryOptions.containsKey(Library.OPTION_TYPE_MAPPER)) {
libraryOptions.put(Library.OPTION_TYPE_MAPPER, lookupField(mappingClass, "TYPE_MAPPER", TypeMapper.class));
}
if (!libraryOptions.containsKey(Library.OPTION_STRUCTURE_ALIGNMENT)) {
libraryOptions.put(Library.OPTION_STRUCTURE_ALIGNMENT, lookupField(mappingClass, "STRUCTURE_ALIGNMENT", Integer.class));
}
if (!libraryOptions.containsKey(Library.OPTION_STRING_ENCODING)) {
libraryOptions.put(Library.OPTION_STRING_ENCODING, lookupField(mappingClass, "STRING_ENCODING", String.class));
}
options.put(mappingClass, libraryOptions);
// Store the original lookup class, if different from the mapping class
if (type != mappingClass) {
options.put(type, libraryOptions);
}
return libraryOptions;
}
}
private static Object lookupField(Class mappingClass, String fieldName, Class resultClass) {
try {
Field field = mappingClass.getField(fieldName);
field.setAccessible(true);
return field.get(null);
}
catch (NoSuchFieldException e) {
return null;
}
catch (Exception e) {
throw new IllegalArgumentException(fieldName + " must be a public field of type "
+ resultClass.getName() + " ("
+ e + "): " + mappingClass);
}
}
/** Return the preferred {@link TypeMapper} for the given native interface.
* See {@link com.sun.jna.Library#OPTION_TYPE_MAPPER}.
*/
public static TypeMapper getTypeMapper(Class cls) {
return (TypeMapper)getLibraryOptions(cls).get(Library.OPTION_TYPE_MAPPER);
}
/** Return the preferred Strring encoding for the given native interface.
* If there is no setting, defaults to the {@link
* #getDefaultStringEncoding()}.
* See {@link com.sun.jna.Library#OPTION_STRING_ENCODING}.
*/
public static String getStringEncoding(Class cls) {
String encoding = (String)getLibraryOptions(cls).get(Library.OPTION_STRING_ENCODING);
return encoding != null ? encoding : getDefaultStringEncoding();
}
/** Return the default string encoding. Returns the value of the system
* property <code>jna.encoding</code> or {@link Native#DEFAULT_ENCODING}.
*/
public static String getDefaultStringEncoding() {
return System.getProperty("jna.encoding", DEFAULT_ENCODING);
}
/** Return the preferred structure alignment for the given native interface.
* See {@link com.sun.jna.Library#OPTION_STRUCTURE_ALIGNMENT}.
*/
public static int getStructureAlignment(Class cls) {
Integer alignment = (Integer)getLibraryOptions(cls).get(Library.OPTION_STRUCTURE_ALIGNMENT);
return alignment == null ? Structure.ALIGN_DEFAULT : alignment.intValue();
}
/** Return a byte array corresponding to the given String. The encoding
* used is obtained from {@link #getDefaultStringEncoding()}.
*/
static byte[] getBytes(String s) {
return getBytes(s, getDefaultStringEncoding());
}
/** Return a byte array corresponding to the given String, using the given
encoding. If the encoding is not found default to the platform native
encoding.
*/
static byte[] getBytes(String s, String encoding) {
if (encoding != null) {
try {
return s.getBytes(encoding);
}
catch(UnsupportedEncodingException e) {
System.err.println("JNA Warning: Encoding '"
+ encoding + "' is unsupported");
}
}
System.err.println("JNA Warning: Encoding with fallback "
+ System.getProperty("file.encoding"));
return s.getBytes();
}
/** Obtain a NUL-terminated byte buffer equivalent to the given String,
using the encoding returned by {@link #getDefaultStringEncoding()}.
*/
public static byte[] toByteArray(String s) {
return toByteArray(s, getDefaultStringEncoding());
}
/** Obtain a NUL-terminated byte buffer equivalent to the given String,
using the given encoding.
*/
public static byte[] toByteArray(String s, String encoding) {
byte[] bytes = getBytes(s, encoding);
byte[] buf = new byte[bytes.length+1];
System.arraycopy(bytes, 0, buf, 0, bytes.length);
return buf;
}
/** Obtain a NUL-terminated wide character buffer equivalent to the given
String.
*/
public static char[] toCharArray(String s) {
char[] chars = s.toCharArray();
char[] buf = new char[chars.length+1];
System.arraycopy(chars, 0, buf, 0, chars.length);
return buf;
}
/**
* Loads the JNA stub library.
* First tries jna.boot.library.path, then the system path, then from the
* jar file.
*/
private static void loadNativeDispatchLibrary() {
if (!Boolean.getBoolean("jna.nounpack")) {
try {
removeTemporaryFiles();
}
catch(IOException e) {
System.err.println("JNA Warning: IOException removing temporary files: " + e.getMessage());
}
}
String libName = System.getProperty("jna.boot.library.name", "jnidispatch");
String bootPath = System.getProperty("jna.boot.library.path");
if (bootPath != null) {
// String.split not available in 1.4
StringTokenizer dirs = new StringTokenizer(bootPath, File.pathSeparator);
while (dirs.hasMoreTokens()) {
String dir = dirs.nextToken();
File file = new File(new File(dir), System.mapLibraryName(libName).replace(".dylib", ".jnilib"));
String path = file.getAbsolutePath();
if (file.exists()) {
try {
System.load(path);
nativeLibraryPath = path;
return;
} catch (UnsatisfiedLinkError ex) {
// Not a problem if already loaded in anoteher class loader
// Unfortunately we can't distinguish the difference...
//System.out.println("File found at " + file + " but not loadable: " + ex.getMessage());
}
}
if (Platform.isMac()) {
String orig, ext;
if (path.endsWith("dylib")) {
orig = "dylib";
ext = "jnilib";
} else {
orig = "jnilib";
ext = "dylib";
}
path = path.substring(0, path.lastIndexOf(orig)) + ext;
if (new File(path).exists()) {
try {
System.load(path);
nativeLibraryPath = path;
return;
} catch (UnsatisfiedLinkError ex) {
System.err.println("File found at " + path + " but not loadable: " + ex.getMessage());
}
}
}
}
}
if (!Boolean.getBoolean("jna.nosys")) {
try {
System.loadLibrary(libName);
return;
}
catch(UnsatisfiedLinkError e) {
}
}
if (!Boolean.getBoolean("jna.noclasspath")) {
loadNativeDispatchLibraryFromClasspath();
}
else {
throw new UnsatisfiedLinkError("Unable to locate JNA native support library");
}
}
static final String JNA_TMPLIB_PREFIX = "jna";
/**
* Attempts to load the native library resource from the filesystem,
* extracting the JNA stub library from jna.jar if not already available.
*/
private static void loadNativeDispatchLibraryFromClasspath() {
try {
String libName = "/com/sun/jna/" + Platform.RESOURCE_PREFIX + "/" + System.mapLibraryName("jnidispatch").replace(".dylib", ".jnilib");
File lib = extractFromResourcePath(libName, Native.class.getClassLoader());
if (lib == null) {
if (lib == null) {
throw new UnsatisfiedLinkError("Could not find JNA native support");
}
}
System.load(lib.getAbsolutePath());
nativeLibraryPath = lib.getAbsolutePath();
// Attempt to delete immediately once jnidispatch is successfully
// loaded. This avoids the complexity of trying to do so on "exit",
// which point can vary under different circumstances (native
// compilation, dynamically loaded modules, normal application, etc).
if (isUnpacked(lib)) {
deleteLibrary(lib);
}
}
catch(IOException e) {
throw new UnsatisfiedLinkError(e.getMessage());
}
}
/** Identify temporary files unpacked from classpath jar files. */
static boolean isUnpacked(File file) {
return file.getName().startsWith(JNA_TMPLIB_PREFIX);
}
/** Attempt to extract a native library from the current resource path,
* using the current thread context class loader.
* @param name Base name of native library to extract. May also be an
* absolute resource path (i.e. starts with "/"), in which case the
* no transformations of the library name are performed. If only the base
* name is given, the resource path is attempted both with and without
* {@link Platform#RESOURCE_PREFIX}, after mapping the library name via
* {@link NativeLibrary#mapSharedLibraryName(String)}.
* @return File indicating extracted resource on disk
* @throws IOException if resource not found
*/
public static File extractFromResourcePath(String name) throws IOException {
return extractFromResourcePath(name, null);
}
/** Attempt to extract a native library from the resource path using the
* given class loader.
* @param name Base name of native library to extract. May also be an
* absolute resource path (i.e. starts with "/"), in which case the
* no transformations of the library name are performed. If only the base
* name is given, the resource path is attempted both with and without
* {@link Platform#RESOURCE_PREFIX}, after mapping the library name via
* {@link NativeLibrary#mapSharedLibraryName(String)}.
* @param loader Class loader to use to load resources
* @return File indicating extracted resource on disk
* @throws IOException if resource not found
*/
public static File extractFromResourcePath(String name, ClassLoader loader) throws IOException {
if (loader == null) {
loader = Thread.currentThread().getContextClassLoader();
// Context class loader is not guaranteed to be set
if (loader == null) {
loader = Native.class.getClassLoader();
}
}
String libname = name.startsWith("/") ? name : NativeLibrary.mapSharedLibraryName(name);
String resourcePath = name.startsWith("/") ? name : Platform.RESOURCE_PREFIX + "/" + libname;
if (resourcePath.startsWith("/")) {
resourcePath = resourcePath.substring(1);
}
URL url = loader.getResource(resourcePath);
if (url == null && resourcePath.startsWith(Platform.RESOURCE_PREFIX)) {
// If not found with the standard resource prefix, try without it
url = loader.getResource(libname);
}
if (url == null) {
String path = System.getProperty("java.class.path");
if (loader instanceof URLClassLoader) {
path = Arrays.asList(((URLClassLoader)loader).getURLs()).toString();
}
throw new IOException("Native library (" + resourcePath + ") not found in resource path (" + path + ")");
}
File lib = null;
if (url.getProtocol().toLowerCase().equals("file")) {
try {
lib = new File(new URI(url.toString()));
}
catch(URISyntaxException e) {
lib = new File(url.getPath());
}
if (!lib.exists()) {
throw new IOException("File URL " + url + " could not be properly decoded");
}
}
else if (!Boolean.getBoolean("jna.nounpack")) {
InputStream is = loader.getResourceAsStream(resourcePath);
if (is == null) {
throw new IOException("Can't obtain InputStream for " + resourcePath);
}
FileOutputStream fos = null;
try {
// Suffix is required on windows, or library fails to load
// Let Java pick the suffix, except on windows, to avoid
// problems with Web Start.
File dir = getTempDir();
lib = File.createTempFile(JNA_TMPLIB_PREFIX, Platform.isWindows()?".dll":null, dir);
lib.deleteOnExit();
fos = new FileOutputStream(lib);
int count;
byte[] buf = new byte[1024];
while ((count = is.read(buf, 0, buf.length)) > 0) {
fos.write(buf, 0, count);
}
}
catch(IOException e) {
throw new IOException("Failed to create temporary file for " + name + " library: " + e.getMessage());
}
finally {
try { is.close(); } catch(IOException e) { }
if (fos != null) {
try { fos.close(); } catch(IOException e) { }
}
}
}
return lib;
}
/**
* Initialize field and method IDs for native methods of this class.
* Returns the size of a native pointer.
**/
private static native int sizeof(int type);
private static native String getNativeVersion();
private static native String getAPIChecksum();
/** Retrieve the last error set by the OS. This corresponds to
* <code>GetLastError()</code> on Windows, and <code>errno</code> on
* most other platforms. The value is preserved per-thread, but whether
* the original value is per-thread depends on the underlying OS. The
* result is undefined if {@link #getPreserveLastError} is
* <code>false</code>.<p>
* The preferred method of obtaining the last error result is
* to declare your mapped method to throw {@link LastErrorException}
* instead.
*/
public static native int getLastError();
/** Set the OS last error code. The value will be saved on a per-thread
* basis.
*/
public static native void setLastError(int code);
/**
* Returns a synchronized (thread-safe) library backed by the specified
* library. This wrapping will prevent simultaneous invocations of any
* functions mapped to a given {@link NativeLibrary}. Note that the
* native library may still be sensitive to being called from different
* threads.
* <p>
* @param library the library to be "wrapped" in a synchronized library.
* @return a synchronized view of the specified library.
*/
public static Library synchronizedLibrary(final Library library) {
Class cls = library.getClass();
if (!Proxy.isProxyClass(cls)) {
throw new IllegalArgumentException("Library must be a proxy class");
}
InvocationHandler ih = Proxy.getInvocationHandler(library);
if (!(ih instanceof Library.Handler)) {
throw new IllegalArgumentException("Unrecognized proxy handler: " + ih);
}
final Library.Handler handler = (Library.Handler)ih;
InvocationHandler newHandler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
synchronized(handler.getNativeLibrary()) {
return handler.invoke(library, method, args);
}
}
};
return (Library)Proxy.newProxyInstance(cls.getClassLoader(),
cls.getInterfaces(),
newHandler);
}
/** If running web start, determine the location of a given native
* library. This value may be used to properly set
* <code>jna.library.path</code> so that JNA can load libraries identified
* by the <nativelib> tag in the JNLP configuration file. Returns
* <code>null</code> if the Web Start native library cache location can not
* be determined. Note that the path returned may be different for any
* given library name.
* <p>
* Use <code>System.getProperty("javawebstart.version")</code> to detect
* whether your code is running under Web Start.
* @throws UnsatisfiedLinkError if the library can't be found by the
* Web Start class loader, which usually means it wasn't included as
* a <code><nativelib></code> resource in the JNLP file.
* @return null if unable to query the web start loader.
*/
public static String getWebStartLibraryPath(final String libName) {
if (System.getProperty("javawebstart.version") == null)
return null;
try {
final ClassLoader cl = Native.class.getClassLoader();
Method m = (Method)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
Method m = ClassLoader.class.getDeclaredMethod("findLibrary", new Class[] { String.class });
m.setAccessible(true);
return m;
}
catch(Exception e) {
return null;
}
}
});
String libpath = (String)m.invoke(cl, new Object[] { libName });
if (libpath != null) {
return new File(libpath).getParent();
}
return null;
}
catch (Exception e) {
return null;
}
}
/** Perform cleanup of automatically unpacked native shared library.
*/
static void markTemporaryFile(File file) {
// If we can't force an unload/delete, flag the file for later
// deletion
try {
File marker = new File(file.getParentFile(), file.getName() + ".x");
marker.createNewFile();
}
catch(IOException e) { e.printStackTrace(); }
}
/** Obtain a directory suitable for writing JNA-specific temporary files.
Override with <code>jna.tmpdir</code>
*/
static File getTempDir() throws IOException {
File jnatmp;
String prop = System.getProperty("jna.tmpdir");
if (prop != null) {
jnatmp = new File(prop);
jnatmp.mkdirs();
}
else {
File tmp = new File(System.getProperty("java.io.tmpdir"));
// Loading DLLs via System.load() under a directory with a unicode
// name will fail on windows, so use a hash code of the user's
// name in case the user's name contains non-ASCII characters
jnatmp = new File(tmp, "jna-" + System.getProperty("user.name").hashCode());
jnatmp.mkdirs();
if (!jnatmp.exists() || !jnatmp.canWrite()) {
jnatmp = tmp;
}
}
if (!jnatmp.exists()) {
throw new IOException("JNA temporary directory '" + jnatmp + "' does not exist");
}
if (!jnatmp.canWrite()) {
throw new IOException("JNA temporary directory '" + jnatmp + "' is not writable");
}
return jnatmp;
}
/** Remove all marked temporary files in the given directory. */
static void removeTemporaryFiles() throws IOException {
File dir = getTempDir();
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".x") && name.startsWith(JNA_TMPLIB_PREFIX);
}
};
File[] files = dir.listFiles(filter);
for (int i=0;files != null && i < files.length;i++) {
File marker = files[i];
String name = marker.getName();