-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathPointer.java
More file actions
10822 lines (10126 loc) · 442 KB
/
Copy pathPointer.java
File metadata and controls
10822 lines (10126 loc) · 442 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.invoke.CallSite;
import java.lang.invoke.LambdaMetafactory;
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.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
public final class Pointer {
private static Object arrayGet(Object array, int index) {
if (array instanceof byte[]) {
return Byte.valueOf(((byte[]) array)[index]);
}
if (array instanceof boolean[]) {
return Boolean.valueOf(((boolean[]) array)[index]);
}
if (array instanceof short[]) {
return Short.valueOf(((short[]) array)[index]);
}
if (array instanceof char[]) {
return Character.valueOf(((char[]) array)[index]);
}
if (array instanceof int[]) {
return Integer.valueOf(((int[]) array)[index]);
}
if (array instanceof long[]) {
return Long.valueOf(((long[]) array)[index]);
}
if (array instanceof float[]) {
return Float.valueOf(((float[]) array)[index]);
}
if (array instanceof double[]) {
return Double.valueOf(((double[]) array)[index]);
}
return ((Object[]) array)[index];
}
private static void arraySet(Object array, int index, Object value) {
if (array instanceof byte[] && value instanceof Byte) {
((byte[]) array)[index] = ((Byte) value).byteValue();
} else if (array instanceof boolean[] && value instanceof Boolean) {
((boolean[]) array)[index] = ((Boolean) value).booleanValue();
} else if (array instanceof short[]
&& (value instanceof Byte || value instanceof Short)) {
((short[]) array)[index] = ((Number) value).shortValue();
} else if (array instanceof char[] && value instanceof Character) {
((char[]) array)[index] = ((Character) value).charValue();
} else if (array instanceof int[]
&& (value instanceof Byte
|| value instanceof Short
|| value instanceof Integer)) {
((int[]) array)[index] = ((Number) value).intValue();
} else if (array instanceof int[] && value instanceof Character) {
((int[]) array)[index] = ((Character) value).charValue();
} else if (array instanceof long[] && value instanceof Character) {
((long[]) array)[index] = ((Character) value).charValue();
} else if (array instanceof long[]
&& (value instanceof Byte
|| value instanceof Short
|| value instanceof Integer
|| value instanceof Long)) {
((long[]) array)[index] = ((Number) value).longValue();
} else if (array instanceof float[]
&& value instanceof Number
&& !(value instanceof Double)) {
((float[]) array)[index] = ((Number) value).floatValue();
} else if (array instanceof double[] && value instanceof Number) {
((double[]) array)[index] = ((Number) value).doubleValue();
} else if (array instanceof Object[]) {
((Object[]) array)[index] = value;
} else {
Array.set(array, index, value);
}
}
public static void dropRustValue(Object value) {
if (value instanceof RustDrop) {
((RustDrop) value).rustDrop();
} else if (value != null && value.getClass().isArray()) {
Throwable pendingDropFailure = null;
int length = Array.getLength(value);
for (int index = 0; index < length; index++) {
try {
dropRustValue(arrayGet(value, index));
} catch (Throwable failure) {
PanicSupport.abortIfStackOverflow(failure);
if (pendingDropFailure != null) {
Runtime.getRuntime().halt(134);
}
pendingDropFailure = failure;
}
}
if (pendingDropFailure != null) {
rethrowUnchecked(pendingDropFailure);
}
} else if (value instanceof TraitObjectCarrier) {
dropRustValue(((TraitObjectCarrier) value).rustTraitObjectPayload());
} else if (value instanceof Pointer) {
Object pointee = ((Pointer) value).directCellValueOrSelf();
if (pointee != value) {
dropRustValue(pointee);
}
}
}
private static void dropTraitPointer(Object pointer) {
if (pointer == null) {
return;
}
if (pointer instanceof TraitObjectCarrier) {
dropRustValue(((TraitObjectCarrier) pointer).rustTraitObjectPayload());
return;
}
if (pointer instanceof Pointer) {
Object payload = ((Pointer) pointer).getObject();
if (payload != pointer) {
dropRustValue(payload);
}
return;
}
if (isSliceViewCarrierType(pointer.getClass())) {
try {
Object backing = instanceField(pointer.getClass(), "array").get(pointer);
int offset = instanceField(pointer.getClass(), "offset").getInt(pointer);
if (backing instanceof Pointer) {
Object payload = ((Pointer) backing).add(offset).directCellValueOrSelf();
if (payload != backing) {
dropRustValue(payload);
}
return;
}
if (backing != null && backing.getClass().isArray()) {
dropRustValue(arrayGet(backing, offset));
return;
}
} catch (ReflectiveOperationException error) {
throw new IllegalStateException("invalid Rust trait-object pointer", error);
}
}
dropRustValue(pointer);
}
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 STRUCT_TRAIT_TAIL_CARRIER_PREFIX = "@trait:";
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 String UTF8_VIEW_CLASS_NAME = "org.rustlang.runtime.Utf8View";
private static final AtomicLong NEXT_ADDRESS = new AtomicLong(0x1_0000_0000L);
private static final Map<Object, AllocationInfo> ALLOCATIONS = new WeakIdentityMap<>();
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 ConcurrentHashMap<Long, TypedExposedEntry>
TYPED_EXPOSED_ADDRESSES = new ConcurrentHashMap<>();
private static final ReferenceQueue<ExposedTarget> TYPED_EXPOSED_TARGET_QUEUE =
new ReferenceQueue<>();
private static final AtomicInteger TYPED_EXPOSED_OPERATIONS_UNTIL_QUEUE_DRAIN =
new AtomicInteger(16);
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, CodecPlan> CODEC_METHODS =
new ConcurrentHashMap<>();
private static final ThreadLocal<CodecPlanCache> RECENT_CODEC_PLANS =
new ThreadLocal<CodecPlanCache>() {
@Override
protected CodecPlanCache initialValue() {
return new CodecPlanCache();
}
};
private static final ConcurrentHashMap<String, Object> SHARED_CONSTANTS =
new ConcurrentHashMap<>();
private static final Map<Object, Boolean> SHARED_CONSTANT_ARRAYS =
new IdentityHashMap<>();
private static final ConcurrentHashMap<String, MethodHandle> DROP_METHOD_HANDLES =
new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, MethodHandle> DROP_FIELDS_METHOD_HANDLES =
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 ClassLoader RUNTIME_CLASS_LOADER =
Pointer.class.getClassLoader();
private static final ConcurrentHashMap<String, Class<?>> RUNTIME_RESOLVED_CLASSES =
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<ConcurrentHashMap<String, FieldAccess>> FIELD_ACCESSORS =
new ClassValue<ConcurrentHashMap<String, FieldAccess>>() {
@Override
protected ConcurrentHashMap<String, FieldAccess> 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, ConstructorPlan>> PUBLIC_CONSTRUCTORS_BY_ARITY =
new ClassValue<Map<Integer, ConstructorPlan>>() {
@Override
protected Map<Integer, ConstructorPlan> computeValue(Class<?> type) {
Map<Integer, ConstructorPlan> constructors = new HashMap<>();
for (Constructor<?> constructor : type.getConstructors()) {
constructor.setAccessible(true);
try {
constructors.putIfAbsent(
constructor.getParameterCount(),
new ConstructorPlan(constructor));
} catch (IllegalAccessException error) {
throw new IllegalStateException(
"could not access generated Rust value constructor", error);
}
}
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);
ManagedFieldPlan[] fieldPlans = new ManagedFieldPlan[fields.length];
for (int index = 0; index < fields.length; index++) {
try {
fieldPlans[index] = new ManagedFieldPlan(fields[index]);
} catch (IllegalAccessException error) {
throw new IllegalStateException(
"could not access generated Rust value field", error);
}
}
ConstructorPlan constructor = constructorWithArity(type, fields.length);
Class<?>[] parameterTypes = constructor.parameterTypes;
Object[] defaults = new Object[parameterTypes.length];
for (int index = 0; index < parameterTypes.length; index++) {
defaults[index] = defaultValue(parameterTypes[index]);
}
return new ManagedCopyPlan(fieldPlans, 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 ConcurrentHashMap<String, JavaStringViews> JAVA_STRING_VIEWS =
new ConcurrentHashMap<>();
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 long IDENTITY_FILTER_REBUILD_MARKS = 1L << 18;
private static final long MEMORY_VIEW_ORIGIN_FILTER_REBUILD_MARKS = 1L << 20;
private static final class RebuildableIdentityFilter {
private final int wordCount;
private final long rebuildMarks;
private volatile AtomicLongArray primary;
private volatile AtomicLongArray secondary;
private final AtomicLong marks = new AtomicLong();
private RebuildableIdentityFilter() {
this(REPEATED_ARRAY_FILTER_WORDS, IDENTITY_FILTER_REBUILD_MARKS);
}
private RebuildableIdentityFilter(int wordCount, long rebuildMarks) {
this.wordCount = wordCount;
this.rebuildMarks = rebuildMarks;
primary = new AtomicLongArray(wordCount);
}
}
private static final AtomicLongArray REPEATED_ARRAY_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final RebuildableIdentityFilter STRUCTURAL_VIEW_FILTER =
new RebuildableIdentityFilter();
private static final RebuildableIdentityFilter MEMORY_VIEW_FILTER =
new RebuildableIdentityFilter();
private static final RebuildableIdentityFilter MEMORY_VIEW_ORIGIN_FILTER =
new RebuildableIdentityFilter();
private static final AtomicLongArray MEMORY_VIEW_EPOCHS =
new AtomicLongArray(STATE_STRIPE_COUNT);
private static final RebuildableIdentityFilter ENCODED_REFERENCE_FILTER =
new RebuildableIdentityFilter();
private static final RebuildableIdentityFilter ENCODED_POINTER_FILTER =
new RebuildableIdentityFilter(1 << 20, 1L << 22);
private static final AtomicLongArray FIELD_CELL_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final AtomicLongArray SHARED_CONSTANT_ARRAY_FILTER =
new AtomicLongArray(REPEATED_ARRAY_FILTER_WORDS);
private static final Map<Object, Map<Long, StructuralViewState>>[] STRUCTURAL_VIEWS =
createWeakMapStripes();
private static final Map<Object, LongRangeMap<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 Map<Object, LongRangeMap<EncodedPointerState>>[]
ENCODED_POINTERS = createWeakMapStripes();
private static final Map<Object, Long>[] ALLOCATION_BASE_CACHE =
createWeakMapStripes();
private static final Map<Object, Long>[] PUBLISHED_ALLOCATION_BASE_CACHE =
createWeakMapStripes();
private static final ThreadLocal<Integer> MEMORY_VIEW_WRITEBACK_DEPTH =
ThreadLocal.withInitial(() -> 0);
private static final ThreadLocal<MemoryViewAbsenceCache> MEMORY_VIEW_ABSENCE =
ThreadLocal.withInitial(MemoryViewAbsenceCache::new);
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 Object[] EMPTY_UNION_OBJECT_STORAGE = new Object[0];
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) {
return stripes[stateStripeIndex(key)];
}
private static int stateStripeIndex(Object key) {
int hash = key == null ? 0 : System.identityHashCode(key);
hash ^= hash >>> 16;
return hash & (STATE_STRIPE_COUNT - 1);
}
private static long memoryViewEpoch(Object allocation) {
return MEMORY_VIEW_EPOCHS.get(stateStripeIndex(allocation));
}
private static void advanceMemoryViewEpoch(Object allocation) {
MEMORY_VIEW_EPOCHS.incrementAndGet(stateStripeIndex(allocation));
}
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);
}
}
maybeRebuildEncodedReferenceFilter();
}
private static void transferEncodedReferences(Object sourceOwner, Object targetOwner) {
sourceOwner = encodedReferenceOwner(sourceOwner);
targetOwner = encodedReferenceOwner(targetOwner);
if (sourceOwner == null || targetOwner == null || sourceOwner == targetOwner) {
return;
}
Object referenced;
Object[] referencedSet = null;
if (!mayBeInIdentityFilter(ENCODED_REFERENCE_FILTER, sourceOwner)) {
return;
}
Map<Object, Object> sourceStripe =
stateStripe(ENCODED_REFERENCES, sourceOwner);
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)) {
Map<Object, Object> stripe =
stateStripe(ENCODED_REFERENCES, owner);
synchronized (stripe) {
stripe.remove(owner);
}
}
discardEncodedPointers(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 JavaStringViews {
private final byte[] bytes;
private volatile Object slice;
private volatile Object utf8;
private JavaStringViews(String value) {
bytes = value.getBytes(StandardCharsets.UTF_8);
}
}
/**
* Small sorted map for byte offsets. Pointer provenance and decoded-view
* ranges normally contain only a handful of entries per allocation, so a
* primitive array avoids TreeMap nodes, boxed Long keys, and entry copies.
*/
private static final class LongRangeMap<V> {
private long firstKey;
private long secondKey;
private Object firstValue;
private Object secondValue;
private long[] keys;
private Object[] values;
private int size;
private int find(long key) {
if (keys == null) {
if (size == 0 || key < firstKey) {
return -1;
}
if (key == firstKey) {
return 0;
}
if (size == 1 || key < secondKey) {
return -2;
}
return key == secondKey ? 1 : -3;
}
int low = 0;
int high = size - 1;
while (low <= high) {
int middle = (low + high) >>> 1;
long candidate = keys[middle];
if (candidate < key) {
low = middle + 1;
} else if (candidate > key) {
high = middle - 1;
} else {
return middle;
}
}
return -low - 1;
}
private void promote() {
keys = new long[4];
values = new Object[4];
keys[0] = firstKey;
keys[1] = secondKey;
values[0] = firstValue;
values[1] = secondValue;
firstValue = null;
secondValue = null;
}
private void ensureCapacity() {
if (keys == null) {
promote();
return;
}
if (size < keys.length) {
return;
}
int capacity = keys.length << 1;
keys = Arrays.copyOf(keys, capacity);
values = Arrays.copyOf(values, capacity);
}
@SuppressWarnings("unchecked")
private V valueAt(int index) {
if (keys == null) {
return (V) (index == 0 ? firstValue : secondValue);
}
return (V) values[index];
}
private long keyAt(int index) {
if (keys == null) {
return index == 0 ? firstKey : secondKey;
}
return keys[index];
}
private V get(long key) {
int index = find(key);
return index < 0 ? null : valueAt(index);
}
private void put(long key, V value) {
int index = find(key);
if (index >= 0) {
if (keys == null) {
if (index == 0) {
firstValue = value;
} else {
secondValue = value;
}
} else {
values[index] = value;
}
return;
}
index = -index - 1;
if (keys == null && size < 2) {
if (size == 0) {
firstKey = key;
firstValue = value;
} else if (index == 0) {
secondKey = firstKey;
secondValue = firstValue;
firstKey = key;
firstValue = value;
} else {
secondKey = key;
secondValue = value;
}
size++;
return;
}
ensureCapacity();
int moved = size - index;
if (moved > 0) {
System.arraycopy(keys, index, keys, index + 1, moved);
System.arraycopy(values, index, values, index + 1, moved);
}
keys[index] = key;
values[index] = value;
size++;
}
private V remove(long key) {
int index = find(key);
return index < 0 ? null : removeAt(index);
}
private V removeAt(int index) {
V previous = valueAt(index);
if (keys == null) {
if (index == 0 && size == 2) {
firstKey = secondKey;
firstValue = secondValue;
}
if (--size < 2) {
secondValue = null;
}
if (size == 0) {
firstValue = null;
}
return previous;
}
int moved = size - index - 1;
if (moved > 0) {
System.arraycopy(keys, index + 1, keys, index, moved);
System.arraycopy(values, index + 1, values, index, moved);
}
values[--size] = null;
return previous;
}
private boolean containsKey(long key) {
return find(key) >= 0;
}
private int floorIndex(long key) {
int index = find(key);
return index >= 0 ? index : -index - 2;
}
private int ceilingIndex(long key) {
int index = find(key);
return index >= 0 ? index : -index - 1;
}
private int size() {
return size;
}
private boolean isEmpty() {
return size == 0;
}
}
private static final class EncodedPointerState {
private final int size;
private final String codec;
private final ExposedTarget target;
private EncodedPointerState(int size, String codec, ExposedTarget target) {
this.size = size;
this.codec = codec;
this.target = target;
}
}
private static final class EncodedPointerCopy {
private final long offset;
private final EncodedPointerState state;
private EncodedPointerCopy(long offset, EncodedPointerState state) {
this.offset = offset;
this.state = state;
}
}
private static void rememberEncodedPointer(
Object owner,
long offset,
int size,
String codec,
Pointer pointer) {
rememberEncodedPointer(
owner,
offset,
size,
codec,
pointer == null ? null : pointer.exposedTarget());
}
private static void rememberEncodedPointer(
Object owner,
long offset,
int size,
String codec,
ExposedTarget target) {
if (owner == null || target == null || size <= 0 || codec == null) {
return;
}
markIdentityFilter(ENCODED_POINTER_FILTER, owner);
Map<Object, LongRangeMap<EncodedPointerState>> stripe =
stateStripe(ENCODED_POINTERS, owner);
synchronized (stripe) {
LongRangeMap<EncodedPointerState> pointers = stripe.get(owner);
if (pointers == null) {
pointers = new LongRangeMap<>();
stripe.put(owner, pointers);
}
removeOverlappingEncodedPointers(pointers, offset, size);
pointers.put(offset, new EncodedPointerState(size, codec, target));
}
maybeRebuildEncodedPointerFilter();
}
private static Pointer encodedPointer(
Object owner, long offset, int size, String codec, long address) {
if (owner != null
&& codec != null
&& mayBeInIdentityFilter(ENCODED_POINTER_FILTER, owner)) {
Map<Object, LongRangeMap<EncodedPointerState>> stripe =
stateStripe(ENCODED_POINTERS, owner);
EncodedPointerState state;
synchronized (stripe) {
LongRangeMap<EncodedPointerState> pointers = stripe.get(owner);
state = pointers == null ? null : pointers.get(offset);
}
if (state != null
&& state.size == size
&& codec.equals(state.codec)) {
Pointer pointer = pointerFromExposedTarget(state.target);
if (pointer.numericAddress() == address) {
return pointer;
}
}
}
return null;
}
private static void transferEncodedPointers(
Object sourceOwner,
long sourceOffset,
Object targetOwner,
long targetOffset,
int length,
boolean move) {
if (sourceOwner == null
|| targetOwner == null
|| length <= 0
|| !mayBeInIdentityFilter(ENCODED_POINTER_FILTER, sourceOwner)) {
return;
}
Map<Object, LongRangeMap<EncodedPointerState>> sourceStripe =
stateStripe(ENCODED_POINTERS, sourceOwner);
java.util.ArrayList<EncodedPointerCopy> copied = null;
synchronized (sourceStripe) {
LongRangeMap<EncodedPointerState> pointers = sourceStripe.get(sourceOwner);
if (pointers == null) {
return;
}
long sourceEnd = Math.addExact(sourceOffset, (long) length);
for (int index = pointers.ceilingIndex(sourceOffset);
index < pointers.size() && pointers.keyAt(index) < sourceEnd;
index++) {
long entryOffset = pointers.keyAt(index);
EncodedPointerState state = pointers.valueAt(index);
if (Math.addExact(entryOffset, (long) state.size) <= sourceEnd) {
if (copied == null) {
copied = new java.util.ArrayList<>();
}
copied.add(new EncodedPointerCopy(entryOffset, state));
}
}
if (move) {
removeOverlappingEncodedPointers(pointers, sourceOffset, length);
if (pointers.isEmpty()) {
sourceStripe.remove(sourceOwner);
}
}
}
if (copied == null) {
return;
}
markIdentityFilter(ENCODED_POINTER_FILTER, targetOwner);
Map<Object, LongRangeMap<EncodedPointerState>> targetStripe =
stateStripe(ENCODED_POINTERS, targetOwner);
synchronized (targetStripe) {
LongRangeMap<EncodedPointerState> pointers = targetStripe.get(targetOwner);
if (pointers == null) {
pointers = new LongRangeMap<>();
targetStripe.put(targetOwner, pointers);
}
removeOverlappingEncodedPointers(pointers, targetOffset, length);
for (int index = 0; index < copied.size(); index++) {
EncodedPointerCopy entry = copied.get(index);
pointers.put(
Math.addExact(
targetOffset,
Math.subtractExact(entry.offset, sourceOffset)),
entry.state);
}
}
}
private static void removeOverlappingEncodedPointers(
LongRangeMap<EncodedPointerState> pointers, long offset, int size) {
long end = Math.addExact(offset, (long) size);
int index = pointers.floorIndex(offset);
if (index < 0) {
index = pointers.ceilingIndex(offset);
}
while (index < pointers.size() && pointers.keyAt(index) < end) {
long entryOffset = pointers.keyAt(index);
EncodedPointerState state = pointers.valueAt(index);
if (offset < Math.addExact(entryOffset, (long) state.size)
&& entryOffset < end) {
pointers.removeAt(index);
} else {
index++;
}
}
}
private static void discardEncodedPointers(Object owner) {
if (owner == null || !mayBeInIdentityFilter(ENCODED_POINTER_FILTER, owner)) {
return;
}
Map<Object, LongRangeMap<EncodedPointerState>> stripe =
stateStripe(ENCODED_POINTERS, owner);
synchronized (stripe) {
stripe.remove(owner);
}
}
private static void discardEncodedPointers(Object owner, long offset, int size) {
if (owner == null
|| size <= 0
|| !mayBeInIdentityFilter(ENCODED_POINTER_FILTER, owner)) {
return;
}
Map<Object, LongRangeMap<EncodedPointerState>> stripe =
stateStripe(ENCODED_POINTERS, owner);
synchronized (stripe) {
LongRangeMap<EncodedPointerState> pointers = stripe.get(owner);
if (pointers == null) {
return;
}
removeOverlappingEncodedPointers(pointers, offset, size);
if (pointers.isEmpty()) {
stripe.remove(owner);
}
}
}