-
-
Notifications
You must be signed in to change notification settings - Fork 305
/
Clazz.java
2111 lines (1853 loc) · 64.2 KB
/
Clazz.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package aQute.bnd.osgi;
import static aQute.bnd.classfile.ClassFile.ACC_ANNOTATION;
import static aQute.bnd.classfile.ClassFile.ACC_ENUM;
import static aQute.bnd.classfile.ClassFile.ACC_MODULE;
import static aQute.bnd.classfile.ConstantPool.CONSTANT_Class;
import static aQute.bnd.classfile.ConstantPool.CONSTANT_Fieldref;
import static aQute.bnd.classfile.ConstantPool.CONSTANT_InterfaceMethodref;
import static aQute.bnd.classfile.ConstantPool.CONSTANT_MethodType;
import static aQute.bnd.classfile.ConstantPool.CONSTANT_Methodref;
import static aQute.bnd.classfile.ConstantPool.CONSTANT_NameAndType;
import static aQute.bnd.classfile.ConstantPool.CONSTANT_String;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators.AbstractSpliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.classfile.AnnotationDefaultAttribute;
import aQute.bnd.classfile.AnnotationInfo;
import aQute.bnd.classfile.AnnotationsAttribute;
import aQute.bnd.classfile.Attribute;
import aQute.bnd.classfile.BootstrapMethodsAttribute;
import aQute.bnd.classfile.BootstrapMethodsAttribute.BootstrapMethod;
import aQute.bnd.classfile.ClassFile;
import aQute.bnd.classfile.CodeAttribute;
import aQute.bnd.classfile.CodeAttribute.ExceptionHandler;
import aQute.bnd.classfile.ConstantPool;
import aQute.bnd.classfile.ConstantPool.AbstractRefInfo;
import aQute.bnd.classfile.ConstantPool.MethodTypeInfo;
import aQute.bnd.classfile.ConstantPool.NameAndTypeInfo;
import aQute.bnd.classfile.ConstantValueAttribute;
import aQute.bnd.classfile.DeprecatedAttribute;
import aQute.bnd.classfile.ElementInfo;
import aQute.bnd.classfile.ElementValueInfo;
import aQute.bnd.classfile.ElementValueInfo.EnumConst;
import aQute.bnd.classfile.ElementValueInfo.ResultConst;
import aQute.bnd.classfile.EnclosingMethodAttribute;
import aQute.bnd.classfile.ExceptionsAttribute;
import aQute.bnd.classfile.FieldInfo;
import aQute.bnd.classfile.InnerClassesAttribute;
import aQute.bnd.classfile.InnerClassesAttribute.InnerClass;
import aQute.bnd.classfile.MemberInfo;
import aQute.bnd.classfile.MethodInfo;
import aQute.bnd.classfile.MethodParametersAttribute;
import aQute.bnd.classfile.ParameterAnnotationInfo;
import aQute.bnd.classfile.ParameterAnnotationsAttribute;
import aQute.bnd.classfile.RuntimeInvisibleAnnotationsAttribute;
import aQute.bnd.classfile.RuntimeInvisibleParameterAnnotationsAttribute;
import aQute.bnd.classfile.RuntimeInvisibleTypeAnnotationsAttribute;
import aQute.bnd.classfile.RuntimeVisibleAnnotationsAttribute;
import aQute.bnd.classfile.RuntimeVisibleParameterAnnotationsAttribute;
import aQute.bnd.classfile.RuntimeVisibleTypeAnnotationsAttribute;
import aQute.bnd.classfile.SignatureAttribute;
import aQute.bnd.classfile.SourceFileAttribute;
import aQute.bnd.classfile.StackMapTableAttribute;
import aQute.bnd.classfile.StackMapTableAttribute.AppendFrame;
import aQute.bnd.classfile.StackMapTableAttribute.FullFrame;
import aQute.bnd.classfile.StackMapTableAttribute.ObjectVariableInfo;
import aQute.bnd.classfile.StackMapTableAttribute.SameLocals1StackItemFrame;
import aQute.bnd.classfile.StackMapTableAttribute.SameLocals1StackItemFrameExtended;
import aQute.bnd.classfile.StackMapTableAttribute.StackMapFrame;
import aQute.bnd.classfile.StackMapTableAttribute.VerificationTypeInfo;
import aQute.bnd.classfile.TypeAnnotationInfo;
import aQute.bnd.classfile.TypeAnnotationsAttribute;
import aQute.bnd.exceptions.Exceptions;
import aQute.bnd.osgi.Annotation.ElementType;
import aQute.bnd.osgi.Descriptors.Descriptor;
import aQute.bnd.osgi.Descriptors.NamedDescriptor;
import aQute.bnd.osgi.Descriptors.PackageRef;
import aQute.bnd.osgi.Descriptors.TypeRef;
import aQute.bnd.signatures.FieldSignature;
import aQute.bnd.signatures.MethodSignature;
import aQute.bnd.signatures.Signature;
import aQute.bnd.stream.MapStream;
import aQute.bnd.unmodifiable.Lists;
import aQute.lib.io.ByteBufferDataInput;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.libg.generics.Create;
import aQute.libg.glob.Glob;
public class Clazz {
private final static Logger logger = LoggerFactory.getLogger(Clazz.class);
public enum JAVA {
Java_1_1("JRE-1.1", "(&(osgi.ee=JRE)(version=1.1))"),
Java_1_2("J2SE-1.2", "(&(osgi.ee=JavaSE)(version=1.2))"),
Java_1_3("J2SE-1.3", "(&(osgi.ee=JavaSE)(version=1.3))"),
Java_1_4("J2SE-1.4", "(&(osgi.ee=JavaSE)(version=1.4))"),
Java_5("J2SE-1.5", "(&(osgi.ee=JavaSE)(version=1.5))"),
Java_6("JavaSE-1.6", "(&(osgi.ee=JavaSE)(version=1.6))"),
Java_7("JavaSE-1.7", "(&(osgi.ee=JavaSE)(version=1.7))"),
Java_8("JavaSE-1.8", "(&(osgi.ee=JavaSE)(version=1.8))") {
Map<String, Set<String>> profiles;
@Override
public Map<String, Set<String>> getProfiles() throws IOException {
if (profiles == null) {
Properties p = new UTF8Properties();
try (InputStream in = Clazz.class.getResourceAsStream("profiles-" + this + ".properties")) {
p.load(in);
}
profiles = MapStream.of(p)
.map((k, v) -> MapStream.entry((String) k, Strings.splitAsStream((String) v)
.collect(toSet())))
.collect(MapStream.toMap());
}
return profiles;
}
},
Java_9,
Java_10,
Java_11,
Java_12,
Java_13,
Java_14,
Java_15,
Java_16,
Java_17,
Java_18,
Java_19,
Java_20,
Java_21,
Java_22,
Java_23,
Java_24,
UNKNOWN(Integer.MAX_VALUE, "<UNKNOWN>", "(osgi.ee=UNKNOWN)");
private final int major;
private final String ee;
private final String filter;
/**
* For use by Java_9 and later.
*/
JAVA() {
this.major = ordinal() + 45;
String version = Integer.toString(ordinal() + 1);
this.ee = "JavaSE-" + version;
this.filter = "(&(osgi.ee=JavaSE)(version=" + version + "))";
}
JAVA(String ee, String filter) {
this.major = ordinal() + 45;
this.ee = ee;
this.filter = filter;
}
JAVA(int major, String ee, String filter) {
this.major = major;
this.ee = ee;
this.filter = filter;
}
private static final JAVA[] values = values();
static JAVA format(int n) {
int ordinal = n - 45;
if ((ordinal < 0) || (ordinal >= (values.length - 1))) {
return UNKNOWN;
}
JAVA java = values[ordinal];
return java;
}
public int getMajor() {
return major;
}
public boolean hasAnnotations() {
return major >= Java_5.major;
}
public boolean hasGenerics() {
return major >= Java_5.major;
}
public boolean hasEnums() {
return major >= Java_5.major;
}
public static JAVA getJava(int major, int minor) {
return format(major);
}
public String getEE() {
return ee;
}
public String getFilter() {
return filter;
}
public Map<String, Set<String>> getProfiles() throws IOException {
return null;
}
}
public enum QUERY {
IMPLEMENTS,
EXTENDS,
IMPORTS,
NAMED,
ANY,
VERSION,
CONCRETE,
ABSTRACT,
PUBLIC,
ANNOTATED,
INDIRECTLY_ANNOTATED,
HIERARCHY_ANNOTATED,
HIERARCHY_INDIRECTLY_ANNOTATED,
RUNTIMEANNOTATIONS,
CLASSANNOTATIONS,
DEFAULT_CONSTRUCTOR,
STATIC,
INNER;
}
public final static EnumSet<QUERY> HAS_ARGUMENT = EnumSet.of(QUERY.IMPLEMENTS, QUERY.EXTENDS, QUERY.IMPORTS,
QUERY.NAMED, QUERY.VERSION, QUERY.ANNOTATED, QUERY.INDIRECTLY_ANNOTATED, QUERY.HIERARCHY_ANNOTATED,
QUERY.HIERARCHY_INDIRECTLY_ANNOTATED);
final static int ACC_SYNTHETIC = 0x1000;
final static int ACC_BRIDGE = 0x0040;
public abstract class Def {
private final int access;
public Def(int access) {
this.access = access;
}
public int getAccess() {
return access;
}
public boolean isEnum() {
return Clazz.isEnum(getAccess());
}
public boolean isPublic() {
return Modifier.isPublic(getAccess());
}
public boolean isAbstract() {
return Modifier.isAbstract(getAccess());
}
public boolean isProtected() {
return Modifier.isProtected(getAccess());
}
public boolean isFinal() {
return Modifier.isFinal(getAccess());
}
public boolean isStatic() {
return Modifier.isStatic(getAccess());
}
public boolean isPrivate() {
return Modifier.isPrivate(getAccess());
}
public boolean isNative() {
return Modifier.isNative(getAccess());
}
public boolean isTransient() {
return Modifier.isTransient(getAccess());
}
public boolean isVolatile() {
return Modifier.isVolatile(getAccess());
}
public boolean isInterface() {
return Modifier.isInterface(getAccess());
}
public boolean isSynthetic() {
return Clazz.isSynthetic(getAccess());
}
public boolean isModule() {
return Clazz.isModule(getAccess());
}
public boolean isAnnotation() {
return Clazz.isAnnotation(getAccess());
}
public TypeRef getOwnerType() {
return classDef.getType();
}
public abstract String getName();
public abstract TypeRef getType();
public Object getClazz() {
return Clazz.this;
}
}
abstract class ElementDef extends Def {
private final Attribute[] attributes;
ElementDef(int access, Attribute[] attributes) {
super(access);
this.attributes = attributes;
}
ElementDef(ElementInfo elementInfo) {
this(elementInfo.access, elementInfo.attributes);
}
Attribute[] attributes() {
return attributes;
}
public boolean isDeprecated() {
return attribute(DeprecatedAttribute.class).isPresent()
|| annotationInfos(RuntimeVisibleAnnotationsAttribute.class)
.anyMatch(a -> a.type.equals("Ljava/lang/Deprecated;"));
}
public String getSignature() {
return attribute(SignatureAttribute.class).map(a -> a.signature)
.orElse(null);
}
<A extends Attribute> Stream<A> attributes(Class<A> attributeType) {
@SuppressWarnings("unchecked")
Stream<A> stream = (Stream<A>) Arrays.stream(attributes())
.filter(attributeType::isInstance);
return stream;
}
<A extends Attribute> Optional<A> attribute(Class<A> attributeType) {
return attributes(attributeType).findFirst();
}
<A extends AnnotationsAttribute> Stream<AnnotationInfo> annotationInfos(Class<A> attributeType) {
return attributes(attributeType).flatMap(a -> Arrays.stream(a.annotations));
}
public Stream<Annotation> annotations(String binaryNameFilter) {
Predicate<AnnotationInfo> matches = matches(binaryNameFilter);
ElementType elementType = elementType();
Stream<Annotation> runtimeAnnotations = annotationInfos(RuntimeVisibleAnnotationsAttribute.class)
.filter(matches)
.map(a -> newAnnotation(a, elementType, RetentionPolicy.RUNTIME, getAccess()));
Stream<Annotation> classAnnotations = annotationInfos(RuntimeInvisibleAnnotationsAttribute.class)
.filter(matches)
.map(a -> newAnnotation(a, elementType, RetentionPolicy.CLASS, getAccess()));
return Stream.concat(runtimeAnnotations, classAnnotations);
}
Predicate<AnnotationInfo> matches(String binaryNameFilter) {
if ((binaryNameFilter == null) || binaryNameFilter.equals("*")) {
return annotationInfo -> true;
}
Glob glob = new Glob("L{" + binaryNameFilter + "};");
return annotationInfo -> glob.matches(annotationInfo.type);
}
<A extends TypeAnnotationsAttribute> Stream<TypeAnnotationInfo> typeAnnotationInfos(Class<A> attributeType) {
return attributes(attributeType).flatMap(a -> Arrays.stream(a.type_annotations));
}
public Stream<TypeAnnotation> typeAnnotations(String binaryNameFilter) {
Predicate<AnnotationInfo> matches = matches(binaryNameFilter);
ElementType elementType = elementType();
Stream<TypeAnnotation> runtimeTypeAnnotations = typeAnnotationInfos(
RuntimeVisibleTypeAnnotationsAttribute.class).filter(matches)
.map(a -> newTypeAnnotation(a, elementType, RetentionPolicy.RUNTIME, getAccess()));
Stream<TypeAnnotation> classTypeAnnotations = typeAnnotationInfos(
RuntimeInvisibleTypeAnnotationsAttribute.class).filter(matches)
.map(a -> newTypeAnnotation(a, elementType, RetentionPolicy.CLASS, getAccess()));
return Stream.concat(runtimeTypeAnnotations, classTypeAnnotations);
}
@Override
public String getName() {
return super.toString();
}
@Override
public TypeRef getType() {
return null;
}
@Override
public String toString() {
return getName();
}
abstract ElementType elementType();
}
class CodeDef extends ElementDef {
private final ElementType elementType;
CodeDef(CodeAttribute code, ElementType elementType) {
super(0, code.attributes);
this.elementType = elementType;
}
@Override
ElementType elementType() {
return elementType;
}
@Override
public boolean isDeprecated() {
return false;
}
}
class ClassDef extends ElementDef {
private final TypeRef type;
ClassDef(ClassFile classFile) {
super(classFile);
type = analyzer.getTypeRef(classFile.this_class);
}
String getSourceFile() {
return attribute(SourceFileAttribute.class).map(a -> a.sourcefile)
.orElse(null);
}
boolean isInnerClass() {
String binary = type.getBinary();
return attributes(InnerClassesAttribute.class).flatMap(a -> Arrays.stream(a.classes))
.filter(inner -> binary.equals(inner.inner_class))
/*
* We need all 3 of these checks. Normally the inner class being
* non-static is enough but sometimes inner classes are marked
* static. Kotlin does this for anonymous and local classes and
* older Java compilers did this sometimes for anonymous
* classes. So we further check for no outer class which means
* local and, as of Java 7, anonymous. Since we must also handle
* pre-Java 7 class files, we must finally check the name since
* anonymous classes have no name in source code.
*/
.anyMatch(inner -> !Modifier.isStatic(inner.inner_access) // inner
|| (inner.outer_class == null) // local or anonymous
|| (inner.inner_name == null)); // anonymous
}
boolean isPackageInfo() {
return type.getBinary()
.endsWith("/package-info");
}
@Override
public String getName() {
return type.getFQN();
}
@Override
public TypeRef getType() {
return type;
}
@Override
ElementType elementType() {
if (super.isAnnotation()) {
return ElementType.ANNOTATION_TYPE;
}
if (super.isModule()) {
return ElementType.MODULE;
}
return isPackageInfo() ? ElementType.PACKAGE : ElementType.TYPE;
}
}
public abstract class MemberDef extends ElementDef {
private final MemberInfo memberInfo;
MemberDef(MemberInfo memberInfo) {
super(memberInfo);
this.memberInfo = memberInfo;
}
@Override
public String getName() {
return memberInfo.name;
}
@Override
public String toString() {
return memberInfo.toString();
}
@Override
public TypeRef getType() {
return getDescriptor().getType();
}
public TypeRef getContainingClass() {
return getClassName();
}
public String descriptor() {
return memberInfo.descriptor;
}
public Descriptor getDescriptor() {
return analyzer.getDescriptor(descriptor());
}
public abstract Object getConstant();
public abstract String getGenericReturnType();
public NamedDescriptor getNamedDescriptor() {
return new NamedDescriptor(getName(), getDescriptor());
}
}
public class FieldDef extends MemberDef {
FieldDef(MemberInfo memberInfo) {
super(memberInfo);
}
@Override
public Object getConstant() {
return attribute(ConstantValueAttribute.class).map(a -> a.value)
.orElse(null);
}
@Override
public String getGenericReturnType() {
String signature = getSignature();
FieldSignature sig = analyzer.getFieldSignature((signature != null) ? signature : descriptor());
return sig.type.toString();
}
@Override
ElementType elementType() {
return ElementType.FIELD;
}
}
public static class MethodParameter {
private final MethodParametersAttribute.MethodParameter methodParameter;
MethodParameter(MethodParametersAttribute.MethodParameter methodParameter) {
this.methodParameter = methodParameter;
}
public String getName() {
return methodParameter.name;
}
public int getAccess() {
return methodParameter.access_flags;
}
@Override
public String toString() {
return getName();
}
static MethodParameter[] parameters(MethodParametersAttribute attribute) {
int parameters_count = attribute.parameters.length;
MethodParameter[] parameters = new MethodParameter[parameters_count];
for (int i = 0; i < parameters_count; i++) {
parameters[i] = new MethodParameter(attribute.parameters[i]);
}
return parameters;
}
}
public class MethodDef extends MemberDef {
public MethodDef(MethodInfo methodInfo) {
super(methodInfo);
}
public boolean isConstructor() {
String name = getName();
return name.equals("<init>") || name.equals("<clinit>");
}
@Override
public boolean isFinal() {
return super.isFinal() || Clazz.this.isFinal();
}
public boolean isDefault() {
return Clazz.this.isInterface() && !isStatic() && !isAbstract();
}
public TypeRef[] getPrototype() {
return getDescriptor().getPrototype();
}
public boolean isBridge() {
return (super.getAccess() & ACC_BRIDGE) != 0;
}
@Override
public String getGenericReturnType() {
String signature = getSignature();
MethodSignature sig = analyzer.getMethodSignature((signature != null) ? signature : descriptor());
return sig.resultType.toString();
}
public MethodParameter[] getParameters() {
return attribute(MethodParametersAttribute.class).map(MethodParameter::parameters)
.orElseGet(() -> new MethodParameter[0]);
}
@Override
public Object getConstant() {
return attribute(AnnotationDefaultAttribute.class).map(a -> annotationDefault(a, getAccess()))
.orElse(null);
}
<A extends ParameterAnnotationsAttribute> Stream<ParameterAnnotationInfo> parameterAnnotationInfos(
Class<A> attributeType) {
return attributes(attributeType).flatMap(a -> Arrays.stream(a.parameter_annotations));
}
public Stream<ParameterAnnotation> parameterAnnotations(String binaryNameFilter) {
Predicate<AnnotationInfo> matches = matches(binaryNameFilter);
ElementType elementType = elementType();
Stream<ParameterAnnotation> runtimeParameterAnnotations = parameterAnnotationInfos(
RuntimeVisibleParameterAnnotationsAttribute.class)
.flatMap(a -> parameterAnnotations(a, matches, elementType, RetentionPolicy.RUNTIME));
Stream<ParameterAnnotation> classParameterAnnotations = parameterAnnotationInfos(
RuntimeInvisibleParameterAnnotationsAttribute.class)
.flatMap(a -> parameterAnnotations(a, matches, elementType, RetentionPolicy.CLASS));
return Stream.concat(runtimeParameterAnnotations, classParameterAnnotations);
}
private Stream<ParameterAnnotation> parameterAnnotations(ParameterAnnotationInfo parameterAnnotationInfo,
Predicate<AnnotationInfo> matches, ElementType elementType, RetentionPolicy policy) {
int parameter = parameterAnnotationInfo.parameter;
return Arrays.stream(parameterAnnotationInfo.annotations)
.filter(matches)
.map(a -> newParameterAnnotation(parameter, a, elementType, policy, getAccess()));
}
/**
* We must also look in the method's Code attribute for type
* annotations.
*/
@Override
<A extends TypeAnnotationsAttribute> Stream<TypeAnnotationInfo> typeAnnotationInfos(Class<A> attributeType) {
ElementType elementType = elementType();
Stream<A> methodAttributes = attributes(attributeType);
Stream<A> codeAttributes = attribute(CodeAttribute.class)
.map(code -> new CodeDef(code, elementType).attributes(attributeType))
.orElseGet(Stream::empty);
return Stream.concat(methodAttributes, codeAttributes)
.flatMap(a -> Arrays.stream(a.type_annotations));
}
@Override
ElementType elementType() {
return getName().equals("<init>") ? ElementType.CONSTRUCTOR : ElementType.METHOD;
}
/**
* Return the set of thrown types in this method. Not that if these
* exceptions contain generics, you should definitely use the signature.
*/
public TypeRef[] getThrows() {
return attribute(ExceptionsAttribute.class).map(ea -> Stream.of(ea.exceptions)
.map(analyzer::getTypeRefFromFQN)
.toArray(TypeRef[]::new))
.orElse(new TypeRef[0]);
}
}
public class TypeDef extends Def {
final TypeRef type;
final boolean interf;
public TypeDef(TypeRef type, boolean interf) {
super(Modifier.PUBLIC);
this.type = type;
this.interf = interf;
}
public TypeRef getReference() {
return type;
}
public boolean getImplements() {
return interf;
}
@Override
public String getName() {
if (interf)
return "<implements>";
return "<extends>";
}
@Override
public TypeRef getType() {
return type;
}
}
public static final Comparator<Clazz> NAME_COMPARATOR = (Clazz a,
Clazz b) -> a.classFile.this_class.compareTo(b.classFile.this_class);
private boolean hasRuntimeAnnotations;
private boolean hasClassAnnotations;
private boolean hasDefaultConstructor;
private Set<PackageRef> imports = Create.set();
private Set<TypeRef> xref = new HashSet<>();
private Set<TypeRef> annotations;
private int forName = 0;
private int class$ = 0;
private Set<PackageRef> api;
private ClassFile classFile = null;
private ConstantPool constantPool = null;
TypeRef superClass;
private TypeRef[] interfaces;
ClassDef classDef;
private Map<TypeRef, Integer> referred = null;
final Analyzer analyzer;
final String path;
final Resource resource;
public static final int TYPEUSE_INDEX_NONE = TypeAnnotationInfo.TYPEUSE_INDEX_NONE;
public static final int TYPEUSE_TARGET_INDEX_EXTENDS = TypeAnnotationInfo.TYPEUSE_TARGET_INDEX_EXTENDS;
public Clazz(Analyzer analyzer, String path, Resource resource) {
this.path = path;
this.resource = resource;
this.analyzer = analyzer;
}
public Set<TypeRef> parseClassFile() throws Exception {
return parseClassFileWithCollector(null);
}
public Set<TypeRef> parseClassFile(InputStream in) throws Exception {
return parseClassFile(in, null);
}
public Set<TypeRef> parseClassFileWithCollector(ClassDataCollector cd) throws Exception {
ByteBuffer bb = resource.buffer();
if (bb != null) {
return parseClassFileData(ByteBufferDataInput.wrap(bb), cd);
}
return parseClassFile(resource.openInputStream(), cd);
}
public Set<TypeRef> parseClassFile(InputStream in, ClassDataCollector cd) throws Exception {
try (DataInputStream din = new DataInputStream(in)) {
return parseClassFileData(din, cd);
}
}
private Set<TypeRef> parseClassFileData(DataInput in, ClassDataCollector cd) throws Exception {
Set<TypeRef> xref = parseClassFileData(in);
visitClassFile(cd);
return xref;
}
private synchronized Set<TypeRef> parseClassFileData(DataInput in) throws Exception {
if (classFile != null) {
return xref;
}
logger.debug("parseClassFile(): path={} resource={}", path, resource);
classFile = ClassFile.parseClassFile(in);
classDef = new ClassDef(classFile);
constantPool = classFile.constant_pool;
referred = new HashMap<>(constantPool.size());
if (classDef.isPublic()) {
api = new HashSet<>();
}
if (!classDef.isModule()) {
referTo(classDef.getType(), Modifier.PUBLIC);
}
String superName = classFile.super_class;
if (superName == null) {
if (!(classDef.getType()
.isObject() || classDef.isModule())) {
throw new IOException("Class does not have a super class and is not java.lang.Object or module-info");
}
} else {
superClass = analyzer.getTypeRef(superName);
referTo(superClass, classFile.access);
}
int interfaces_count = classFile.interfaces.length;
if (interfaces_count > 0) {
interfaces = new TypeRef[interfaces_count];
for (int i = 0; i < interfaces_count; i++) {
interfaces[i] = analyzer.getTypeRef(classFile.interfaces[i]);
referTo(interfaces[i], classFile.access);
}
}
// All name&type and class constant records contain descriptors we
// must treat as references, though not API
int constant_pool_count = constantPool.size();
for (int i = 1; i < constant_pool_count; i++) {
switch (constantPool.tag(i)) {
case CONSTANT_Fieldref :
case CONSTANT_Methodref :
case CONSTANT_InterfaceMethodref : {
AbstractRefInfo info = constantPool.entry(i);
classConstRef(constantPool.className(info.class_index));
break;
}
case CONSTANT_NameAndType : {
NameAndTypeInfo info = constantPool.entry(i);
referTo(constantPool.utf8(info.descriptor_index), 0);
break;
}
case CONSTANT_MethodType : {
MethodTypeInfo info = constantPool.entry(i);
referTo(constantPool.utf8(info.descriptor_index), 0);
break;
}
default :
break;
}
}
for (FieldInfo fieldInfo : classFile.fields) {
referTo(fieldInfo.descriptor, fieldInfo.access);
processAttributes(fieldInfo.attributes, elementType(fieldInfo), fieldInfo.access);
}
// We crawl the code to find the instruction sequence:
//
// ldc(_w) <string constant>
// invokestatic Class.forName(String)
//
// We calculate the method reference index so we can do this
// efficiently during code inspection.
forName = analyzer.is(Constants.NOCLASSFORNAME) ? -1
: findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
class$ = findMethodReference(classFile.this_class, "class$", "(Ljava/lang/String;)Ljava/lang/Class;");
for (MethodInfo methodInfo : classFile.methods) {
referTo(methodInfo.descriptor, methodInfo.access);
ElementType elementType = elementType(methodInfo);
if ((elementType == ElementType.CONSTRUCTOR) && Modifier.isPublic(methodInfo.access)
&& methodInfo.descriptor.equals("()V")) {
hasDefaultConstructor = true;
}
processAttributes(methodInfo.attributes, elementType, methodInfo.access);
}
processAttributes(classFile.attributes, elementType(classFile), classFile.access);
return xref;
}
private void visitClassFile(ClassDataCollector cd) throws Exception {
if (cd == null) {
return;
}
logger.debug("visitClassFile(): path={} resource={}", path, resource);
if (!cd.classStart(this)) {
return;
}
try {
cd.version(classFile.minor_version, classFile.major_version);
if (superClass != null) {
cd.extendsClass(superClass);
}
if (interfaces != null) {
cd.implementsInterfaces(interfaces);
}
referred.forEach((typeRef, access) -> {
cd.addReference(typeRef);
cd.referTo(typeRef, access.intValue());
});
for (FieldInfo fieldInfo : classFile.fields) {
FieldDef fieldDef = new FieldDef(fieldInfo);
cd.field(fieldDef);
visitAttributes(cd, fieldDef);
}
for (MethodInfo methodInfo : classFile.methods) {
MethodDef methodDef = new MethodDef(methodInfo);
cd.method(methodDef);
visitAttributes(cd, methodDef);
}
cd.memberEnd();
visitAttributes(cd, classDef);
} finally {
cd.classEnd();
}
}
public Stream<FieldDef> fields() {
return Arrays.stream(classFile.fields)
.map(FieldDef::new);
}
public Stream<MethodDef> methods() {
return Arrays.stream(classFile.methods)
.map(MethodDef::new);
}
/**
* Find a method reference in the pool that points to the given class,
* methodname and descriptor.
*
* @param clazz
* @param methodname
* @param descriptor
* @return index in constant pool
*/
private int findMethodReference(String clazz, String methodname, String descriptor) {
int constant_pool_count = constantPool.size();
for (int i = 1; i < constant_pool_count; i++) {
switch (constantPool.tag(i)) {
case CONSTANT_Methodref :
case CONSTANT_InterfaceMethodref :
AbstractRefInfo refInfo = constantPool.entry(i);
if (clazz.equals(constantPool.className(refInfo.class_index))) {
NameAndTypeInfo nameAndTypeInfo = constantPool.entry(refInfo.name_and_type_index);
if (methodname.equals(constantPool.utf8(nameAndTypeInfo.name_index))
&& descriptor.equals(constantPool.utf8(nameAndTypeInfo.descriptor_index))) {
return i;
}
}
}
}
return -1;
}
/**
* Called for the attributes in the class, field, method or Code attribute.
*/
private void processAttributes(Attribute[] attributes, ElementType elementType, int access_flags) {
for (Attribute attribute : attributes) {
switch (attribute.name()) {
case RuntimeVisibleAnnotationsAttribute.NAME :
processAnnotations((AnnotationsAttribute) attribute, elementType, RetentionPolicy.RUNTIME,
access_flags);
break;
case RuntimeInvisibleAnnotationsAttribute.NAME :
processAnnotations((AnnotationsAttribute) attribute, elementType, RetentionPolicy.CLASS,