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
|
#!/usr/bin/python3
#
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Generate java test files for 712-varhandle-invocations
"""
from enum import Enum
from pathlib import Path
from random import Random
from string import Template
import io
import re
import sys
class JavaType(object):
def __init__(self, name, examples, supports_bitwise=False, supports_numeric=False):
self.name=name
self.examples=examples
self.supports_bitwise=supports_bitwise
self.supports_numeric=supports_numeric
def is_value_type(self):
return False
def __repr__(self):
return self.name
def __str__(self):
return self.name
class ValueType(JavaType):
def __init__(self, name, boxed_type, examples, ordinal=-1, width=-1, supports_bitwise=True, supports_numeric=True):
JavaType.__init__(self, name, examples, supports_bitwise, supports_numeric)
self.ordinal=ordinal
self.width=width
self.boxed_type=boxed_type
def boxing_method(self):
return self.boxed_type + ".valueOf"
def unboxing_method(self):
return self.name + "Value"
def is_value_type(self):
return True
def __eq__(self, other):
return self.ordinal == other.ordinal
def __hash__(self):
return self.ordinal
def __le__(self, other):
return self.ordinal < other.ordinal
def __repr__(self):
return self.name
def __str__(self):
return self.name
BOOLEAN_TYPE = ValueType("boolean", "Boolean", [ "true", "false" ], ordinal = 0, width = 1, supports_numeric=False)
BYTE_TYPE=ValueType("byte", "Byte", [ "(byte) -128", "(byte) -61", "(byte) 7", "(byte) 127", "(byte) 33" ], ordinal=1, width=1)
SHORT_TYPE=ValueType("short", "Short", [ "(short) -32768", "(short) -384", "(short) 32767", "(short) 0xaa55" ], ordinal=2, width=2)
CHAR_TYPE=ValueType("char", "Character", [ r"'A'", r"'#'", r"'$'", r"'Z'", r"'t'", r"'c'" ], ordinal=3, width=2)
INT_TYPE=ValueType("int", "Integer", [ "-0x01234567", "0x7f6e5d4c", "0x12345678", "0x10215220", "42" ], ordinal=4, width=4)
LONG_TYPE=ValueType("long", "Long", [ "-0x0123456789abcdefl", "0x789abcdef0123456l", "0xfedcba9876543210l" ], ordinal=5, width=8)
FLOAT_TYPE=ValueType("float", "Float", [ "-7.77e23f", "1.234e-17f", "3.40e36f", "-8.888e3f", "4.442e11f" ], ordinal=6, width=4, supports_bitwise=False)
DOUBLE_TYPE=ValueType("double", "Double", [ "-1.0e-200", "1.11e200", "3.141", "1.1111", "6.022e23", "6.626e-34" ], ordinal=7, width=4, supports_bitwise=False)
VALUE_TYPES = { BOOLEAN_TYPE, BYTE_TYPE, SHORT_TYPE, CHAR_TYPE, INT_TYPE, LONG_TYPE, FLOAT_TYPE, DOUBLE_TYPE }
WIDENING_CONVERSIONS = {
BOOLEAN_TYPE : set(),
BYTE_TYPE : { SHORT_TYPE, INT_TYPE, LONG_TYPE, FLOAT_TYPE, DOUBLE_TYPE },
SHORT_TYPE : { INT_TYPE, LONG_TYPE, FLOAT_TYPE, DOUBLE_TYPE },
CHAR_TYPE : { INT_TYPE, LONG_TYPE, FLOAT_TYPE, DOUBLE_TYPE },
INT_TYPE : { LONG_TYPE, FLOAT_TYPE, DOUBLE_TYPE },
LONG_TYPE : { FLOAT_TYPE, DOUBLE_TYPE },
FLOAT_TYPE : { DOUBLE_TYPE },
DOUBLE_TYPE : set()
}
def types_that_widen_to(var_type):
types_that_widen = { var_type }
for src_type in WIDENING_CONVERSIONS:
if var_type in WIDENING_CONVERSIONS[src_type]:
types_that_widen.add(src_type)
return types_that_widen
class VarHandleKind(object):
ALL_SUPPORTED_TYPES = VALUE_TYPES
VIEW_SUPPORTED_TYPES = list(filter(lambda x : x.width >= 2, ALL_SUPPORTED_TYPES))
def __init__(self, name, imports=[], declarations=[], lookup='', coordinates=[], get_value='', may_throw_read_only=False):
self.name = name
self.imports = imports
self.declarations = declarations
self.lookup = lookup
self.coordinates = coordinates
self.get_value_ = get_value
self.may_throw_read_only = may_throw_read_only
def get_name(self):
return self.name
def get_coordinates(self):
return self.coordinates
def get_field_declarations(self, dictionary):
return list(map(lambda d: Template(d).safe_substitute(dictionary), self.declarations))
def get_imports(self):
return self.imports
def get_lookup(self, dictionary):
return Template(self.lookup).safe_substitute(dictionary)
def get_supported_types(self):
return VarHandleKind.VIEW_SUPPORTED_TYPES if self.is_view() else VarHandleKind.ALL_SUPPORTED_TYPES
def is_view(self):
return "View" in self.name
def get_value(self, dictionary):
return Template(self.get_value_).safe_substitute(dictionary)
FIELD_VAR_HANDLE = VarHandleKind("Field",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle'
],
[
"${var_type} field = ${initial_value}"
],
'MethodHandles.lookup().findVarHandle(${test_class}.class, "field", ${var_type}.class)',
[
'this'
],
'field',
may_throw_read_only = False)
FINAL_FIELD_VAR_HANDLE = VarHandleKind("FinalField",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle'
],
[
"${var_type} field = ${initial_value}"
],
'MethodHandles.lookup().findVarHandle(${test_class}.class, "field", ${var_type}.class)',
[
'this'
],
'field',
may_throw_read_only = False)
STATIC_FIELD_VAR_HANDLE = VarHandleKind("StaticField",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle'
],
[
"static ${var_type} field = ${initial_value}"
],
'MethodHandles.lookup().findStaticVarHandle(${test_class}.class, "field", ${var_type}.class)',
[],
'field',
may_throw_read_only = False)
STATIC_FINAL_FIELD_VAR_HANDLE = VarHandleKind("StaticFinalField",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle'
],
[
"static ${var_type} field = ${initial_value}"
],
'MethodHandles.lookup().findStaticVarHandle(${test_class}.class, "field", ${var_type}.class)',
[],
'field',
may_throw_read_only = False)
ARRAY_ELEMENT_VAR_HANDLE = VarHandleKind("ArrayElement",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle'
],
[
"${var_type}[] array = new ${var_type}[11]",
"int index = 3",
"{ array[index] = ${initial_value}; }"
],
'MethodHandles.arrayElementVarHandle(${var_type}[].class)',
[ 'array', 'index'],
'array[index]',
may_throw_read_only = False)
BYTE_ARRAY_LE_VIEW_VAR_HANDLE = VarHandleKind("ByteArrayViewLE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteOrder'
],
[
"byte[] array = new byte[27]",
"int index = 8",
"{"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(array, index);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(array, index, ${initial_value}, ByteOrder.LITTLE_ENDIAN);"
"}"
],
'MethodHandles.byteArrayViewVarHandle(${var_type}[].class, ByteOrder.LITTLE_ENDIAN)',
[
'array',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(array, index, ByteOrder.LITTLE_ENDIAN)',
may_throw_read_only = False)
BYTE_ARRAY_BE_VIEW_VAR_HANDLE = VarHandleKind("ByteArrayViewBE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteOrder'
],
[
"byte[] array = new byte[27]",
"int index = 8",
"{"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(array, index);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(array, index, ${initial_value}, ByteOrder.BIG_ENDIAN);"
"}"
],
'MethodHandles.byteArrayViewVarHandle(${var_type}[].class, ByteOrder.BIG_ENDIAN)',
[
'array',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(array, index, ByteOrder.BIG_ENDIAN)',
may_throw_read_only = False)
DIRECT_BYTE_BUFFER_LE_VIEW_VAR_HANDLE = VarHandleKind("DirectByteBufferViewLE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteBuffer',
'java.nio.ByteOrder'
],
[
"ByteBuffer bb = ByteBuffer.allocateDirect(31)",
"int index = 8",
"{"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(bb, index);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(bb, index, ${initial_value}, ByteOrder.LITTLE_ENDIAN);"
"}"
],
'MethodHandles.byteBufferViewVarHandle(${var_type}[].class, ByteOrder.LITTLE_ENDIAN)',
[
'bb',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(bb, index, ByteOrder.LITTLE_ENDIAN)',
may_throw_read_only = False)
DIRECT_BYTE_BUFFER_BE_VIEW_VAR_HANDLE = VarHandleKind("DirectByteBufferViewBE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteBuffer',
'java.nio.ByteOrder'
],
[
"ByteBuffer bb = ByteBuffer.allocateDirect(31)",
"int index = 8",
"{"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(bb, index);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(bb, index, ${initial_value}, ByteOrder.BIG_ENDIAN);"
"}"
],
'MethodHandles.byteBufferViewVarHandle(${var_type}[].class, ByteOrder.BIG_ENDIAN)',
[
'bb',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(bb, index, ByteOrder.BIG_ENDIAN)',
may_throw_read_only = False)
HEAP_BYTE_BUFFER_LE_VIEW_VAR_HANDLE = VarHandleKind("HeapByteBufferViewLE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteBuffer',
'java.nio.ByteOrder'
],
[
"byte[] array = new byte[36]",
"int offset = 8",
"ByteBuffer bb = ByteBuffer.wrap(array, offset, array.length - offset)",
"int index = 8",
"{"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(bb, index);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(bb, index, ${initial_value}, ByteOrder.LITTLE_ENDIAN);"
"}"
],
'MethodHandles.byteBufferViewVarHandle(${var_type}[].class, ByteOrder.LITTLE_ENDIAN)',
[
'bb',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(bb, index, ByteOrder.LITTLE_ENDIAN)',
may_throw_read_only = False)
HEAP_BYTE_BUFFER_BE_VIEW_VAR_HANDLE = VarHandleKind("HeapByteBufferViewBE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteBuffer',
'java.nio.ByteOrder'
],
[
"byte[] array = new byte[47]",
"int offset = 8",
"ByteBuffer bb = ByteBuffer.wrap(array, offset, array.length - offset)",
"int index = 8",
"{"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(bb, index);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(bb, index, ${initial_value}, ByteOrder.BIG_ENDIAN);"
"}"
],
'MethodHandles.byteBufferViewVarHandle(${var_type}[].class, ByteOrder.BIG_ENDIAN)',
[
'bb',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(bb, index, ByteOrder.BIG_ENDIAN)',
may_throw_read_only = False)
HEAP_BYTE_BUFFER_RO_LE_VIEW_VAR_HANDLE = VarHandleKind("HeapByteBufferReadOnlyViewLE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteBuffer',
'java.nio.ByteOrder',
'java.nio.ReadOnlyBufferException'
],
[
"byte[] array = new byte[43]",
"int index = 8",
"ByteBuffer bb",
"{"
" bb = ByteBuffer.wrap(array).asReadOnlyBuffer();"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(bb, index);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(array, index, ${initial_value}, ByteOrder.LITTLE_ENDIAN);"
" bb = bb.asReadOnlyBuffer();"
"}"
],
'MethodHandles.byteBufferViewVarHandle(${var_type}[].class, ByteOrder.LITTLE_ENDIAN)',
[
'bb',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(bb, index, ByteOrder.LITTLE_ENDIAN)',
may_throw_read_only = True)
HEAP_BYTE_BUFFER_RO_BE_VIEW_VAR_HANDLE = VarHandleKind("HeapByteBufferReadOnlyViewBE",
[
'java.lang.invoke.MethodHandles',
'java.lang.invoke.VarHandle',
'java.nio.ByteBuffer',
'java.nio.ByteOrder',
'java.nio.ReadOnlyBufferException'
],
[
"byte[] array = new byte[29]",
"int index",
"ByteBuffer bb",
"{"
" bb = ByteBuffer.wrap(array);"
" index = VarHandleUnitTestHelpers.alignedOffset_${var_type}(bb, 8);"
" VarHandleUnitTestHelpers.setBytesAs_${var_type}(array, index, ${initial_value}, ByteOrder.BIG_ENDIAN);"
" bb = bb.asReadOnlyBuffer();"
"}"
],
'MethodHandles.byteBufferViewVarHandle(${var_type}[].class, ByteOrder.BIG_ENDIAN)',
[
'bb',
'index'
],
'VarHandleUnitTestHelpers.getBytesAs_${var_type}(bb, index, ByteOrder.BIG_ENDIAN)',
may_throw_read_only = True)
ALL_FIELD_VAR_HANDLE_KINDS = [
FIELD_VAR_HANDLE,
FINAL_FIELD_VAR_HANDLE,
STATIC_FIELD_VAR_HANDLE,
STATIC_FINAL_FIELD_VAR_HANDLE
]
ALL_BYTE_VIEW_VAR_HANDLE_KINDS = [
BYTE_ARRAY_LE_VIEW_VAR_HANDLE,
BYTE_ARRAY_BE_VIEW_VAR_HANDLE,
DIRECT_BYTE_BUFFER_LE_VIEW_VAR_HANDLE,
DIRECT_BYTE_BUFFER_BE_VIEW_VAR_HANDLE,
HEAP_BYTE_BUFFER_LE_VIEW_VAR_HANDLE,
HEAP_BYTE_BUFFER_BE_VIEW_VAR_HANDLE,
HEAP_BYTE_BUFFER_RO_LE_VIEW_VAR_HANDLE,
HEAP_BYTE_BUFFER_RO_BE_VIEW_VAR_HANDLE
]
ALL_VAR_HANDLE_KINDS = ALL_FIELD_VAR_HANDLE_KINDS + [ ARRAY_ELEMENT_VAR_HANDLE ] + ALL_BYTE_VIEW_VAR_HANDLE_KINDS
class AccessModeForm(Enum):
GET = 0
SET = 1
STRONG_COMPARE_AND_SET = 2
WEAK_COMPARE_AND_SET = 3
COMPARE_AND_EXCHANGE = 4
GET_AND_SET = 5
GET_AND_UPDATE_BITWISE = 6
GET_AND_UPDATE_NUMERIC = 7
class VarHandleAccessor:
def __init__(self, method_name):
self.method_name = method_name
self.access_mode = self.get_access_mode(method_name)
self.access_mode_form = self.get_access_mode_form(method_name)
def get_return_type(self, var_type):
if self.access_mode_form == AccessModeForm.SET:
return None
elif (self.access_mode_form == AccessModeForm.STRONG_COMPARE_AND_SET or
self.access_mode_form == AccessModeForm.WEAK_COMPARE_AND_SET):
return BOOLEAN_TYPE
else:
return var_type
def get_number_of_var_type_arguments(self):
if self.access_mode_form == AccessModeForm.GET:
return 0
elif (self.access_mode_form == AccessModeForm.SET or
self.access_mode_form == AccessModeForm.GET_AND_SET or
self.access_mode_form == AccessModeForm.GET_AND_UPDATE_BITWISE or
self.access_mode_form == AccessModeForm.GET_AND_UPDATE_NUMERIC):
return 1
elif (self.access_mode_form == AccessModeForm.STRONG_COMPARE_AND_SET or
self.access_mode_form == AccessModeForm.WEAK_COMPARE_AND_SET or
self.access_mode_form == AccessModeForm.COMPARE_AND_EXCHANGE):
return 2
else:
raise ValueError(self.access_mode_form)
def is_read_only(self):
return self.access_mode_form == AccessModeForm.GET
def get_java_bitwise_operator(self):
if "BitwiseAnd" in self.method_name:
return "&"
elif "BitwiseOr" in self.method_name:
return "|"
elif "BitwiseXor" in self.method_name:
return "^"
raise ValueError(self.method_name)
def get_java_numeric_operator(self):
if "Add" in self.method_name:
return "+"
raise ValueError(self.method_name)
@staticmethod
def get_access_mode(accessor_method):
"""Converts an access method name to AccessMode value. For example, getAndSet becomes GET_AND_SET"""
return re.sub('([A-Z])', r'_\1', accessor_method).upper()
@staticmethod
def get_access_mode_form(accessor_method):
prefix_mode_list = [
('getAndAdd', AccessModeForm.GET_AND_UPDATE_NUMERIC),
('getAndBitwise', AccessModeForm.GET_AND_UPDATE_BITWISE),
('getAndSet', AccessModeForm.GET_AND_SET),
('get', AccessModeForm.GET),
('set', AccessModeForm.SET),
('compareAndSet', AccessModeForm.STRONG_COMPARE_AND_SET),
('weakCompareAndSet', AccessModeForm.WEAK_COMPARE_AND_SET),
('compareAndExchange', AccessModeForm.COMPARE_AND_EXCHANGE)]
for prefix, mode in prefix_mode_list:
if accessor_method.startswith(prefix):
return mode
raise ValueError(accessor_method)
VAR_HANDLE_ACCESSORS = [
VarHandleAccessor('get'),
VarHandleAccessor('set'),
VarHandleAccessor('getVolatile'),
VarHandleAccessor('setVolatile'),
VarHandleAccessor('getAcquire'),
VarHandleAccessor('setRelease'),
VarHandleAccessor('getOpaque'),
VarHandleAccessor('setOpaque'),
VarHandleAccessor('compareAndSet'),
VarHandleAccessor('compareAndExchange'),
VarHandleAccessor('compareAndExchangeAcquire'),
VarHandleAccessor('compareAndExchangeRelease'),
VarHandleAccessor('weakCompareAndSetPlain'),
VarHandleAccessor('weakCompareAndSet'),
VarHandleAccessor('weakCompareAndSetAcquire'),
VarHandleAccessor('weakCompareAndSetRelease'),
VarHandleAccessor('getAndSet'),
VarHandleAccessor('getAndSetAcquire'),
VarHandleAccessor('getAndSetRelease'),
VarHandleAccessor('getAndAdd'),
VarHandleAccessor('getAndAddAcquire'),
VarHandleAccessor('getAndAddRelease'),
VarHandleAccessor('getAndBitwiseOr'),
VarHandleAccessor('getAndBitwiseOrRelease'),
VarHandleAccessor('getAndBitwiseOrAcquire'),
VarHandleAccessor('getAndBitwiseAnd'),
VarHandleAccessor('getAndBitwiseAndRelease'),
VarHandleAccessor('getAndBitwiseAndAcquire'),
VarHandleAccessor('getAndBitwiseXor'),
VarHandleAccessor('getAndBitwiseXorRelease'),
VarHandleAccessor('getAndBitwiseXorAcquire')
]
# Pseudo-RNG used for arbitrary decisions
RANDOM = Random(0)
BANNER = '// This file is generated by util-src/generate_java.py do not directly modify!'
# List of generated test classes
GENERATED_TEST_CLASSES = []
def java_file_for_class(class_name):
return class_name + ".java"
def capitalize_first(word):
return word[0].upper() + word[1:]
def indent_code(code):
"""Applies rudimentary indentation to code"""
return code
def build_template_dictionary(test_class, var_handle_kind, accessor, var_type):
initial_value = RANDOM.choice(var_type.examples)
updated_value = RANDOM.choice(list(filter(lambda v : v != initial_value, var_type.examples)))
coordinates = ", ".join(var_handle_kind.get_coordinates())
if accessor.get_number_of_var_type_arguments() != 0 and coordinates != "":
coordinates += ", "
dictionary = {
'accessor_method' : accessor.method_name,
'access_mode' : accessor.access_mode,
'banner' : BANNER,
'coordinates' : coordinates,
'initial_value' : initial_value,
'test_class' : test_class,
'updated_value' : updated_value,
'var_type' : var_type,
}
dictionary['imports'] = ";\n".join(list(map(lambda x: "import " + x, var_handle_kind.get_imports())))
dictionary['lookup'] = var_handle_kind.get_lookup(dictionary)
dictionary['field_declarations'] = ";\n".join(var_handle_kind.get_field_declarations(dictionary))
dictionary['read_value'] = var_handle_kind.get_value(dictionary)
return dictionary
def emit_accessor_test(var_handle_kind, accessor, var_type, output_path):
test_class = var_handle_kind.get_name() + capitalize_first(accessor.method_name) + capitalize_first(var_type.name)
GENERATED_TEST_CLASSES.append(test_class)
src_file_path = output_path / java_file_for_class(test_class)
expansions = build_template_dictionary(test_class, var_handle_kind, accessor, var_type)
# Compute test operation
if accessor.access_mode_form == AccessModeForm.GET:
test_template = Template("""
${var_type} value = (${var_type}) vh.${accessor_method}(${coordinates});
assertEquals(${initial_value}, value);""")
elif accessor.access_mode_form == AccessModeForm.SET:
test_template = Template("""
vh.${accessor_method}(${coordinates}${updated_value});
assertEquals(${updated_value}, ${read_value});""")
elif accessor.access_mode_form == AccessModeForm.STRONG_COMPARE_AND_SET:
test_template = Template("""
assertEquals(${initial_value}, ${read_value});
// Test an update that should succeed.
boolean applied = (boolean) vh.${accessor_method}(${coordinates}${initial_value}, ${updated_value});
assertEquals(${updated_value}, ${read_value});
assertTrue(applied);
// Test an update that should fail.
applied = (boolean) vh.${accessor_method}(${coordinates}${initial_value}, ${initial_value});
assertFalse(applied);
assertEquals(${updated_value}, ${read_value});""")
elif accessor.access_mode_form == AccessModeForm.WEAK_COMPARE_AND_SET:
test_template = Template("""
assertEquals(${initial_value}, ${read_value});
// Test an update that should succeed.
int attempts = 10000;
boolean applied;
do {
applied = (boolean) vh.${accessor_method}(${coordinates}${initial_value}, ${updated_value});
} while (applied == false && attempts-- > 0);
assertEquals(${updated_value}, ${read_value});
assertTrue(attempts > 0);
// Test an update that should fail.
applied = (boolean) vh.${accessor_method}(${coordinates}${initial_value}, ${initial_value});
assertFalse(applied);
assertEquals(${updated_value}, ${read_value});""")
elif accessor.access_mode_form == AccessModeForm.COMPARE_AND_EXCHANGE:
test_template = Template("""
// This update should succeed.
${var_type} witness_value = (${var_type}) vh.${accessor_method}(${coordinates}${initial_value}, ${updated_value});
assertEquals(${initial_value}, witness_value);
assertEquals(${updated_value}, ${read_value});
// This update should fail.
witness_value = (${var_type}) vh.${accessor_method}(${coordinates}${initial_value}, ${initial_value});
assertEquals(${updated_value}, witness_value);
assertEquals(${updated_value}, ${read_value});""")
elif accessor.access_mode_form == AccessModeForm.GET_AND_SET:
test_template = Template("""
${var_type} old_value = (${var_type}) vh.${accessor_method}(${coordinates}${updated_value});
assertEquals(${initial_value}, old_value);
assertEquals(${updated_value}, ${read_value});""")
elif accessor.access_mode_form == AccessModeForm.GET_AND_UPDATE_BITWISE:
if var_type.supports_bitwise == True:
expansions['binop'] = accessor.get_java_bitwise_operator()
test_template = Template("""
${var_type} old_value = (${var_type}) vh.${accessor_method}(${coordinates}${updated_value});
assertEquals(${initial_value}, old_value);
assertEquals(${initial_value} ${binop} ${updated_value}, ${read_value});""")
else:
test_template = Template("""
vh.${accessor_method}(${coordinates}${initial_value}, ${updated_value});
failUnreachable();""")
elif accessor.access_mode_form == AccessModeForm.GET_AND_UPDATE_NUMERIC:
if var_type.supports_numeric == True:
expansions['binop'] = accessor.get_java_numeric_operator()
test_template = Template("""
${var_type} old_value = (${var_type}) vh.${accessor_method}(${coordinates}${updated_value});
assertEquals(${initial_value}, old_value);
${var_type} expected_value = (${var_type}) (${initial_value} ${binop} ${updated_value});
assertEquals(expected_value, ${read_value});""")
else:
test_template = Template("""
vh.${accessor_method}(${coordinates}${initial_value}, ${updated_value});
failUnreachable();""")
else:
raise ValueError(accessor.access_mode_form)
if var_handle_kind.may_throw_read_only and not accessor.is_read_only():
# ByteBufferViews can be read-only and dynamically raise ReadOnlyBufferException.
expansions['try_statement'] = "try {"
expansions['catch_statement'] = "failUnreachable();\n} catch (ReadOnlyBufferException ex) {}"
else:
expansions['try_statement'] = ""
expansions['catch_statement'] = ""
expansions['test_body'] = test_template.safe_substitute(expansions)
s = Template("""${banner}
${imports};
class ${test_class} extends VarHandleUnitTest {
${field_declarations};
static final VarHandle vh;
static {
try {
vh = ${lookup};
} catch (Exception e) {
throw new RuntimeException("Unexpected initialization exception", e);
}
}
@Override
public void doTest() throws Exception {
if (!vh.isAccessModeSupported(VarHandle.AccessMode.${access_mode})) {
try {
${test_body}
failUnreachable();
} catch (UnsupportedOperationException ex) {}
} else {
${try_statement}
${test_body}
${catch_statement}
}
}
public static void main(String[] args) {
new ${test_class}().run();
}
}
""").safe_substitute(expansions)
with src_file_path.open("w") as src_file:
print(s, file=src_file)
def emit_value_type_accessor_tests(output_path):
for var_handle_kind in ALL_VAR_HANDLE_KINDS:
for accessor in VAR_HANDLE_ACCESSORS:
for var_type in var_handle_kind.get_supported_types():
emit_accessor_test(var_handle_kind, accessor, var_type, output_path)
def emit_reference_accessor_tests(output_path):
ref_type = JavaType("Widget", [ "Widget.ONE", "Widget.TWO", "null" ])
for var_handle_kind in ALL_VAR_HANDLE_KINDS:
if var_handle_kind.is_view():
# Views as reference type arrays are not supported. They
# fail instantiation. This is tested in 710-varhandle-creation.
continue
for accessor in VAR_HANDLE_ACCESSORS:
emit_accessor_test(var_handle_kind, accessor, ref_type, output_path)
def emit_interface_accessor_tests(output_path):
ref_type = JavaType("WidgetInterface", [ "Widget.ONE", "Widget.TWO", "null" ])
for var_handle_kind in ALL_VAR_HANDLE_KINDS:
if var_handle_kind.is_view():
# Views as reference type arrays are not supported. They
# fail instantiation. This is tested in 710-varhandle-creation.
continue
for accessor in VAR_HANDLE_ACCESSORS:
emit_accessor_test(var_handle_kind, accessor, ref_type, output_path)
def emit_boxing_value_type_accessor_test(accessor, var_type, output_path):
test_class = "Boxing" + capitalize_first(accessor.method_name) + capitalize_first(var_type.name)
GENERATED_TEST_CLASSES.append(test_class)
src_file_path = output_path / java_file_for_class(test_class)
var_handle_kind = FIELD_VAR_HANDLE
expansions = build_template_dictionary(test_class, var_handle_kind, accessor, var_type)
template = Template("""
${banner}
${imports};
import java.lang.invoke.WrongMethodTypeException;
public class ${test_class} extends VarHandleUnitTest {
${field_declarations};
private static final VarHandle vh;
static {
try {
vh = ${lookup};
} catch (Exception e) {
throw new RuntimeException("Unexpected initialization exception", e);
}
}
@Override
public void doTest() throws Exception {
${body}
}
public static void main(String[] args) {
new ${test_class}().run();
}
}
""")
with io.StringIO() as body_text:
compatible_types = types_that_widen_to(var_type)
incompatible_types = { RANDOM.choice(list(VALUE_TYPES - compatible_types)) }
test_types = compatible_types | incompatible_types
for value_type in test_types:
print("try {", file=body_text)
return_type = accessor.get_return_type(var_type)
if return_type:
print("{0} result = ({0}) ".format(return_type), end="", file=body_text)
print("vh.{0}(this".format(accessor.method_name), end="", file=body_text)
num_args = accessor.get_number_of_var_type_arguments()
for i in range(0, num_args):
print(", SampleValues.get_{0}({1})".format(value_type.boxed_type, i), end="", file=body_text)
print(");", file=body_text)
if value_type in compatible_types:
print(" assertTrue(vh.isAccessModeSupported(VarHandle.AccessMode.{0}));".format(accessor.access_mode),
file=body_text)
else:
print("failUnreachable();", file=body_text)
print("} catch (WrongMethodTypeException e) {", file=body_text)
print("} catch (UnsupportedOperationException e) {", file=body_text)
print(" assertFalse(vh.isAccessModeSupported(VarHandle.AccessMode.{0}));".format(accessor.access_mode),
file=body_text)
print("}", file=body_text)
expansions['body'] = body_text.getvalue();
with src_file_path.open("w") as src_file:
print(template.safe_substitute(expansions), file=src_file)
def emit_boxing_return_value_type_test(accessor, var_type, output_path):
test_class = "BoxingReturn" + capitalize_first(accessor.method_name) + capitalize_first(var_type.name)
GENERATED_TEST_CLASSES.append(test_class)
src_file_path = output_path / java_file_for_class(test_class)
var_handle_kind = FIELD_VAR_HANDLE
expansions = build_template_dictionary(test_class, var_handle_kind, accessor, var_type)
template = Template("""
${banner}
${imports};
import java.lang.invoke.WrongMethodTypeException;
public class ${test_class} extends VarHandleUnitTest {
${field_declarations};
private static final VarHandle vh;
static {
try {
vh = ${lookup};
} catch (Exception e) {
throw new RuntimeException("Unexpected initialization exception", e);
}
}
@Override
public void doTest() throws Exception {
${body}
}
public static void main(String[] args) {
new ${test_class}().run();
}
}
""")
with io.StringIO() as body_text:
return_type = accessor.get_return_type(var_type)
compatible_types = { return_type }
incompatible_types = { RANDOM.choice(list(VALUE_TYPES - compatible_types)) }
test_types = compatible_types | incompatible_types
for value_type in test_types:
print("try {", file=body_text)
print("{0} result = ({0}) ".format(value_type.boxed_type), end="", file=body_text)
print("vh.{0}(this".format(accessor.method_name), end="", file=body_text)
num_args = accessor.get_number_of_var_type_arguments()
for i in range(0, num_args):
print(", {0})".format(var_type.examples[i]), end="", file=body_text)
print(");", file=body_text)
if value_type in compatible_types:
print(" assertTrue(vh.isAccessModeSupported(VarHandle.AccessMode.{0}));".format(accessor.access_mode),
file=body_text)
else:
print("failUnreachable();", file=body_text)
print("} catch (WrongMethodTypeException e) {", file=body_text)
print("} catch (UnsupportedOperationException e) {", file=body_text)
print(" assertFalse(vh.isAccessModeSupported(VarHandle.AccessMode.{0}));".format(accessor.access_mode),
file=body_text)
print("}", file=body_text)
expansions['body'] = body_text.getvalue();
with src_file_path.open("w") as src_file:
print(template.safe_substitute(expansions), file=src_file)
def emit_boxing_value_type_accessor_tests(output_path):
for var_type in VALUE_TYPES:
for accessor in VAR_HANDLE_ACCESSORS:
if accessor.get_number_of_var_type_arguments() > 0:
emit_boxing_value_type_accessor_test(accessor, var_type, output_path)
else:
emit_boxing_return_value_type_test(accessor, var_type, output_path)
def emit_main(output_path, manual_test_classes):
main_file_path = output_path / "Main.java"
all_test_classes = GENERATED_TEST_CLASSES + manual_test_classes
with main_file_path.open("w") as main_file:
print("// " + BANNER, file=main_file)
print("""
public class Main {
public static void main(String[] args) {
""", file=main_file)
for cls in all_test_classes:
print(" " + cls + ".main(args);", file=main_file)
print(" VarHandleUnitTest.DEFAULT_COLLECTOR.printSummary();", file=main_file)
print(" System.exit(VarHandleUnitTest.DEFAULT_COLLECTOR.failuresOccurred() ? 1 : 0);", file=main_file)
print(" }\n}", file=main_file)
def main(argv):
final_java_dir = Path(argv[1])
if not final_java_dir.exists() or not final_java_dir.is_dir():
print("{} is not a valid java dir".format(final_java_dir), file=sys.stderr)
sys.exit(1)
emit_value_type_accessor_tests(final_java_dir)
emit_reference_accessor_tests(final_java_dir)
emit_interface_accessor_tests(final_java_dir)
emit_boxing_value_type_accessor_tests(final_java_dir)
emit_main(final_java_dir, argv[2:])
if __name__ == '__main__':
main(sys.argv)
|