-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathPointer.java
More file actions
7061 lines (6549 loc) · 291 KB
/
Copy pathPointer.java
File metadata and controls
7061 lines (6549 loc) · 291 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
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
package org.rustlang.runtime;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
public final class Pointer {
public static void dropRustValue(Object value) {
if (value instanceof RustDrop) {
((RustDrop) value).rustDrop();
} else if (value instanceof TraitObjectCarrier) {
dropRustValue(((TraitObjectCarrier) value).rustTraitObjectPayload());
} else if (value instanceof Pointer) {
Object pointee = ((Pointer) value).directCellValueOrSelf();
if (pointee != value) {
dropRustValue(pointee);
}
}
}
public static boolean catchUnwind(Object tryFunction, Pointer data, Object catchFunction) {
try {
invokeRustFunction(tryFunction, data);
return false;
} catch (Throwable failure) {
PanicSupport.abortIfStackOverflow(failure);
if (failure instanceof VirtualMachineError || failure instanceof ThreadDeath) {
rethrowUnchecked(failure);
}
if (Boolean.getBoolean("org.rustlang.debugUnwind")) {
failure.printStackTrace(System.err);
}
Pointer payload = Pointer.cell(failure, 8, MANAGED_OBJECT_VIEW_CODEC);
invokeRustFunction(catchFunction, data, payload);
return true;
}
}
static Object invokeRustFunction(Object function, Object... arguments) {
if (function == null) {
throw new NullPointerException("Rust function pointer is null");
}
Method target = null;
for (Method method : function.getClass().getMethods()) {
if (method.getName().equals("call")
&& method.getParameterTypes().length == arguments.length) {
target = method;
break;
}
}
if (target == null) {
throw new IllegalArgumentException(
"Rust function pointer has no compatible call method: "
+ function.getClass().getName());
}
try {
target.setAccessible(true);
return target.invoke(function, arguments);
} catch (InvocationTargetException failure) {
rethrowUnchecked(failure.getCause());
return null;
} catch (IllegalAccessException failure) {
throw new IllegalStateException("Rust function pointer invocation failed", failure);
}
}
private static void rethrowUnchecked(Throwable failure) {
if (failure instanceof RuntimeException) {
throw (RuntimeException) failure;
}
if (failure instanceof Error) {
throw (Error) failure;
}
throw new IllegalStateException("Rust unwind handler failed", failure);
}
private static final String MANAGED_OBJECT_VIEW_CODEC = "@managed-object";
private static final String RAW_POINTER_VIEW_CODEC = "@raw-pointer";
private static final String ARRAY_REFERENCE_VIEW_CODEC_PREFIX = "@array-reference\n";
private static final String SLICE_POINTER_VIEW_CODEC_PREFIX = "@slice-pointer\n";
private static final String STRUCT_TAIL_POINTER_VIEW_CODEC_PREFIX =
"@struct-tail-pointer\n";
private static final String TRAIT_POINTER_VIEW_CODEC_PREFIX = "@trait-pointer\n";
private static final String SIGNED_BIG_INTEGER_CODEC = "@signed-big-integer";
private static final String UNSIGNED_BIG_INTEGER_CODEC = "@unsigned-big-integer";
private static final String F128_CODEC = "@f128";
private static final String STRUCTURAL_VIEW_CODEC_PREFIX = "@structural-view:";
private static final String STRUCT_TAIL_VIEW_CODEC_PREFIX = "@struct-tail-view:";
private static final String SLICE_VIEW_CLASS_NAME = "org.rustlang.runtime.SliceView";
private static final AtomicLong NEXT_ADDRESS = new AtomicLong(0x1_0000_0000L);
private static final Map<IdentityWeakReference, AllocationInfo> ALLOCATIONS = new HashMap<>();
private static final ReferenceQueue<Object> ALLOCATION_INFO_QUEUE = new ReferenceQueue<>();
private static final Map<Object, Boolean> ALLOCATOR_OWNED_ALLOCATIONS =
new IdentityHashMap<>();
private static final Map<String, byte[]> CONSTANT_ALLOCATIONS = new HashMap<>();
private static final Map<String, Pointer> CONSTANT_CELLS = new HashMap<>();
private static final Map<Long, ExposedTarget> EXPOSED_ADDRESSES = new HashMap<>();
private static final Map<Long, Map<String, ExposedTarget>> TYPED_EXPOSED_ADDRESSES =
new HashMap<>();
private static final Map<Object, Set<Long>> ALLOCATION_EXPOSED_ADDRESSES =
new IdentityHashMap<>();
private static final NavigableMap<Long, AllocationRange> ALLOCATION_RANGES =
new TreeMap<>();
private static final ReferenceQueue<Object> ALLOCATION_RANGE_QUEUE =
new ReferenceQueue<>();
private static final ConcurrentHashMap<String, Method[]> CODEC_METHODS =
new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, String[]> CODEC_DESCRIPTORS =
new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, String> BINARY_CLASS_NAMES =
new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Class<?>, Method[]> SCALAR_ENUM_METHODS =
new ConcurrentHashMap<>();
private static final Map<ClassLoader, ConcurrentHashMap<String, Class<?>>> RESOLVED_CLASSES =
new IdentityHashMap<>();
private static final ClassValue<ConcurrentHashMap<String, Field>> INSTANCE_FIELDS =
new ClassValue<ConcurrentHashMap<String, Field>>() {
@Override
protected ConcurrentHashMap<String, Field> computeValue(Class<?> type) {
return new ConcurrentHashMap<>();
}
};
private static final ClassValue<Field[]> PUBLIC_INSTANCE_FIELDS =
new ClassValue<Field[]>() {
@Override
protected Field[] computeValue(Class<?> type) {
Field[] all = type.getFields();
int count = 0;
for (Field field : all) {
if (!Modifier.isStatic(field.getModifiers())) {
count++;
}
}
Field[] fields = new Field[count];
int index = 0;
for (Field field : all) {
if (!Modifier.isStatic(field.getModifiers())) {
field.setAccessible(true);
fields[index++] = field;
}
}
return fields;
}
};
private static final ClassValue<Map<Integer, Constructor<?>>> PUBLIC_CONSTRUCTORS_BY_ARITY =
new ClassValue<Map<Integer, Constructor<?>>>() {
@Override
protected Map<Integer, Constructor<?>> computeValue(Class<?> type) {
Map<Integer, Constructor<?>> constructors = new HashMap<>();
for (Constructor<?> constructor : type.getConstructors()) {
constructor.setAccessible(true);
constructors.putIfAbsent(constructor.getParameterCount(), constructor);
}
return constructors;
}
};
private static final ClassValue<Constructor<?>> SLICE_VIEW_CONSTRUCTORS =
new ClassValue<Constructor<?>>() {
@Override
protected Constructor<?> computeValue(Class<?> type) {
try {
Constructor<?> constructor =
type.getConstructor(Object.class, int.class, int.class);
constructor.setAccessible(true);
return constructor;
} catch (NoSuchMethodException error) {
throw new IllegalStateException(
"Rust slice view has no array/offset/length constructor", error);
}
}
};
private static final ClassValue<Constructor<?>> LONG_SLICE_VIEW_CONSTRUCTORS =
new ClassValue<Constructor<?>>() {
@Override
protected Constructor<?> computeValue(Class<?> type) {
try {
Constructor<?> constructor =
type.getConstructor(Object.class, int.class, long.class);
constructor.setAccessible(true);
return constructor;
} catch (NoSuchMethodException error) {
throw new IllegalStateException(
"Rust slice view has no long-length constructor", error);
}
}
};
private static final ClassValue<Boolean> RUST_FUNCTION_POINTER_TYPES =
new ClassValue<Boolean>() {
@Override
protected Boolean computeValue(Class<?> type) {
for (Class<?> implementedInterface : type.getInterfaces()) {
if (implementedInterface.getName()
.startsWith("org.rustlang.runtime.FnPtr_")) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
};
private static final ClassValue<ManagedCopyPlan> MANAGED_COPY_PLANS =
new ClassValue<ManagedCopyPlan>() {
@Override
protected ManagedCopyPlan computeValue(Class<?> type) {
Field[] fields = PUBLIC_INSTANCE_FIELDS.get(type);
Constructor<?> constructor = constructorWithArity(type, fields.length);
Class<?>[] parameterTypes = constructor.getParameterTypes();
Object[] defaults = new Object[parameterTypes.length];
for (int index = 0; index < parameterTypes.length; index++) {
defaults[index] = defaultValue(parameterTypes[index]);
}
return new ManagedCopyPlan(fields, constructor, defaults);
}
};
private static final Map<Object, Long> MANAGED_OBJECT_ADDRESSES = new IdentityHashMap<>();
private static final Map<Long, WeakReference<Object>> MANAGED_OBJECTS = new HashMap<>();
private static final Map<String, byte[]> JAVA_STRING_UTF8 = new IdentityHashMap<>();
private static final Map<String, Pointer> TRAIT_METADATA_MARKERS = new HashMap<>();
private static final ConcurrentHashMap<Long, TraitMetadataInfo> TRAIT_METADATA_INFO =
new ConcurrentHashMap<>();
private static final int STATE_STRIPE_COUNT = 64;
private static final int LAZY_ARRAY_REPEAT_THRESHOLD = 2;
private static final int REPEATED_ARRAY_FILTER_WORDS = 1 << 16;
private static final AtomicLongArray REPEATED_ARRAY_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final AtomicLongArray STRUCTURAL_VIEW_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final AtomicLongArray MEMORY_VIEW_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final AtomicLongArray MEMORY_VIEW_ORIGIN_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final AtomicLongArray ENCODED_REFERENCE_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final Map<Object, Map<Long, StructuralViewState>>[] STRUCTURAL_VIEWS =
createWeakMapStripes();
private static final Map<Object, NavigableMap<Long, MemoryViewState>>[] MEMORY_VIEWS =
createWeakMapStripes();
private static final Map<Object, MemoryViewOrigin>[] MEMORY_VIEW_ORIGINS =
createWeakMapStripes();
private static final Map<Object, Map<Object, Boolean>>[] MEMORY_ORIGIN_VIEWS =
createWeakMapStripes();
private static final Map<Object, RepeatedArrayState>[] REPEATED_ARRAYS =
createWeakMapStripes();
private static final Map<Object, Object>[] ENCODED_REFERENCES =
createWeakMapStripes();
private static final ThreadLocal<Integer> MEMORY_VIEW_WRITEBACK_DEPTH =
ThreadLocal.withInitial(() -> 0);
private static final Map<Object, Map<String, WeakReference<FieldCell>>>[] FIELD_CELLS =
createWeakMapStripes();
private static final int ATOMIC_STRIPE_COUNT = 64;
private static final int ATOMIC_RELAXED = 0;
private static final int ATOMIC_RELEASE = 1;
private static final int ATOMIC_ACQUIRE = 2;
private static final int ATOMIC_ACQ_REL = 3;
private static final int ATOMIC_SEQ_CST = 4;
private static final Object[] ATOMIC_STRIPES = createAtomicStripes();
private static final Object ATOMIC_SEQUENCE_LOCK = new Object();
private static final AtomicLong ATOMIC_FENCE_EPOCH = new AtomicLong();
@SuppressWarnings("unchecked")
private static <V> Map<Object, V>[] createWeakMapStripes() {
Map<Object, V>[] stripes = (Map<Object, V>[]) new Map<?, ?>[STATE_STRIPE_COUNT];
for (int index = 0; index < stripes.length; index++) {
stripes[index] = new WeakIdentityMap<>();
}
return stripes;
}
private static <V> Map<Object, V> stateStripe(Map<Object, V>[] stripes, Object key) {
int hash = key == null ? 0 : System.identityHashCode(key);
hash ^= hash >>> 16;
return stripes[hash & (stripes.length - 1)];
}
private static Object encodedReferenceOwner(Object owner) {
return owner instanceof FieldCell ? ((FieldCell) owner).owner() : owner;
}
private static void retainEncodedReference(Object owner, Object referencedAllocation) {
owner = encodedReferenceOwner(owner);
if (owner == null
|| referencedAllocation == null
|| owner == referencedAllocation) {
return;
}
markIdentityFilter(ENCODED_REFERENCE_FILTER, owner);
Map<Object, Object> stripe =
stateStripe(ENCODED_REFERENCES, owner);
synchronized (stripe) {
Object current = stripe.get(owner);
if (current == null) {
stripe.put(owner, referencedAllocation);
} else if (current != referencedAllocation) {
EncodedReferenceSet references;
if (current instanceof EncodedReferenceSet) {
references = (EncodedReferenceSet) current;
} else {
references = new EncodedReferenceSet(current);
stripe.put(owner, references);
}
references.allocations.put(referencedAllocation, Boolean.TRUE);
}
}
}
private static void transferEncodedReferences(Object sourceOwner, Object targetOwner) {
sourceOwner = encodedReferenceOwner(sourceOwner);
targetOwner = encodedReferenceOwner(targetOwner);
if (sourceOwner == null || targetOwner == null || sourceOwner == targetOwner) {
return;
}
if (!mayBeInIdentityFilter(ENCODED_REFERENCE_FILTER, sourceOwner)) {
return;
}
Map<Object, Object> sourceStripe =
stateStripe(ENCODED_REFERENCES, sourceOwner);
Object referenced;
Object[] referencedSet = null;
synchronized (sourceStripe) {
referenced = sourceStripe.get(sourceOwner);
if (referenced == null) {
return;
}
if (referenced instanceof EncodedReferenceSet) {
referencedSet = ((EncodedReferenceSet) referenced)
.allocations.keySet().toArray();
}
}
if (referencedSet != null) {
for (Object allocation : referencedSet) {
retainEncodedReference(targetOwner, allocation);
}
} else {
retainEncodedReference(targetOwner, referenced);
}
}
private static void moveEncodedReferences(Object sourceOwner, Object targetOwner) {
Object source = encodedReferenceOwner(sourceOwner);
Object target = encodedReferenceOwner(targetOwner);
if (source == null || source == target) {
return;
}
transferEncodedReferences(source, target);
discardEncodedReferences(source);
}
private static void discardEncodedReferences(Object owner) {
owner = encodedReferenceOwner(owner);
if (owner == null) {
return;
}
if (!mayBeInIdentityFilter(ENCODED_REFERENCE_FILTER, owner)) {
return;
}
Map<Object, Object> stripe =
stateStripe(ENCODED_REFERENCES, owner);
synchronized (stripe) {
stripe.remove(owner);
}
}
private static final class EncodedReferenceSet {
private final IdentityHashMap<Object, Boolean> allocations = new IdentityHashMap<>();
private EncodedReferenceSet(Object first) {
allocations.put(first, Boolean.TRUE);
}
}
private static final class IdentityWeakReference extends WeakReference<Object> {
private final int identityHash;
private IdentityWeakReference(Object value, ReferenceQueue<Object> queue) {
super(value, queue);
identityHash = System.identityHashCode(value);
}
@Override
public int hashCode() {
return identityHash;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof IdentityWeakReference)) {
return false;
}
Object value = get();
return value != null && value == ((IdentityWeakReference) other).get();
}
}
private static final class WeakIdentityMap<V> extends AbstractMap<Object, V> {
private static final class Entry<V> extends WeakReference<Object> {
private final int identityHash;
private V value;
private Entry<V> next;
private Entry(
Object key, V value, ReferenceQueue<Object> queue, Entry<V> next) {
super(key, queue);
identityHash = System.identityHashCode(key);
this.value = value;
this.next = next;
}
}
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
private Entry<V>[] buckets = newTable(16);
private int size;
@SuppressWarnings("unchecked")
private static <V> Entry<V>[] newTable(int length) {
return (Entry<V>[]) new Entry<?>[length];
}
private static int bucketIndex(int hash, int length) {
hash ^= hash >>> 16;
return hash & (length - 1);
}
private void removeEntry(Entry<V> target) {
int index = bucketIndex(target.identityHash, buckets.length);
Entry<V> previous = null;
for (Entry<V> entry = buckets[index]; entry != null; entry = entry.next) {
if (entry == target) {
if (previous == null) {
buckets[index] = entry.next;
} else {
previous.next = entry.next;
}
entry.next = null;
size--;
return;
}
previous = entry;
}
}
private void discardCollected(int limit) {
for (int count = 0; count < limit; count++) {
@SuppressWarnings("unchecked")
Entry<V> reference = (Entry<V>) queue.poll();
if (reference == null) {
return;
}
removeEntry(reference);
}
}
private void resize() {
Entry<V>[] oldBuckets = buckets;
buckets = newTable(oldBuckets.length << 1);
for (Entry<V> bucket : oldBuckets) {
Entry<V> entry = bucket;
while (entry != null) {
Entry<V> next = entry.next;
int index = bucketIndex(entry.identityHash, buckets.length);
entry.next = buckets[index];
buckets[index] = entry;
entry = next;
}
}
}
@Override
public V get(Object key) {
discardCollected(8);
int hash = System.identityHashCode(key);
int index = bucketIndex(hash, buckets.length);
for (Entry<V> entry = buckets[index]; entry != null; entry = entry.next) {
if (entry.identityHash == hash && entry.get() == key) {
return entry.value;
}
}
return null;
}
@Override
public V put(Object key, V value) {
discardCollected(8);
int hash = System.identityHashCode(key);
int index = bucketIndex(hash, buckets.length);
for (Entry<V> entry = buckets[index]; entry != null; entry = entry.next) {
if (entry.identityHash == hash && entry.get() == key) {
V previous = entry.value;
entry.value = value;
return previous;
}
}
buckets[index] = new Entry<>(key, value, queue, buckets[index]);
size++;
if (size * 4 >= buckets.length * 3) {
resize();
}
return null;
}
@Override
public V remove(Object key) {
discardCollected(8);
int hash = System.identityHashCode(key);
int index = bucketIndex(hash, buckets.length);
Entry<V> previous = null;
for (Entry<V> entry = buckets[index]; entry != null; entry = entry.next) {
if (entry.identityHash == hash && entry.get() == key) {
if (previous == null) {
buckets[index] = entry.next;
} else {
previous.next = entry.next;
}
entry.next = null;
size--;
return entry.value;
}
previous = entry;
}
return null;
}
@Override
public Set<Map.Entry<Object, V>> entrySet() {
discardCollected(Integer.MAX_VALUE);
Set<Map.Entry<Object, V>> entries = new HashSet<>();
for (Entry<V> bucket : buckets) {
for (Entry<V> entry = bucket; entry != null; entry = entry.next) {
Object key = entry.get();
if (key != null) {
entries.add(new java.util.AbstractMap.SimpleImmutableEntry<>(
key, entry.value));
}
}
}
return entries;
}
}
/** Must be called while holding {@link #ALLOCATIONS}. */
private static void discardCollectedAllocationInfo(int limit) {
for (int count = 0; count < limit; count++) {
IdentityWeakReference reference =
(IdentityWeakReference) ALLOCATION_INFO_QUEUE.poll();
if (reference == null) {
return;
}
ALLOCATIONS.remove(reference);
}
}
/** Must be called while holding {@link #ALLOCATIONS}. */
private static AllocationInfo allocationInfo(Object allocation) {
discardCollectedAllocationInfo(8);
IdentityWeakReference lookup = new IdentityWeakReference(allocation, null);
AllocationInfo info = ALLOCATIONS.get(lookup);
if (info == null) {
info = new AllocationInfo();
ALLOCATIONS.put(
new IdentityWeakReference(allocation, ALLOCATION_INFO_QUEUE), info);
}
return info;
}
private static void recordAlignment(Object allocation, int alignment) {
// Synthetic addresses are already 16-byte aligned. Avoid creating
// allocation metadata for the overwhelmingly common weaker layouts.
if (alignment <= 16) {
return;
}
synchronized (ALLOCATIONS) {
allocationInfo(allocation).alignment = alignment;
}
}
private static boolean isSliceViewType(Class<?> type) {
return type != null && SLICE_VIEW_CLASS_NAME.equals(type.getName());
}
private static boolean isSliceViewCarrierType(Class<?> type) {
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
if (SLICE_VIEW_CLASS_NAME.equals(current.getName())) {
return true;
}
}
return false;
}
/**
* Keeps the distinct JVM carriers for a Rust struct-tail unsizing coercion
* coherent. Rust guarantees exclusive access through a mutable borrow, so
* synchronizing when execution changes carrier is sufficient even though
* mutations happen directly on the generated public fields.
*/
private static final class StructuralViewState {
private final Map<Class<?>, Object> views = new HashMap<>();
private Object active;
private StructuralViewState(Object source) {
views.put(source.getClass(), source);
active = source;
}
private Object activate(Class<?> targetClass) {
return activate(targetClass, null);
}
private Object activate(Class<?> targetClass, Object traitTailCarrier) {
Object target = views.get(targetClass);
if (target == null) {
target = constructStructuralView(active, targetClass, traitTailCarrier);
views.put(targetClass, target);
} else if (target != active) {
copyStructuralFields(active, target);
}
active = target;
return target;
}
}
/**
* A live JVM view of aggregate data stored in byte-addressable Rust memory.
* Generated code can mutate public fields directly after a pointer load, so
* the decoded carrier must remain authoritative until the memory is next
* observed through another view.
*/
private static final class MemoryViewState {
private final int size;
private final String codecClassName;
private final Object value;
private byte[] originalImage;
private MemoryViewState(
int size, String codecClassName, Object value, byte[] originalImage) {
this.size = size;
this.codecClassName = codecClassName;
this.value = value;
this.originalImage = originalImage;
}
}
/** Original byte-addressable storage for a decoded aggregate receiver. */
private static final class MemoryViewOrigin {
private final WeakReference<Object> allocation;
private final int allocationElementSize;
private final long byteOffset;
private final long viewSize;
private final String allocationCodecClassName;
private final long metadata;
private MemoryViewOrigin(Pointer pointer) {
allocation = new WeakReference<>(pointer.allocation);
allocationElementSize = pointer.allocationElementSize;
byteOffset = pointer.byteOffset;
viewSize = pointer.viewSize;
allocationCodecClassName = pointer.allocationCodecClassName;
metadata = pointer.metadata;
}
private boolean matches(Pointer pointer) {
return allocation.get() == pointer.allocation
&& allocationElementSize == pointer.allocationElementSize
&& byteOffset == pointer.byteOffset
&& viewSize == pointer.viewSize
&& java.util.Objects.equals(
allocationCodecClassName, pointer.allocationCodecClassName)
&& metadata == pointer.metadata;
}
}
private static final class ManagedCopyPlan {
private final Field[] fields;
private final Constructor<?> constructor;
private final Object[] defaults;
private ManagedCopyPlan(
Field[] fields, Constructor<?> constructor, Object[] defaults) {
this.fields = fields;
this.constructor = constructor;
this.defaults = defaults;
}
}
private static final class RepeatedArrayState {
private final Object template;
private RepeatedArrayState(Object template) {
this.template = template;
}
}
private static Constructor<?> constructorWithArity(Class<?> type, int arity) {
Constructor<?> constructor = PUBLIC_CONSTRUCTORS_BY_ARITY.get(type).get(arity);
if (constructor == null) {
throw new IllegalArgumentException(
"no generated Rust value constructor for " + type.getName());
}
return constructor;
}
/**
* Implements a whole-value assignment through an instance method's
* {@code &mut self}. The JVM receiver identity cannot be replaced, so copy
* the generated Rust value fields from the replacement object instead.
*/
public static void overwriteManagedObject(Object target, Object replacement) {
if (target == replacement) {
return;
}
if (target == null || replacement == null || target.getClass() != replacement.getClass()) {
throw new IllegalArgumentException("managed-object overwrite requires matching non-null classes");
}
copyStructuralFields(replacement, target);
}
/** Runs generated Rust element drop glue over a dynamically sized slice. */
public static void dropSlice(Object slice, String ownerClassName, String methodName) {
if (slice == null) {
return;
}
try {
Class<?> sliceClass = slice.getClass();
Object array = instanceField(sliceClass, "array").get(slice);
int offset = instanceField(sliceClass, "offset").getInt(slice);
int length = instanceField(sliceClass, "length").getInt(slice);
Pointer data = array instanceof Pointer
? ((Pointer) array).sliceElementView().add(offset)
: null;
if (data == null && (array == null || !array.getClass().isArray())) {
throw new IllegalArgumentException("Rust slice drop requires array-backed storage");
}
MethodHandle drop = null;
for (int index = 0; index < length; index++) {
Pointer element = data == null
? Pointer.cell(Array.get(array, offset + index))
: data.add(index);
Object managed = element.getObject();
if (managed instanceof RustDrop) {
((RustDrop) managed).rustDrop();
} else {
if (drop == null) {
Class<?> owner = resolvedRuntimeClass(ownerClassName);
drop = MethodHandles.publicLookup().findStatic(
owner,
methodName,
MethodType.methodType(void.class, Pointer.class));
}
drop.invokeExact(element);
}
}
} catch (ReflectiveOperationException error) {
throw new IllegalStateException("could not invoke Rust slice element drop glue", error);
} catch (Throwable error) {
PanicSupport.abortIfStackOverflow(error);
if (error instanceof RuntimeException) {
throw (RuntimeException) error;
}
if (error instanceof Error) {
throw (Error) error;
}
throw new IllegalStateException("Rust slice element drop failed", error);
}
}
/** Creates an independent JVM carrier for a copied Rust aggregate value. */
public static Object copyManagedValue(Object value) {
if (value == null) {
return null;
}
Class<?> valueClass = value.getClass();
if (valueClass.isArray()) {
int length = Array.getLength(value);
Object copy = Array.newInstance(valueClass.getComponentType(), length);
if (valueClass.getComponentType().isPrimitive()) {
System.arraycopy(value, 0, copy, 0, length);
transferEncodedReferences(value, copy);
} else {
Object[] sourceElements = (Object[]) value;
Object[] copyElements = (Object[]) copy;
for (int index = 0; index < length; index++) {
copyElements[index] = copyManagedValue(sourceElements[index]);
}
}
return copy;
}
if (isManagedValueImmutable(value, valueClass)) {
return value;
}
try {
ManagedCopyPlan plan = MANAGED_COPY_PLANS.get(valueClass);
Object copy = plan.constructor.newInstance(plan.defaults);
for (Field field : plan.fields) {
field.set(copy, copyManagedValue(field.get(value)));
}
return copy;
} catch (ReflectiveOperationException error) {
throw new IllegalStateException("could not copy managed Rust value", error);
}
}
private static boolean isManagedValueImmutable(Object value, Class<?> valueClass) {
return valueClass.isPrimitive()
|| value instanceof Number
|| value instanceof Boolean
|| value instanceof Character
|| value instanceof String
|| valueClass.isEnum()
|| valueClass.getName().startsWith("org.rustlang.runtime.")
|| isRustFunctionPointer(valueClass);
}
/**
* Implements a Rust array-repeat initializer without requiring the
* compiler to emit one bytecode store for every element.
*/
public static void fillArray(Object array, Object value, boolean copyValue) {
int length = Array.getLength(array);
Map<Object, RepeatedArrayState> stripe = stateStripe(REPEATED_ARRAYS, array);
synchronized (stripe) {
stripe.remove(array);
}
if (copyValue
&& length >= LAZY_ARRAY_REPEAT_THRESHOLD
&& value != null
&& !array.getClass().getComponentType().isPrimitive()
&& !isManagedValueImmutable(value, value.getClass())) {
Arrays.fill((Object[]) array, value);
synchronized (stripe) {
stripe.put(array, new RepeatedArrayState(value));
}
markRepeatedArray(array);
return;
}
for (int index = 0; index < length; index++) {
Array.set(array, index, copyValue ? copyManagedValue(value) : value);
}
}
private static Object independentRepeatedArrayElement(Object array, int index) {
if (Array.getLength(array) < LAZY_ARRAY_REPEAT_THRESHOLD
|| !mayBeRepeatedArray(array)) {
return Array.get(array, index);
}
Map<Object, RepeatedArrayState> stripe = stateStripe(REPEATED_ARRAYS, array);
synchronized (stripe) {
RepeatedArrayState state = stripe.get(array);
Object value = Array.get(array, index);
if (state == null || value != state.template) {
return value;
}
Object copy = copyManagedValue(value);
Array.set(array, index, copy);
return copy;
}
}
private static void markRepeatedArray(Object array) {
int hash = System.identityHashCode(array);
markFilterHash(REPEATED_ARRAY_FILTER, mixRepeatedArrayHash(hash));
markFilterHash(REPEATED_ARRAY_FILTER, mixRepeatedArrayHash(hash ^ 0x9e37_79b9));
}
private static boolean mayBeRepeatedArray(Object array) {
return mayBeInIdentityFilter(REPEATED_ARRAY_FILTER, array);
}
private static int mixRepeatedArrayHash(int hash) {
hash ^= hash >>> 16;
hash *= 0x7feb_352d;
hash ^= hash >>> 15;
return hash;
}
private static void markFilterHash(AtomicLongArray filter, int hash) {
int bitIndex = hash & (REPEATED_ARRAY_FILTER_WORDS * Long.SIZE - 1);
int wordIndex = bitIndex >>> 6;
long bit = 1L << bitIndex;
while (true) {
long previous = filter.get(wordIndex);
if ((previous & bit) != 0
|| filter.compareAndSet(wordIndex, previous, previous | bit)) {
return;
}
}
}
private static boolean hasFilterHash(AtomicLongArray filter, int hash) {
int bitIndex = hash & (REPEATED_ARRAY_FILTER_WORDS * Long.SIZE - 1);
return (filter.get(bitIndex >>> 6) & (1L << bitIndex)) != 0;
}
/** Reads one reference-array element while preserving Rust array value semantics. */
public static Object arrayGetObject(Object array, int index) {
return independentRepeatedArrayElement(array, index);
}
/** Encodes an array into Rust's contiguous, little-endian memory layout. */
public static void encodeArrayMemory(
Object array, byte[] bytes, int offset, int elementSize, String elementCodec) {
int length = Array.getLength(array);
// A differently typed pointer into an aggregate array (for example,
// `&mut T` retyped from `MaybeUninit<T>`) may have a decoded live view
// whose fields were mutated directly by generated bytecode. Preserve
// those mutations before a containing aggregate encodes this array.
new Pointer(
array,
elementSize,
0,
Math.multiplyExact(length, elementSize),
elementCodec)
.flushAllMemoryViews();
for (int index = 0; index < length; index++) {
byte[] element = encodeMemoryValue(Array.get(array, index), elementSize, elementCodec);
System.arraycopy(element, 0, bytes, offset + index * elementSize, elementSize);
if (elementCodec != null) {
moveEncodedReferences(element, bytes);
}
}
}
/** Decodes Rust's contiguous, little-endian memory layout into an array. */
public static void decodeArrayMemory(
byte[] bytes, int offset, Object array, int elementSize, String elementCodec) {
int length = Array.getLength(array);
Class<?> componentType = array.getClass().getComponentType();
for (int index = 0; index < length; index++) {
Object element = decodeMemoryValue(
bytes, offset + index * elementSize, elementSize, elementCodec, componentType);
Array.set(array, index, element);
}
}
private static byte[] encodeMemoryValue(Object value, int size, String codec) {
if (isFatPointerCodec(codec)) {
return encodeFatPointer(value, size, codec);
}
if (codec != null
&& !MANAGED_OBJECT_VIEW_CODEC.equals(codec)
&& !isRawPointerCodec(codec)
&& !isBigIntegerCodec(codec)
&& !F128_CODEC.equals(codec)) {
byte[] encoded = encodeAggregate(codec, value);
if (encoded.length != size) {
throw new IllegalStateException("Rust aggregate codec returned "
+ encoded.length + " bytes, expected " + size);
}
return encoded;
}
byte[] encoded = new byte[size];
if (value == null) {
return encoded;
}
if (isBigIntegerCodec(codec)) {
BigInteger integer = value instanceof I128
? ((I128) value).toBigInteger()
: ((U128) value).toBigInteger();
for (int index = 0; index < size; index++) {
encoded[index] = bigIntegerByte(integer, index);
}
return encoded;
}
if (F128_CODEC.equals(codec)) {
BigInteger bits = ((F128) value).toBits();
for (int index = 0; index < size; index++) {
encoded[index] = bigIntegerByte(bits, index);
}
return encoded;
}
long bits;
if (MANAGED_OBJECT_VIEW_CODEC.equals(codec)) {
bits = managedObjectAddress(value);
} else if (isRawPointerCodec(codec)) {
bits = encodedAddress(rawPointerCarrier(value, codec), encoded, codec);
} else {
bits = incomingBits(value, size);