1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.bcel.classfile;
20
21 import java.io.ByteArrayOutputStream;
22 import java.io.DataOutputStream;
23 import java.io.File;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.OutputStream;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Objects;
32 import java.util.Set;
33 import java.util.StringTokenizer;
34 import java.util.TreeSet;
35
36 import org.apache.bcel.Const;
37 import org.apache.bcel.generic.Type;
38 import org.apache.bcel.util.Args;
39 import org.apache.bcel.util.BCELComparator;
40 import org.apache.bcel.util.ClassQueue;
41 import org.apache.bcel.util.SyntheticRepository;
42 import org.apache.commons.lang3.ArrayUtils;
43
44
45
46
47
48
49
50
51
52 public class JavaClass extends AccessFlags implements Cloneable, Node, Comparable<JavaClass> {
53
54 private static final String CLASS_NAME_OBJECT = "java.lang.Object";
55
56
57
58
59
60
61 public static final String EXTENSION = ".class";
62
63
64
65
66
67
68 public static final JavaClass[] EMPTY_ARRAY = {};
69
70
71 public static final byte HEAP = 1;
72
73
74 public static final byte FILE = 2;
75
76
77 public static final byte ZIP = 3;
78
79 private static final boolean debug = Boolean.getBoolean("JavaClass.debug");
80
81 private static BCELComparator<JavaClass> bcelComparator = new BCELComparator<JavaClass>() {
82
83 @Override
84 public boolean equals(final JavaClass a, final JavaClass b) {
85 return a == b || a != null && b != null && Objects.equals(a.getClassName(), b.getClassName());
86 }
87
88 @Override
89 public int hashCode(final JavaClass o) {
90 return o != null ? Objects.hashCode(o.getClassName()) : 0;
91 }
92 };
93
94
95
96
97 static void Debug(final String str) {
98 if (debug) {
99 System.out.println(str);
100 }
101 }
102
103
104
105
106
107
108 public static BCELComparator<JavaClass> getComparator() {
109 return bcelComparator;
110 }
111
112 private static String indent(final Object obj) {
113 final StringTokenizer tokenizer = new StringTokenizer(obj.toString(), "\n");
114 final StringBuilder buf = new StringBuilder();
115 while (tokenizer.hasMoreTokens()) {
116 buf.append("\t").append(tokenizer.nextToken()).append("\n");
117 }
118 return buf.toString();
119 }
120
121
122
123
124
125
126 public static void setComparator(final BCELComparator<JavaClass> comparator) {
127 bcelComparator = comparator;
128 }
129
130 private String fileName;
131 private final String packageName;
132 private String sourceFileName = "<Unknown>";
133 private int classNameIndex;
134 private int superclassNameIndex;
135 private String className;
136 private String superclassName;
137 private int major;
138 private int minor;
139 private ConstantPool constantPool;
140 private int[] interfaces;
141 private String[] interfaceNames;
142 private Field[] fields;
143 private Method[] methods;
144 private Attribute[] attributes;
145
146 private AnnotationEntry[] annotations;
147 private byte source = HEAP;
148
149 private boolean isAnonymous;
150
151 private boolean isNested;
152 private boolean isRecord;
153
154 private boolean computedNestedTypeStatus;
155 private boolean computedRecord;
156
157
158
159
160
161 private transient org.apache.bcel.util.Repository repository = SyntheticRepository.getInstance();
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178 public JavaClass(final int classNameIndex, final int superclassNameIndex, final String fileName, final int major, final int minor, final int accessFlags,
179 final ConstantPool constantPool, final int[] interfaces, final Field[] fields, final Method[] methods, final Attribute[] attributes) {
180 this(classNameIndex, superclassNameIndex, fileName, major, minor, accessFlags, constantPool, interfaces, fields, methods, attributes, HEAP);
181 }
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199 public JavaClass(final int classNameIndex, final int superclassNameIndex, final String fileName, final int major, final int minor, final int accessFlags,
200 final ConstantPool constantPool, int[] interfaces, Field[] fields, Method[] methods, Attribute[] attributes, final byte source) {
201 super(accessFlags);
202 interfaces = ArrayUtils.nullToEmpty(interfaces);
203 if (attributes == null) {
204 attributes = Attribute.EMPTY_ARRAY;
205 }
206 if (fields == null) {
207 fields = Field.EMPTY_ARRAY;
208 }
209 if (methods == null) {
210 methods = Method.EMPTY_ARRAY;
211 }
212 this.classNameIndex = classNameIndex;
213 this.superclassNameIndex = superclassNameIndex;
214 this.fileName = fileName;
215 this.major = major;
216 this.minor = minor;
217 this.constantPool = constantPool;
218 this.interfaces = interfaces;
219 this.fields = fields;
220 this.methods = methods;
221 this.attributes = attributes;
222 this.source = source;
223
224 for (final Attribute attribute : attributes) {
225 if (attribute instanceof SourceFile) {
226 sourceFileName = ((SourceFile) attribute).getSourceFileName();
227 break;
228 }
229 }
230
231
232
233
234 className = constantPool.getConstantString(classNameIndex, Const.CONSTANT_Class);
235 className = Utility.compactClassName(className, false);
236 final int index = className.lastIndexOf('.');
237 if (index < 0) {
238 packageName = "";
239 } else {
240 packageName = className.substring(0, index);
241 }
242 if (superclassNameIndex > 0) {
243
244 superclassName = constantPool.getConstantString(superclassNameIndex, Const.CONSTANT_Class);
245 superclassName = Utility.compactClassName(superclassName, false);
246 } else {
247 superclassName = CLASS_NAME_OBJECT;
248 }
249 interfaceNames = new String[interfaces.length];
250 for (int i = 0; i < interfaces.length; i++) {
251 final String str = constantPool.getConstantString(interfaces[i], Const.CONSTANT_Class);
252 interfaceNames[i] = Utility.compactClassName(str, false);
253 }
254 }
255
256
257
258
259
260
261
262 @Override
263 public void accept(final Visitor v) {
264 v.visitJavaClass(this);
265 }
266
267
268
269
270
271
272 @Override
273 public int compareTo(final JavaClass obj) {
274 return getClassName().compareTo(obj.getClassName());
275 }
276
277 private void computeIsRecord() {
278 if (computedRecord) {
279 return;
280 }
281 for (final Attribute attribute : this.attributes) {
282 if (attribute instanceof Record) {
283 isRecord = true;
284 break;
285 }
286 }
287 this.computedRecord = true;
288 }
289
290 private void computeNestedTypeStatus() {
291 if (computedNestedTypeStatus) {
292 return;
293 }
294 for (final Attribute attribute : this.attributes) {
295 if (attribute instanceof InnerClasses) {
296 ((InnerClasses) attribute).forEach(innerClass -> {
297 boolean innerClassAttributeRefersToMe = false;
298 String innerClassName = constantPool.getConstantString(innerClass.getInnerClassIndex(), Const.CONSTANT_Class);
299 innerClassName = Utility.compactClassName(innerClassName, false);
300 if (innerClassName.equals(getClassName())) {
301 innerClassAttributeRefersToMe = true;
302 }
303 if (innerClassAttributeRefersToMe) {
304 this.isNested = true;
305 if (innerClass.getInnerNameIndex() == 0) {
306 this.isAnonymous = true;
307 }
308 }
309 });
310 }
311 }
312 this.computedNestedTypeStatus = true;
313 }
314
315
316
317
318
319
320 public JavaClass copy() {
321 try {
322 final JavaClass c = (JavaClass) clone();
323 c.constantPool = constantPool.copy();
324 c.interfaces = interfaces.clone();
325 c.interfaceNames = interfaceNames.clone();
326 c.fields = new Field[fields.length];
327 Arrays.setAll(c.fields, i -> fields[i].copy(c.constantPool));
328 c.methods = new Method[methods.length];
329 Arrays.setAll(c.methods, i -> methods[i].copy(c.constantPool));
330 c.attributes = new Attribute[attributes.length];
331 Arrays.setAll(c.attributes, i -> attributes[i].copy(c.constantPool));
332 return c;
333 } catch (final CloneNotSupportedException e) {
334 return null;
335 }
336 }
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352 public void dump(final DataOutputStream file) throws IOException {
353
354 final boolean compactCodeHeader = major == Const.MAJOR_1_1 && minor < Const.MINOR_1_1 && Arrays.stream(methods)
355 .map(Method::getCode).filter(Objects::nonNull).anyMatch(Code::isCompactCodeHeader);
356 file.writeInt(Const.JVM_CLASSFILE_MAGIC);
357 file.writeShort(minor);
358 file.writeShort(major);
359 constantPool.dump(file);
360 file.writeShort(super.getAccessFlags());
361 file.writeShort(classNameIndex);
362 file.writeShort(superclassNameIndex);
363 file.writeShort(Args.requireU2(interfaces.length, "interfaces.length"));
364 for (final int interface1 : interfaces) {
365 file.writeShort(interface1);
366 }
367 file.writeShort(Args.requireU2(fields.length, "fields.length"));
368 for (final Field field : fields) {
369 field.dump(file);
370 }
371 file.writeShort(Args.requireU2(methods.length, "methods.length"));
372 for (final Method method : methods) {
373 method.dump(file, compactCodeHeader);
374 }
375 if (attributes != null) {
376 file.writeShort(Args.requireU2(attributes.length, "attributes.length"));
377 for (final Attribute attribute : attributes) {
378 attribute.dump(file);
379 }
380 } else {
381 file.writeShort(0);
382 }
383 file.flush();
384 }
385
386
387
388
389
390
391
392 public void dump(final File file) throws IOException {
393 final String parent = file.getParent();
394 if (parent != null) {
395 final File dir = new File(parent);
396 if (!dir.mkdirs() && !dir.isDirectory()) {
397 throw new IOException("Could not create the directory " + dir);
398 }
399 }
400 try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(file))) {
401 dump(dos);
402 }
403 }
404
405
406
407
408
409
410
411 public void dump(final OutputStream file) throws IOException {
412 dump(new DataOutputStream(file));
413 }
414
415
416
417
418
419
420
421 public void dump(final String fileName) throws IOException {
422 dump(new File(fileName));
423 }
424
425
426
427
428
429
430
431 @Override
432 public boolean equals(final Object obj) {
433 return obj instanceof JavaClass && bcelComparator.equals(this, (JavaClass) obj);
434 }
435
436
437
438
439
440
441
442
443
444
445 public Field findField(final String fieldName, final Type fieldType) throws ClassNotFoundException {
446 return findFieldVisit(fieldName, fieldType, new HashSet<>());
447 }
448
449 private Field findFieldVisit(final String fieldName, final Type fieldType, final Set<JavaClass> visiting) throws ClassNotFoundException {
450 if (!visiting.add(this)) {
451 throw new ClassFormatException(getClassName());
452 }
453 try {
454 for (final Field field : fields) {
455 if (field.getName().equals(fieldName)) {
456 final Type fType = Type.getType(field.getSignature());
457
458 if (fType.equals(fieldType)) {
459 return field;
460 }
461 }
462 }
463 final JavaClass superclass = getSuperClass();
464 if (superclass != null && !CLASS_NAME_OBJECT.equals(superclass.getClassName())) {
465 final Field f = superclass.findFieldVisit(fieldName, fieldType, visiting);
466 if (f != null && (f.isPublic() || f.isProtected() || !f.isPrivate() && packageName.equals(superclass.getPackageName()))) {
467 return f;
468 }
469 }
470 final JavaClass[] implementedInterfaces = getInterfaces();
471 if (implementedInterfaces != null) {
472 for (final JavaClass implementedInterface : implementedInterfaces) {
473 final Field f = implementedInterface.findFieldVisit(fieldName, fieldType, visiting);
474 if (f != null) {
475 return f;
476 }
477 }
478 }
479 return null;
480 } finally {
481 visiting.remove(this);
482 }
483 }
484
485
486
487
488
489
490
491 public JavaClass[] getAllInterfaces() throws ClassNotFoundException {
492 final ClassQueue queue = new ClassQueue();
493 final Set<JavaClass> allInterfaces = new TreeSet<>();
494 final Set<JavaClass> visited = new HashSet<>();
495 queue.enqueue(this);
496 while (!queue.empty()) {
497 final JavaClass clazz = queue.dequeue();
498 if (!visited.add(clazz)) {
499 continue;
500 }
501 final JavaClass souper = clazz.getSuperClass();
502 final JavaClass[] interfaces = clazz.getInterfaces();
503 if (clazz.isInterface()) {
504 allInterfaces.add(clazz);
505 } else if (souper != null) {
506 queue.enqueue(souper);
507 }
508 for (final JavaClass iface : interfaces) {
509 queue.enqueue(iface);
510 }
511 }
512 return allInterfaces.toArray(EMPTY_ARRAY);
513 }
514
515
516
517
518
519
520
521 public AnnotationEntry[] getAnnotationEntries() {
522 if (annotations == null) {
523 annotations = AnnotationEntry.createAnnotationEntries(getAttributes());
524 }
525
526 return annotations;
527 }
528
529
530
531
532
533
534
535
536
537
538 @SuppressWarnings("unchecked")
539 public final <T extends Attribute> T getAttribute(final byte tag) {
540 for (final Attribute attribute : getAttributes()) {
541 if (attribute.getTag() == tag) {
542 return (T) attribute;
543 }
544 }
545 return null;
546 }
547
548
549
550
551
552
553 public Attribute[] getAttributes() {
554 return attributes;
555 }
556
557
558
559
560
561
562 public byte[] getBytes() {
563 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
564 try (DataOutputStream dos = new DataOutputStream(baos)) {
565 dump(dos);
566 } catch (final IOException e) {
567 e.printStackTrace();
568 }
569 return baos.toByteArray();
570 }
571
572
573
574
575
576
577 public String getClassName() {
578 return className;
579 }
580
581
582
583
584
585
586 public int getClassNameIndex() {
587 return classNameIndex;
588 }
589
590
591
592
593
594
595 public ConstantPool getConstantPool() {
596 return constantPool;
597 }
598
599
600
601
602
603
604
605 public Field[] getFields() {
606 return fields;
607 }
608
609
610
611
612
613
614 public String getFileName() {
615 return fileName;
616 }
617
618
619
620
621
622
623 public int[] getInterfaceIndices() {
624 return interfaces;
625 }
626
627
628
629
630
631
632 public String[] getInterfaceNames() {
633 return interfaceNames;
634 }
635
636
637
638
639
640
641
642 public JavaClass[] getInterfaces() throws ClassNotFoundException {
643 final String[] interfaces = getInterfaceNames();
644 final JavaClass[] classes = new JavaClass[interfaces.length];
645 for (int i = 0; i < interfaces.length; i++) {
646 classes[i] = repository.loadClass(interfaces[i]);
647 }
648 return classes;
649 }
650
651
652
653
654
655
656 public int getMajor() {
657 return major;
658 }
659
660
661
662
663
664
665
666 public Method getMethod(final java.lang.reflect.Method m) {
667 for (final Method method : methods) {
668 if (m.getName().equals(method.getName()) && m.getModifiers() == method.getModifiers() && Type.getSignature(m).equals(method.getSignature())) {
669 return method;
670 }
671 }
672 return null;
673 }
674
675
676
677
678
679
680 public Method[] getMethods() {
681 return methods;
682 }
683
684
685
686
687
688
689 public int getMinor() {
690 return minor;
691 }
692
693
694
695
696
697
698 public String getPackageName() {
699 return packageName;
700 }
701
702
703
704
705
706
707
708 public org.apache.bcel.util.Repository getRepository() {
709 return repository;
710 }
711
712
713
714
715
716
717 public final byte getSource() {
718 return source;
719 }
720
721
722
723
724
725
726 public String getSourceFileName() {
727 return sourceFileName;
728 }
729
730
731
732
733
734
735
736 public String getSourceFilePath() {
737 final StringBuilder outFileName = new StringBuilder();
738 if (!packageName.isEmpty()) {
739 outFileName.append(Utility.packageToPath(packageName));
740 outFileName.append('/');
741 }
742 outFileName.append(sourceFileName);
743 return outFileName.toString();
744 }
745
746
747
748
749
750
751
752 public JavaClass getSuperClass() throws ClassNotFoundException {
753 if (CLASS_NAME_OBJECT.equals(getClassName())) {
754 return null;
755 }
756 return repository.loadClass(getSuperclassName());
757 }
758
759
760
761
762
763
764
765 public JavaClass[] getSuperClasses() throws ClassNotFoundException {
766 JavaClass clazz = this;
767 final List<JavaClass> allSuperClasses = new ArrayList<>();
768 final Set<JavaClass> visited = new HashSet<>();
769 visited.add(this);
770 for (clazz = clazz.getSuperClass(); clazz != null; clazz = clazz.getSuperClass()) {
771 if (!visited.add(clazz)) {
772 throw new ClassFormatException(clazz.getClassName());
773 }
774 allSuperClasses.add(clazz);
775 }
776 return allSuperClasses.toArray(EMPTY_ARRAY);
777 }
778
779
780
781
782
783
784
785 public String getSuperclassName() {
786 return superclassName;
787 }
788
789
790
791
792
793
794 public int getSuperclassNameIndex() {
795 return superclassNameIndex;
796 }
797
798
799
800
801
802
803 @Override
804 public int hashCode() {
805 return bcelComparator.hashCode(this);
806 }
807
808
809
810
811
812
813
814
815 public boolean implementationOf(final JavaClass inter) throws ClassNotFoundException {
816 if (!inter.isInterface()) {
817 throw new IllegalArgumentException(inter.getClassName() + " is not an interface");
818 }
819 if (equals(inter)) {
820 return true;
821 }
822 final JavaClass[] superInterfaces = getAllInterfaces();
823 for (final JavaClass superInterface : superInterfaces) {
824 if (superInterface.equals(inter)) {
825 return true;
826 }
827 }
828 return false;
829 }
830
831
832
833
834
835
836
837
838 public final boolean instanceOf(final JavaClass superclass) throws ClassNotFoundException {
839 if (equals(superclass)) {
840 return true;
841 }
842 for (final JavaClass clazz : getSuperClasses()) {
843 if (clazz.equals(superclass)) {
844 return true;
845 }
846 }
847 if (superclass.isInterface()) {
848 return implementationOf(superclass);
849 }
850 return false;
851 }
852
853
854
855
856
857
858
859 public final boolean isAnonymous() {
860 computeNestedTypeStatus();
861 return this.isAnonymous;
862 }
863
864
865
866
867
868
869 public final boolean isClass() {
870 return (super.getAccessFlags() & Const.ACC_INTERFACE) == 0;
871 }
872
873
874
875
876
877
878
879 public final boolean isNested() {
880 computeNestedTypeStatus();
881 return this.isNested;
882 }
883
884
885
886
887
888
889
890 public boolean isRecord() {
891 computeIsRecord();
892 return this.isRecord;
893 }
894
895
896
897
898
899
900 public final boolean isSuper() {
901 return (super.getAccessFlags() & Const.ACC_SUPER) != 0;
902 }
903
904
905
906
907
908
909 public void setAttributes(final Attribute[] attributes) {
910 this.attributes = attributes != null ? attributes : Attribute.EMPTY_ARRAY;
911 }
912
913
914
915
916
917
918 public void setClassName(final String className) {
919 this.className = className;
920 }
921
922
923
924
925
926
927 public void setClassNameIndex(final int classNameIndex) {
928 this.classNameIndex = classNameIndex;
929 }
930
931
932
933
934
935
936 public void setConstantPool(final ConstantPool constantPool) {
937 this.constantPool = constantPool;
938 }
939
940
941
942
943
944
945 public void setFields(final Field[] fields) {
946 this.fields = fields != null ? fields : Field.EMPTY_ARRAY;
947 }
948
949
950
951
952
953
954 public void setFileName(final String fileName) {
955 this.fileName = fileName;
956 }
957
958
959
960
961
962
963 public void setInterfaceNames(final String[] interfaceNames) {
964 this.interfaceNames = ArrayUtils.nullToEmpty(interfaceNames);
965 }
966
967
968
969
970
971
972 public void setInterfaces(final int[] interfaces) {
973 this.interfaces = ArrayUtils.nullToEmpty(interfaces);
974 }
975
976
977
978
979
980
981 public void setMajor(final int major) {
982 this.major = major;
983 }
984
985
986
987
988
989
990 public void setMethods(final Method[] methods) {
991 this.methods = methods != null ? methods : Method.EMPTY_ARRAY;
992 }
993
994
995
996
997
998
999 public void setMinor(final int minor) {
1000 this.minor = minor;
1001 }
1002
1003
1004
1005
1006
1007
1008 public void setRepository(final org.apache.bcel.util.Repository repository) {
1009 this.repository = repository;
1010 }
1011
1012
1013
1014
1015
1016
1017 public void setSourceFileName(final String sourceFileName) {
1018 this.sourceFileName = sourceFileName;
1019 }
1020
1021
1022
1023
1024
1025
1026 public void setSuperclassName(final String superclassName) {
1027 this.superclassName = superclassName;
1028 }
1029
1030
1031
1032
1033
1034
1035 public void setSuperclassNameIndex(final int superclassNameIndex) {
1036 this.superclassNameIndex = superclassNameIndex;
1037 }
1038
1039
1040
1041
1042 @Override
1043 public String toString() {
1044 String access = Utility.accessToString(super.getAccessFlags(), true);
1045 access = access.isEmpty() ? "" : access + " ";
1046 final StringBuilder buf = new StringBuilder(128);
1047 buf.append(access).append(Utility.classOrInterface(super.getAccessFlags())).append(" ").append(className).append(" extends ")
1048 .append(Utility.compactClassName(superclassName, false)).append('\n');
1049 final int size = interfaces.length;
1050 if (size > 0) {
1051 buf.append("implements\t\t");
1052 for (int i = 0; i < size; i++) {
1053 buf.append(interfaceNames[i]);
1054 if (i < size - 1) {
1055 buf.append(", ");
1056 }
1057 }
1058 buf.append('\n');
1059 }
1060 buf.append("file name\t\t").append(fileName).append('\n');
1061 buf.append("compiled from\t\t").append(sourceFileName).append('\n');
1062 buf.append("compiler version\t").append(major).append(".").append(minor).append('\n');
1063 buf.append("access flags\t\t").append(super.getAccessFlags()).append('\n');
1064 buf.append("constant pool\t\t").append(constantPool.getLength()).append(" entries\n");
1065 buf.append("ACC_SUPER flag\t\t").append(isSuper()).append("\n");
1066 if (attributes.length > 0) {
1067 buf.append("\nAttribute(s):\n");
1068 for (final Attribute attribute : attributes) {
1069 buf.append(indent(attribute));
1070 }
1071 }
1072 final AnnotationEntry[] annotations = getAnnotationEntries();
1073 if (annotations != null && annotations.length > 0) {
1074 buf.append("\nAnnotation(s):\n");
1075 for (final AnnotationEntry annotation : annotations) {
1076 buf.append(indent(annotation));
1077 }
1078 }
1079 if (fields.length > 0) {
1080 buf.append("\n").append(fields.length).append(" fields:\n");
1081 for (final Field field : fields) {
1082 buf.append("\t").append(field).append('\n');
1083 }
1084 }
1085 if (methods.length > 0) {
1086 buf.append("\n").append(methods.length).append(" methods:\n");
1087 for (final Method method : methods) {
1088 buf.append("\t").append(method).append('\n');
1089 }
1090 }
1091 return buf.toString();
1092 }
1093 }
1094