-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathStructure.java
2199 lines (2039 loc) · 81.6 KB
/
Structure.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
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.nio.Buffer;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Represents a native structure with a Java peer class. When used as a
* function parameter or return value, this class corresponds to
* <code>struct*</code>. When used as a field within another
* <code>Structure</code>, it corresponds to <code>struct</code>. The
* tagging interfaces {@link ByReference} and {@link ByValue} may be used
* to alter the default behavior. Structures may have variable size, but only
* by providing an array field (e.g. byte[]).
* <p>
* See the <a href={@docRoot}/overview-summary.html>overview</a> for supported
* type mappings for struct fields.
* <p>
* Structure alignment and type mappings are derived by default from the
* enclosing interface definition (if any) by using
* {@link Native#getStructureAlignment} and {@link Native#getTypeMapper}.
* Alternatively you can explicitly provide alignment, field order, or type
* mapping by calling the respective Structure functions in your subclass's
* constructor.
* </p>
* <p>Structure fields corresponding to native struct fields <em>must</em> be
* public. If your structure is to have no fields of its own, it must be
* declared abstract.
* </p>
* <p>You <em>must</em> annotate the class with {@link FieldOrder} or implement
* {@link #getFieldOrder}, whichever you choose it must contain the field names
* (Strings) indicating the proper order of the fields. If you chose to implement
* {@link #getFieldOrder} notice that when dealing with multiple levels of
* subclasses of Structure, you must add to the list provided by the superclass
* {@link #getFieldOrder} the fields defined in the current class.
* </p>
* <p>In the past, most VMs would return them in a predictable order, but the JVM
* spec does not require it, so {@link #getFieldOrder} is now required to
* ensure JNA knows the proper order).
* </p>
* <p>Structure fields may additionally have the following modifiers:</p>
* <ul>
* <li><code>volatile</code> JNA will not write the field unless specifically
* instructed to do so via {@link #writeField(String)}. This allows you to
* prevent inadvertently overwriting memory that may be updated in real time
* on another (possibly native) thread.
* <li><code>final</code> JNA will overwrite the field via {@link #read()},
* but otherwise the field is not modifiable from Java. Take care when using
* this option, since the compiler will usually assume <em>all</em> accesses
* to the field (for a given Structure instance) have the same value. This
* modifier is invalid to use on J2ME.
* </ul>
* <p>NOTE: Strings are used to represent native C strings because usage of
* <code>char *</code> is generally more common than <code>wchar_t *</code>.
* You may provide a type mapper ({@link com.sun.jna.win32.W32APITypeMapper
* example here)} if you prefer to use String in place of {@link WString} if
* your native code predominantly uses <code>wchar_t *</code>.
* </p>
* <p>NOTE: In general, instances of this class are <em>not</em> synchronized.
* </p>
*
* @author Todd Fast, [email protected]
* @author [email protected]
*/
public abstract class Structure {
/** Tagging interface to indicate the value of an instance of the
* <code>Structure</code> type is to be used in function invocations rather
* than its address. The default behavior is to treat
* <code>Structure</code> function parameters and return values as by
* reference, meaning the address of the structure is used.
*/
public interface ByValue { }
/** Tagging interface to indicate the address of an instance of the
* Structure type is to be used within a <code>Structure</code> definition
* rather than nesting the full Structure contents. The default behavior
* is to inline <code>Structure</code> fields.
*/
public interface ByReference { }
/** Use the platform default alignment. */
public static final int ALIGN_DEFAULT = 0;
/** No alignment, place all fields on nearest 1-byte boundary */
public static final int ALIGN_NONE = 1;
/** validated for 32-bit x86 linux/gcc; align field size, max 4 bytes */
public static final int ALIGN_GNUC = 2;
/** validated for w32/msvc; align on field size */
public static final int ALIGN_MSVC = 3;
/** Align to a 2-byte boundary. */
//public static final int ALIGN_2 = 4;
/** Align to a 4-byte boundary. */
//public static final int ALIGN_4 = 5;
/** Align to an 8-byte boundary. */
//public static final int ALIGN_8 = 6;
protected static final int CALCULATE_SIZE = -1;
static final Map<Class<?>, LayoutInfo> layoutInfo = new WeakHashMap<Class<?>, LayoutInfo>();
static final Map<Class<?>, List<String>> fieldOrder = new WeakHashMap<Class<?>, List<String>>();
// This field is accessed by native code
private Pointer memory;
private int size = CALCULATE_SIZE;
private int alignType;
private String encoding;
private int actualAlignType;
private int structAlignment;
private Map<String, StructField> structFields;
// Keep track of native C strings which have been allocated,
// corresponding to String fields of this Structure
private final Map<String, Object> nativeStrings = new HashMap<String, Object>();
private TypeMapper typeMapper;
// This field is accessed by native code
private long typeInfo;
private boolean autoRead = true;
private boolean autoWrite = true;
// Keep a reference when this structure is mapped to an array
private Structure[] array;
private boolean readCalled;
protected Structure() {
this(ALIGN_DEFAULT);
}
protected Structure(TypeMapper mapper) {
this(null, ALIGN_DEFAULT, mapper);
}
protected Structure(int alignType) {
this(null, alignType);
}
protected Structure(int alignType, TypeMapper mapper) {
this(null, alignType, mapper);
}
/** Create a structure cast onto pre-allocated memory. */
protected Structure(Pointer p) {
this(p, ALIGN_DEFAULT);
}
protected Structure(Pointer p, int alignType) {
this(p, alignType, null);
}
protected Structure(Pointer p, int alignType, TypeMapper mapper) {
setAlignType(alignType);
setStringEncoding(Native.getStringEncoding(getClass()));
initializeTypeMapper(mapper);
validateFields();
if (p != null) {
useMemory(p, 0, true);
}
else {
allocateMemory(CALCULATE_SIZE);
}
initializeFields();
}
/** Return all fields in this structure (ordered). This represents the
* layout of the structure, and will be shared among Structures of the
* same class except when the Structure can have a variable size.
* NOTE: {@link #ensureAllocated()} <em>must</em> be called prior to
* calling this method.
* @return {@link Map} of field names to field representations.
*/
Map<String, StructField> fields() {
return structFields;
}
/**
* @return the type mapper in effect for this Structure.
*/
TypeMapper getTypeMapper() {
return typeMapper;
}
/** Initialize the type mapper for this structure.
* If <code>null</code>, the default mapper for the
* defining class will be used.
* @param mapper Find the type mapper appropriate for this structure's
* context if none was explicitly set.
*/
private void initializeTypeMapper(TypeMapper mapper) {
if (mapper == null) {
mapper = Native.getTypeMapper(getClass());
}
this.typeMapper = mapper;
layoutChanged();
}
/** Call whenever a Structure setting is changed which might affect its
* memory layout.
*/
private void layoutChanged() {
if (this.size != CALCULATE_SIZE) {
this.size = CALCULATE_SIZE;
if (this.memory instanceof AutoAllocated) {
this.memory = null;
}
// recalculate layout, since it was done once already
ensureAllocated();
}
}
/** Set the desired encoding to use when writing String fields to native
* memory.
* @param encoding desired encoding
*/
protected void setStringEncoding(String encoding) {
this.encoding = encoding;
}
/** Encoding to use to convert {@link String} to native <code>const
* char*</code>. Defaults to {@link Native#getDefaultStringEncoding()}.
* @return Current encoding
*/
protected String getStringEncoding() {
return this.encoding;
}
/** Change the alignment of this structure. Re-allocates memory if
* necessary. If alignment is {@link #ALIGN_DEFAULT}, the default
* alignment for the defining class will be used.
* @param alignType desired alignment type
*/
protected void setAlignType(int alignType) {
this.alignType = alignType;
if (alignType == ALIGN_DEFAULT) {
alignType = Native.getStructureAlignment(getClass());
if (alignType == ALIGN_DEFAULT) {
if (Platform.isWindows())
alignType = ALIGN_MSVC;
else
alignType = ALIGN_GNUC;
}
}
this.actualAlignType = alignType;
layoutChanged();
}
/**
* Obtain auto-allocated memory for use with struct represenations.
* @param size desired size
* @return newly-allocated memory
*/
protected Memory autoAllocate(int size) {
return new AutoAllocated(size);
}
/** Set the memory used by this structure. This method is used to
* indicate the given structure is nested within another or otherwise
* overlaid on some other memory block and thus does not own its own
* memory.
* @param m Memory to with which to back this {@link Structure}.
*/
protected void useMemory(Pointer m) {
useMemory(m, 0);
}
/** Set the memory used by this structure. This method is used to
* indicate the given structure is based on natively-allocated data,
* nested within another, or otherwise overlaid on existing memory and
* thus does not own its own memory allocation.
* @param m Base memory to use to back this structure.
* @param offset offset into provided memory where structure mapping
* should start.
*/
protected void useMemory(Pointer m, int offset) {
useMemory(m, offset, false);
}
/** Set the memory used by this structure. This method is used to
* indicate the given structure is based on natively-allocated data,
* nested within another, or otherwise overlaid on existing memory and
* thus does not own its own memory allocation.
* @param m Native pointer
* @param offset offset from pointer to use
* @param force ByValue structures normally ignore requests to use a
* different memory offset; this input is set <code>true</code> when
* setting a ByValue struct that is nested within another struct.
*/
void useMemory(Pointer m, int offset, boolean force) {
try {
// Clear any local cache
nativeStrings.clear();
if (this instanceof ByValue && !force) {
// ByValue parameters always use dedicated memory, so only
// copy the contents of the original
byte[] buf = new byte[size()];
m.read(0, buf, 0, buf.length);
this.memory.write(0, buf, 0, buf.length);
}
else {
// Ensure our memory pointer is initialized, even if we can't
// yet figure out a proper size/layout
this.memory = m.share(offset);
if (size == CALCULATE_SIZE) {
size = calculateSize(false);
}
if (size != CALCULATE_SIZE) {
this.memory = m.share(offset, size);
}
}
this.array = null;
this.readCalled = false;
}
catch(IndexOutOfBoundsException e) {
throw new IllegalArgumentException("Structure exceeds provided memory bounds", e);
}
}
/** Ensure this memory has its size and layout calculated and its
memory allocated. */
protected void ensureAllocated() {
ensureAllocated(false);
}
/** Ensure this memory has its size and layout calculated and its
memory allocated.
@param avoidFFIType used when computing FFI type information
to avoid recursion
*/
private void ensureAllocated(boolean avoidFFIType) {
if (memory == null) {
allocateMemory(avoidFFIType);
}
else if (size == CALCULATE_SIZE) {
this.size = calculateSize(true, avoidFFIType);
if (!(this.memory instanceof AutoAllocated)) {
// Ensure we've set bounds on the shared memory used
try {
this.memory = this.memory.share(0, this.size);
}
catch(IndexOutOfBoundsException e) {
throw new IllegalArgumentException("Structure exceeds provided memory bounds", e);
}
}
}
}
/** Attempt to allocate memory if sufficient information is available.
* Returns whether the operation was successful.
*/
protected void allocateMemory() {
allocateMemory(false);
}
private void allocateMemory(boolean avoidFFIType) {
allocateMemory(calculateSize(true, avoidFFIType));
}
/** Provided for derived classes to indicate a different
* size than the default. Returns whether the operation was successful.
* Will leave memory untouched if it is non-null and not allocated
* by this class.
* @param size how much memory to allocate
*/
protected void allocateMemory(int size) {
if (size == CALCULATE_SIZE) {
// Analyze the struct, but don't worry if we can't yet do it
size = calculateSize(false);
}
else if (size <= 0) {
throw new IllegalArgumentException("Structure size must be greater than zero: " + size);
}
// May need to defer size calculation if derived class not fully
// initialized
if (size != CALCULATE_SIZE) {
if (this.memory == null
|| this.memory instanceof AutoAllocated) {
this.memory = autoAllocate(size);
}
this.size = size;
}
}
/** Returns the size in memory occupied by this Structure.
* @return Native size of this structure, in bytes.
*/
public int size() {
ensureAllocated();
return this.size;
}
/** Clears the native memory associated with this Structure. */
public void clear() {
ensureAllocated();
memory.clear(size());
}
/** Return a {@link Pointer} object to this structure. Note that if you
* use the structure's pointer as a function argument, you are responsible
* for calling {@link #write()} prior to the call and {@link #read()}
* after the call. These calls are normally handled automatically by the
* {@link Function} object when it encounters a {@link Structure} argument
* or return value.
* The returned pointer may not have meaning for {@link Structure.ByValue}
* structure representations.
* @return Native pointer representation of this structure.
*/
public Pointer getPointer() {
ensureAllocated();
return memory;
}
//////////////////////////////////////////////////////////////////////////
// Data synchronization methods
//////////////////////////////////////////////////////////////////////////
// Keep track of ByReference reads to avoid redundant reads of the same
// address
private static final ThreadLocal<Map<Pointer, Structure>> reads = new ThreadLocal<Map<Pointer, Structure>>() {
@Override
protected synchronized Map<Pointer, Structure> initialValue() {
return new HashMap<Pointer, Structure>();
}
};
// Keep track of what is currently being read/written to avoid redundant
// reads (avoids problems with circular references).
private static final ThreadLocal<Set<Structure>> busy = new ThreadLocal<Set<Structure>>() {
@Override
protected synchronized Set<Structure> initialValue() {
return new StructureSet();
}
};
/** Avoid using a hash-based implementation since the hash code
for a Structure is not immutable.
*/
static class StructureSet extends AbstractCollection<Structure> implements Set<Structure> {
Structure[] elements;
private int count;
private void ensureCapacity(int size) {
if (elements == null) {
elements = new Structure[size*3/2];
}
else if (elements.length < size) {
Structure[] e = new Structure[size*3/2];
System.arraycopy(elements, 0, e, 0, elements.length);
elements = e;
}
}
public Structure[] getElements() {
return elements;
}
@Override
public int size() { return count; }
@Override
public boolean contains(Object o) {
return indexOf((Structure) o) != -1;
}
@Override
public boolean add(Structure o) {
if (!contains(o)) {
ensureCapacity(count+1);
elements[count++] = o;
}
return true;
}
private int indexOf(Structure s1) {
for (int i=0;i < count;i++) {
Structure s2 = elements[i];
if (s1 == s2
|| (s1.getClass() == s2.getClass()
&& s1.size() == s2.size()
&& s1.getPointer().equals(s2.getPointer()))) {
return i;
}
}
return -1;
}
@Override
public boolean remove(Object o) {
int idx = indexOf((Structure) o);
if (idx != -1) {
if (--count >= 0) {
elements[idx] = elements[count];
elements[count] = null;
}
return true;
}
return false;
}
/** Simple implementation so that toString() doesn't break.
Provides an iterator over a snapshot of this Set.
*/
@Override
public Iterator<Structure> iterator() {
Structure[] e = new Structure[count];
if (count > 0) {
System.arraycopy(elements, 0, e, 0, count);
}
return Arrays.asList(e).iterator();
}
}
static Set<Structure> busy() {
return busy.get();
}
static Map<Pointer, Structure> reading() {
return reads.get();
}
/** Performs auto-read only if uninitialized. */
void conditionalAutoRead() {
if (!readCalled) {
autoRead();
}
}
/**
* Reads the fields of the struct from native memory
*/
public void read() {
// Avoid reading from a null pointer
if (memory == PLACEHOLDER_MEMORY) {
return;
}
readCalled = true;
// convenience: allocate memory and/or calculate size if it hasn't
// been already; this allows structures to do field-based
// initialization of arrays and not have to explicitly call
// allocateMemory in a ctor
ensureAllocated();
// Avoid redundant reads
if (busy().contains(this)) {
return;
}
busy().add(this);
if (this instanceof Structure.ByReference) {
reading().put(getPointer(), this);
}
try {
for (StructField structField : fields().values()) {
readField(structField);
}
}
finally {
busy().remove(this);
if (reading().get(getPointer()) == this) {
reading().remove(getPointer());
}
}
}
/** Returns the calculated offset of the given field.
* @param name field to examine
* @return return offset of the given field
*/
protected int fieldOffset(String name) {
ensureAllocated();
StructField f = fields().get(name);
if (f == null)
throw new IllegalArgumentException("No such field: " + name);
return f.offset;
}
/** Force a read of the given field from native memory. The Java field
* will be updated from the current contents of native memory.
* @param name field to be read
* @return the new field value, after updating
* @throws IllegalArgumentException if no field exists with the given name
*/
public Object readField(String name) {
ensureAllocated();
StructField f = fields().get(name);
if (f == null)
throw new IllegalArgumentException("No such field: " + name);
return readField(f);
}
/** Obtain the value currently in the Java field. Does not read from
* native memory.
* @param field field to look up
* @return current field value (Java-side only)
*/
Object getFieldValue(Field field) {
try {
return field.get(this);
}
catch (Exception e) {
throw new Error("Exception reading field '" + field.getName() + "' in " + getClass(), e);
}
}
/**
* @param field field to set
* @param value value to set
*/
void setFieldValue(Field field, Object value) {
setFieldValue(field, value, false);
}
private void setFieldValue(Field field, Object value, boolean overrideFinal) {
try {
field.set(this, value);
}
catch(IllegalAccessException e) {
int modifiers = field.getModifiers();
if (Modifier.isFinal(modifiers)) {
if (overrideFinal) {
// WARNING: setAccessible(true) on J2ME does *not* allow
// overwriting of a final field.
throw new UnsupportedOperationException("This VM does not support Structures with final fields (field '" + field.getName() + "' within " + getClass() + ")", e);
}
throw new UnsupportedOperationException("Attempt to write to read-only field '" + field.getName() + "' within " + getClass(), e);
}
throw new Error("Unexpectedly unable to write to field '" + field.getName() + "' within " + getClass(), e);
}
}
/** Only keep the original structure if its native address is unchanged.
* Otherwise replace it with a new object.
* @param type Structure subclass
* @param s Original Structure object
* @param address the native <code>struct *</code>
* @return Updated <code>Structure.ByReference</code> object
*/
static <T extends Structure> T updateStructureByReference(Class<T> type, T s, Pointer address) {
if (address == null) {
s = null;
}
else {
if (s == null || !address.equals(s.getPointer())) {
Structure s1 = reading().get(address);
if (s1 != null && type.equals(s1.getClass())) {
s = (T) s1;
s.autoRead();
}
else {
s = newInstance(type, address);
s.conditionalAutoRead();
}
}
else {
s.autoRead();
}
}
return s;
}
/** Read the given field and return its value. The Java field will be
* updated from the contents of native memory.
* @param structField field to be read
* @return value of the requested field
*/
// TODO: make overridable method with calculated native type, offset, etc
protected Object readField(StructField structField) {
// Get the offset of the field
int offset = structField.offset;
// Determine the type of the field
Class<?> fieldType = structField.type;
FromNativeConverter readConverter = structField.readConverter;
if (readConverter != null) {
fieldType = readConverter.nativeType();
}
// Get the current value only for types which might need to be preserved
Object currentValue = (Structure.class.isAssignableFrom(fieldType)
|| Callback.class.isAssignableFrom(fieldType)
|| (Platform.HAS_BUFFERS && Buffer.class.isAssignableFrom(fieldType))
|| Pointer.class.isAssignableFrom(fieldType)
|| NativeMapped.class.isAssignableFrom(fieldType)
|| fieldType.isArray())
? getFieldValue(structField.field) : null;
Object result;
if (fieldType == String.class) {
Pointer p = memory.getPointer(offset);
result = p == null ? null : p.getString(0, encoding);
}
else {
result = memory.getValue(offset, fieldType, currentValue);
}
if (readConverter != null) {
result = readConverter.fromNative(result, structField.context);
if (currentValue != null && currentValue.equals(result)) {
result = currentValue;
}
}
if (fieldType.equals(String.class)
|| fieldType.equals(WString.class)) {
nativeStrings.put(structField.name + ".ptr", memory.getPointer(offset));
nativeStrings.put(structField.name + ".val", result);
}
// Update the value on the Java field
setFieldValue(structField.field, result, true);
return result;
}
/**
* Writes the fields of the struct to native memory
*/
public void write() {
// Avoid writing to a null pointer
if (memory == PLACEHOLDER_MEMORY) {
return;
}
// convenience: allocate memory if it hasn't been already; this
// allows structures to do field-based initialization of arrays and not
// have to explicitly call allocateMemory in a ctor
ensureAllocated();
// Update native FFI type information, if needed
if (this instanceof ByValue) {
getTypeInfo();
}
// Avoid redundant writes
if (busy().contains(this)) {
return;
}
busy().add(this);
try {
// Write all fields, except those marked 'volatile'
for (StructField sf : fields().values()) {
if (!sf.isVolatile) {
writeField(sf);
}
}
}
finally {
busy().remove(this);
}
}
/** Write the given field to native memory. The current value in the Java
* field will be translated into native memory.
* @param name which field to synch
* @throws IllegalArgumentException if no field exists with the given name
*/
public void writeField(String name) {
ensureAllocated();
StructField f = fields().get(name);
if (f == null)
throw new IllegalArgumentException("No such field: " + name);
writeField(f);
}
/** Write the given field value to the field and native memory. The
* given value will be written both to the Java field and the
* corresponding native memory.
* @param name field to write
* @param value value to write
* @throws IllegalArgumentException if no field exists with the given name
*/
public void writeField(String name, Object value) {
ensureAllocated();
StructField structField = fields().get(name);
if (structField == null)
throw new IllegalArgumentException("No such field: " + name);
setFieldValue(structField.field, value);
writeField(structField);
}
/**
* @param structField internal field representation to synch to native memory
*/
protected void writeField(StructField structField) {
if (structField.isReadOnly)
return;
// Get the offset of the field
int offset = structField.offset;
// Get the value from the field
Object value = getFieldValue(structField.field);
// Determine the type of the field
Class<?> fieldType = structField.type;
ToNativeConverter converter = structField.writeConverter;
if (converter != null) {
value = converter.toNative(value, new StructureWriteContext(this, structField.field));
fieldType = converter.nativeType();
}
// Java strings get converted to C strings, where a Pointer is used
if (String.class == fieldType
|| WString.class == fieldType) {
// Allocate a new string in memory
boolean wide = fieldType == WString.class;
if (value != null) {
// If we've already allocated a native string here, and the
// string value is unchanged, leave it alone
if (nativeStrings.containsKey(structField.name + ".ptr")
&& value.equals(nativeStrings.get(structField.name + ".val"))) {
return;
}
NativeString nativeString = wide
? new NativeString(value.toString(), true)
: new NativeString(value.toString(), encoding);
// Keep track of allocated C strings to avoid
// premature garbage collection of the memory.
nativeStrings.put(structField.name, nativeString);
value = nativeString.getPointer();
}
else {
nativeStrings.remove(structField.name);
}
nativeStrings.remove(structField.name + ".ptr");
nativeStrings.remove(structField.name + ".val");
}
try {
memory.setValue(offset, value, fieldType);
}
catch(IllegalArgumentException e) {
String msg = "Structure field \"" + structField.name
+ "\" was declared as " + structField.type
+ (structField.type == fieldType
? "" : " (native type " + fieldType + ")")
+ ", which is not supported within a Structure";
throw new IllegalArgumentException(msg, e);
}
}
/** Used to declare fields order as metadata instead of method.
* example:
* <pre><code>
* // New
* {@literal @}FieldOrder({ "n", "s" })
* class Parent extends Structure {
* public int n;
* public String s;
* }
* {@literal @}FieldOrder({ "d", "c" })
* class Son extends Parent {
* public double d;
* public char c;
* }
* // Old
* class Parent extends Structure {
* public int n;
* public String s;
* protected List<String> getFieldOrder() {
* return Arrays.asList("n", "s");
* }
* }
* class Son extends Parent {
* public double d;
* public char c;
* protected List<String> getFieldOrder() {
* List<String> fields = new LinkedList<String>(super.getFieldOrder());
* fields.addAll(Arrays.asList("d", "c"));
* return fields;
* }
* }
* </code></pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FieldOrder {
String[] value();
}
/** Returns this Structure's field names in their proper order.<br>
*
* When defining a new {@link Structure} you shouldn't override this
* method, but use {@link FieldOrder} annotation to define your field
* order(this also works with inheritance)<br>
*
* If you want to do something non-standard you can override the method
* and define it as followed
* <pre><code>
* protected List<String> getFieldOrder() {
* return Arrays.asList(...);
* }
* </code></pre>
* <strong>IMPORTANT</strong>
* When deriving from an existing Structure subclass, ensure that
* you augment the list provided by the superclass, e.g.
* <pre><code>
* protected List<String> getFieldOrder() {
* List<String> fields = new LinkedList<String>(super.getFieldOrder());
* fields.addAll(Arrays.asList(...));
* return fields;
* }
* </code></pre>
*
* Field order must be explicitly indicated, since the
* field order as returned by {@link Class#getFields()} is not
* guaranteed to be predictable.
* @return ordered list of field names
*/
// TODO(idosu 28 Apr 2018): Maybe deprecate this method to let users know they should use @FieldOrder
protected List<String> getFieldOrder() {
List<String> fields = new LinkedList<String>();
for (Class<?> clazz = getClass(); clazz != Structure.class; clazz = clazz.getSuperclass()) {
FieldOrder order = clazz.getAnnotation(FieldOrder.class);
if (order != null) {
fields.addAll(0, Arrays.asList(order.value()));
}
}
// fields.isEmpty() can be true because it is check somewhere else
return Collections.unmodifiableList(fields);
}
/** Sort the structure fields according to the given array of names.
* @param fields list of fields to be sorted
* @param names list of names representing the desired sort order
*/
protected void sortFields(List<Field> fields, List<String> names) {
for (int i=0;i < names.size();i++) {
String name = names.get(i);
for (int f=0;f < fields.size();f++) {
Field field = fields.get(f);
if (name.equals(field.getName())) {
Collections.swap(fields, i, f);
break;
}
}
}
}
/** Look up all fields in this class and superclasses.
* @return ordered list of public {@link java.lang.reflect.Field} available on
* this {@link Structure} class.
*/
protected List<Field> getFieldList() {
List<Field> flist = new ArrayList<Field>();
for (Class<?> cls = getClass();
!cls.equals(Structure.class);
cls = cls.getSuperclass()) {
List<Field> classFields = new ArrayList<Field>();
Field[] fields = cls.getDeclaredFields();
for (int i=0;i < fields.length;i++) {
int modifiers = fields[i].getModifiers();
if (Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers)) {
continue;
}
classFields.add(fields[i]);
}
flist.addAll(0, classFields);
}
return flist;
}
/** Cache field order per-class.
* @return (cached) ordered list of fields
*/