forked from classgraph/classgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassfile.java
More file actions
2026 lines (1902 loc) · 101 KB
/
Classfile.java
File metadata and controls
2026 lines (1902 loc) · 101 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
/*
* This file is part of ClassGraph.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Luke Hutchison
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.classgraph;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import io.github.classgraph.Scanner.ClassfileScanWorkUnit;
import nonapi.io.github.classgraph.concurrency.WorkQueue;
import nonapi.io.github.classgraph.fileslice.reader.ClassfileReader;
import nonapi.io.github.classgraph.scanspec.ScanSpec;
import nonapi.io.github.classgraph.types.ParseException;
import nonapi.io.github.classgraph.utils.CollectionUtils;
import nonapi.io.github.classgraph.utils.JarUtils;
import nonapi.io.github.classgraph.utils.LogNode;
import nonapi.io.github.classgraph.utils.StringUtils;
/**
* A classfile binary format parser. Implements its own buffering to avoid the overhead of using DataInputStream.
* This class should only be used by a single thread at a time, but can be re-used to scan multiple classfiles in
* sequence, to avoid re-allocating buffer memory.
*/
class Classfile {
/** The {@link ClassfileReader} for the current classfile. */
private ClassfileReader reader;
/** The classpath element that contains this classfile. */
private final ClasspathElement classpathElement;
/** The classpath order. */
private final List<ClasspathElement> classpathOrder;
/** The relative path to the classfile (should correspond to className). */
private final String relativePath;
/** The classfile resource. */
private final Resource classfileResource;
/** The string intern map. */
private final ConcurrentHashMap<String, String> stringInternMap;
/** The name of the class. */
private String className;
/** The minor version of the classfile format. */
private int minorVersion;
/** The major version of the classfile format. */
private int majorVersion;
/** Whether this is an external class. */
private final boolean isExternalClass;
/** The class modifiers. */
private int classModifiers;
/** Whether this class is an interface. */
private boolean isInterface;
/** Whether this class is a record. */
private boolean isRecord;
/** Whether this class is an annotation. */
private boolean isAnnotation;
/** The superclass name. (can be null if no superclass, or if superclass is rejected.) */
private String superclassName;
/** The implemented interfaces. */
private List<String> implementedInterfaces;
/** The class annotations. */
private AnnotationInfoList classAnnotations;
/** The fully qualified name of the defining method. */
private String fullyQualifiedDefiningMethodName;
/** Class containment entries. */
private List<ClassContainment> classContainmentEntries;
/** Annotation default parameter values. */
private AnnotationParameterValueList annotationParamDefaultValues;
/** Referenced class names. */
private Set<String> refdClassNames;
/** The field info list. */
private FieldInfoList fieldInfoList;
/** The method info list. */
private MethodInfoList methodInfoList;
/** The type signature. */
private String typeSignatureStr;
/** The type annotation decorators for the {@link ClassTypeSignature} instance. */
private List<ClassTypeAnnotationDecorator> classTypeAnnotationDecorators;
/** The names of accepted classes found in the classpath while scanning paths within classpath elements. */
private final Set<String> acceptedClassNamesFound;
/**
* The names of external (non-accepted) classes scheduled for extended scanning (where scanning is extended
* upwards to superclasses, interfaces and annotations).
*/
private final Set<String> classNamesScheduledForExtendedScanning;
/** Any additional work units scheduled for scanning. */
private List<ClassfileScanWorkUnit> additionalWorkUnits;
/** The scan spec. */
private final ScanSpec scanSpec;
// -------------------------------------------------------------------------------------------------------------
/** The number of constant pool entries plus one. */
private int cpCount;
/** The byte offset for the beginning of each entry in the constant pool. */
private int[] entryOffset;
/** The tag (type) for each entry in the constant pool. */
private int[] entryTag;
/** The indirection index for String/Class entries in the constant pool. */
private int[] indirectStringRefs;
// -------------------------------------------------------------------------------------------------------------
/** An empty array for the case where there are no annotations. */
private static final AnnotationInfo[] NO_ANNOTATIONS = new AnnotationInfo[0];
// -------------------------------------------------------------------------------------------------------------
/**
* Class containment.
*/
static class ClassContainment {
/** The inner class name. */
public final String innerClassName;
/** The inner class modifier bits. */
public final int innerClassModifierBits;
/** The outer class name. */
public final String outerClassName;
/**
* Constructor.
*
* @param innerClassName
* the inner class name.
* @param innerClassModifierBits
* the inner class modifier bits.
* @param outerClassName
* the outer class name.
*/
public ClassContainment(final String innerClassName, final int innerClassModifierBits,
final String outerClassName) {
this.innerClassName = innerClassName;
this.innerClassModifierBits = innerClassModifierBits;
this.outerClassName = outerClassName;
}
}
// -------------------------------------------------------------------------------------------------------------
/** Thrown when a classfile's contents are not in the correct format. */
static class ClassfileFormatException extends IOException {
/** serialVersionUID. */
static final long serialVersionUID = 1L;
/**
* Constructor.
*
* @param message
* the message
*/
public ClassfileFormatException(final String message) {
super(message);
}
/**
* Constructor.
*
* @param message
* the message
* @param cause
* the cause
*/
public ClassfileFormatException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Speed up exception (stack trace is not needed for this exception).
*
* @return this
*/
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
/** Thrown when a classfile needs to be skipped. */
static class SkipClassException extends IOException {
/** serialVersionUID. */
static final long serialVersionUID = 1L;
/**
* Constructor.
*
* @param message
* the message
*/
public SkipClassException(final String message) {
super(message);
}
/**
* Speed up exception (stack trace is not needed for this exception).
*
* @return this
*/
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Extend scanning to a superclass, interface or annotation.
*
* @param className
* the class name
* @param relationship
* the relationship type
* @param log
* the log
*/
private void scheduleScanningIfExternalClass(final String className, final String relationship,
final LogNode log) {
// Don't scan Object
if (className != null && !className.equals("java.lang.Object")
// Don't schedule a class for scanning that was already found to be accepted
&& !acceptedClassNamesFound.contains(className)
// Only schedule each external class once for scanning, across all threads
&& classNamesScheduledForExtendedScanning.add(className)) {
if (scanSpec.classAcceptReject.isRejected(className)) {
if (log != null) {
log.log("Cannot extend scanning upwards to external " + relationship + " " + className
+ ", since it is rejected");
}
} else {
// Search for the named class' classfile among classpath elements, in classpath order (this is O(N)
// for each class, but there shouldn't be too many cases of extending scanning upwards)
final String classfilePath = JarUtils.classNameToClassfilePath(className);
// First check current classpath element, to avoid iterating through other classpath elements
Resource classResource = classpathElement.getResource(classfilePath);
ClasspathElement foundInClasspathElt = null;
if (classResource != null) {
// Found the classfile in the current classpath element
foundInClasspathElt = classpathElement;
} else {
// Didn't find the classfile in the current classpath element -- iterate through other elements
for (final ClasspathElement classpathOrderElt : classpathOrder) {
if (classpathOrderElt != classpathElement) {
classResource = classpathOrderElt.getResource(classfilePath);
if (classResource != null) {
foundInClasspathElt = classpathOrderElt;
break;
}
}
}
}
if (classResource != null) {
// Found class resource
if (log != null) {
// Log the extended scan as a child LogNode of the current class' scan log, since the
// external class is not scanned at the regular place in the classpath element hierarchy
// traversal
classResource.scanLog = log
.log("Extending scanning to external " + relationship
+ (foundInClasspathElt == classpathElement ? " in same classpath element"
: " in classpath element " + foundInClasspathElt)
+ ": " + className);
}
if (additionalWorkUnits == null) {
additionalWorkUnits = new ArrayList<>();
}
// Schedule class resource for scanning
additionalWorkUnits.add(new ClassfileScanWorkUnit(foundInClasspathElt, classResource,
/* isExternalClass = */ true));
} else {
if (log != null) {
log.log("External " + relationship + " " + className + " was not found in "
+ "non-rejected packages -- cannot extend scanning to this class");
}
}
}
}
}
/**
* Check if scanning needs to be extended upwards from an annotation parameter value.
*
* @param annotationParamVal
* the {@link AnnotationInfo} object for an annotation, or for an annotation parameter value.
* @param log
* the log
*/
private void extendScanningUpwardsFromAnnotationParameterValues(final Object annotationParamVal,
final LogNode log) {
if (annotationParamVal == null) {
// Should not be possible -- ignore
} else if (annotationParamVal instanceof AnnotationInfo) {
final AnnotationInfo annotationInfo = (AnnotationInfo) annotationParamVal;
scheduleScanningIfExternalClass(annotationInfo.getClassName(), "annotation class", log);
for (final AnnotationParameterValue apv : annotationInfo.getParameterValues()) {
extendScanningUpwardsFromAnnotationParameterValues(apv.getValue(), log);
}
} else if (annotationParamVal instanceof AnnotationEnumValue) {
scheduleScanningIfExternalClass(((AnnotationEnumValue) annotationParamVal).getClassName(), "enum class",
log);
} else if (annotationParamVal instanceof AnnotationClassRef) {
scheduleScanningIfExternalClass(((AnnotationClassRef) annotationParamVal).getClassName(), "class ref",
log);
} else if (annotationParamVal.getClass().isArray()) {
for (int i = 0, n = Array.getLength(annotationParamVal); i < n; i++) {
extendScanningUpwardsFromAnnotationParameterValues(Array.get(annotationParamVal, i), log);
}
} else {
// String etc. -- ignore
}
}
/**
* Check if scanning needs to be extended upwards to an external superclass, interface or annotation.
*
* @param log
* the log
*/
private void extendScanningUpwards(final LogNode log) {
// Check superclass
if (superclassName != null) {
scheduleScanningIfExternalClass(superclassName, "superclass", log);
}
// Check implemented interfaces
if (implementedInterfaces != null) {
for (final String interfaceName : implementedInterfaces) {
scheduleScanningIfExternalClass(interfaceName, "interface", log);
}
}
// Check class annotations
if (classAnnotations != null) {
for (final AnnotationInfo annotationInfo : classAnnotations) {
scheduleScanningIfExternalClass(annotationInfo.getName(), "class annotation", log);
extendScanningUpwardsFromAnnotationParameterValues(annotationInfo, log);
}
}
// Check annotation default parameter values
if (annotationParamDefaultValues != null) {
for (final AnnotationParameterValue apv : annotationParamDefaultValues) {
extendScanningUpwardsFromAnnotationParameterValues(apv.getValue(), log);
}
}
// Check method annotations and method parameter annotations
if (methodInfoList != null) {
for (final MethodInfo methodInfo : methodInfoList) {
if (methodInfo.annotationInfo != null) {
for (final AnnotationInfo methodAnnotationInfo : methodInfo.annotationInfo) {
scheduleScanningIfExternalClass(methodAnnotationInfo.getName(), "method annotation", log);
extendScanningUpwardsFromAnnotationParameterValues(methodAnnotationInfo, log);
}
if (methodInfo.parameterAnnotationInfo != null
&& methodInfo.parameterAnnotationInfo.length > 0) {
for (final AnnotationInfo[] paramAnnInfoArr : methodInfo.parameterAnnotationInfo) {
if (paramAnnInfoArr != null && paramAnnInfoArr.length > 0) {
for (final AnnotationInfo paramAnnInfo : paramAnnInfoArr) {
scheduleScanningIfExternalClass(paramAnnInfo.getName(),
"method parameter annotation", log);
extendScanningUpwardsFromAnnotationParameterValues(paramAnnInfo, log);
}
}
}
}
}
}
}
// Check field annotations
if (fieldInfoList != null) {
for (final FieldInfo fieldInfo : fieldInfoList) {
if (fieldInfo.annotationInfo != null) {
for (final AnnotationInfo fieldAnnotationInfo : fieldInfo.annotationInfo) {
scheduleScanningIfExternalClass(fieldAnnotationInfo.getName(), "field annotation", log);
extendScanningUpwardsFromAnnotationParameterValues(fieldAnnotationInfo, log);
}
}
}
}
// Check if this class is an inner class, and if so, extend scanning to outer class
if (classContainmentEntries != null) {
for (final ClassContainment classContainmentEntry : classContainmentEntries) {
if (classContainmentEntry.innerClassName.equals(className)) {
scheduleScanningIfExternalClass(classContainmentEntry.outerClassName, "outer class", log);
}
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Link classes. Not threadsafe, should be run in a single-threaded context.
*
* @param classNameToClassInfo
* map from class name to class info
* @param packageNameToPackageInfo
* map from package name to package info
* @param moduleNameToModuleInfo
* map from module name to module info
*/
void link(final Map<String, ClassInfo> classNameToClassInfo,
final Map<String, PackageInfo> packageNameToPackageInfo,
final Map<String, ModuleInfo> moduleNameToModuleInfo) {
boolean isModuleDescriptor = false;
boolean isPackageDescriptor = false;
ClassInfo classInfo = null;
if (className.equals("module-info")) {
isModuleDescriptor = true;
} else if (className.equals("package-info") || className.endsWith(".package-info")) {
isPackageDescriptor = true;
} else {
// Handle regular classfile
classInfo = ClassInfo.addScannedClass(className, classModifiers, isExternalClass, classNameToClassInfo,
classpathElement, classfileResource);
classInfo.setClassfileVersion(minorVersion, majorVersion);
classInfo.setModifiers(classModifiers);
classInfo.setIsInterface(isInterface);
classInfo.setIsAnnotation(isAnnotation);
classInfo.setIsRecord(isRecord);
if (superclassName != null) {
classInfo.addSuperclass(superclassName, classNameToClassInfo);
}
if (implementedInterfaces != null) {
for (final String interfaceName : implementedInterfaces) {
classInfo.addImplementedInterface(interfaceName, classNameToClassInfo);
}
}
if (classAnnotations != null) {
for (final AnnotationInfo classAnnotation : classAnnotations) {
classInfo.addClassAnnotation(classAnnotation, classNameToClassInfo);
}
}
if (classContainmentEntries != null) {
ClassInfo.addClassContainment(classContainmentEntries, classNameToClassInfo);
}
if (annotationParamDefaultValues != null) {
classInfo.addAnnotationParamDefaultValues(annotationParamDefaultValues);
}
if (fullyQualifiedDefiningMethodName != null) {
classInfo.addFullyQualifiedDefiningMethodName(fullyQualifiedDefiningMethodName);
}
if (fieldInfoList != null) {
classInfo.addFieldInfo(fieldInfoList, classNameToClassInfo);
}
if (methodInfoList != null) {
classInfo.addMethodInfo(methodInfoList, classNameToClassInfo);
}
if (typeSignatureStr != null) {
classInfo.setTypeSignature(typeSignatureStr);
}
if (refdClassNames != null) {
classInfo.addReferencedClassNames(refdClassNames);
}
if (classTypeAnnotationDecorators != null) {
classInfo.addTypeDecorators(classTypeAnnotationDecorators);
}
}
// Get or create PackageInfo, if this is not a module descriptor (the module descriptor's package is "")
PackageInfo packageInfo = null;
if (!isModuleDescriptor) {
// Get package for this class or package descriptor
final String packageName = PackageInfo.getParentPackageName(className);
packageInfo = PackageInfo.getOrCreatePackage(packageName, packageNameToPackageInfo);
if (isPackageDescriptor) {
// Add any class annotations on the package-info.class file to the ModuleInfo
packageInfo.addAnnotations(classAnnotations);
} else if (classInfo != null) {
// Add ClassInfo to PackageInfo, and vice versa
packageInfo.addClassInfo(classInfo);
classInfo.packageInfo = packageInfo;
}
}
// Get or create ModuleInfo, if there is a module name
final String moduleName = classpathElement.getModuleName();
if (moduleName != null) {
// Get or create a ModuleInfo object for this module
ModuleInfo moduleInfo = moduleNameToModuleInfo.get(moduleName);
if (moduleInfo == null) {
moduleNameToModuleInfo.put(moduleName,
moduleInfo = new ModuleInfo(classfileResource.getModuleRef(), classpathElement));
}
if (isModuleDescriptor) {
// Add any class annotations on the module-info.class file to the ModuleInfo
moduleInfo.addAnnotations(classAnnotations);
}
if (classInfo != null) {
// Add ClassInfo to ModuleInfo, and vice versa
moduleInfo.addClassInfo(classInfo);
classInfo.moduleInfo = moduleInfo;
}
if (packageInfo != null) {
// Add PackageInfo to ModuleInfo
moduleInfo.addPackageInfo(packageInfo);
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Intern a string.
*
* @param str
* the str
* @return the string
*/
private String intern(final String str) {
if (str == null) {
return null;
}
final String interned = stringInternMap.putIfAbsent(str, str);
if (interned != null) {
return interned;
}
return str;
}
/**
* Get the byte offset within the buffer of a string from the constant pool, or 0 for a null string.
*
* @param cpIdx
* the constant pool index
* @param subFieldIdx
* should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for
* CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1.
* @return the constant pool string offset
* @throws ClassfileFormatException
* If a problem is detected
*/
private int getConstantPoolStringOffset(final int cpIdx, final int subFieldIdx)
throws ClassfileFormatException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
final int t = entryTag[cpIdx];
if ((t != 12 && subFieldIdx != 0) || (t == 12 && subFieldIdx != 0 && subFieldIdx != 1)) {
throw new ClassfileFormatException(
"Bad subfield index " + subFieldIdx + " for tag " + t + ", cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
int cpIdxToUse;
if (t == 0) {
// Assume this means null
return 0;
} else if (t == 1) {
// CONSTANT_Utf8
cpIdxToUse = cpIdx;
} else if (t == 7 || t == 8 || t == 19) {
// t == 7 => CONSTANT_Class, e.g. "[[I", "[Ljava/lang/Thread;"; t == 8 => CONSTANT_String;
// t == 19 => CONSTANT_Method_Info
final int indirIdx = indirectStringRefs[cpIdx];
if (indirIdx == -1) {
// Should not happen
throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
if (indirIdx == 0) {
// I assume this represents a null string, since the zeroeth entry is unused
return 0;
}
cpIdxToUse = indirIdx;
} else if (t == 12) {
// CONSTANT_NameAndType_info
final int compoundIndirIdx = indirectStringRefs[cpIdx];
if (compoundIndirIdx == -1) {
// Should not happen
throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
final int indirIdx = (subFieldIdx == 0 ? (compoundIndirIdx >> 16) : compoundIndirIdx) & 0xffff;
if (indirIdx == 0) {
// Should not happen
throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
cpIdxToUse = indirIdx;
} else {
throw new ClassfileFormatException("Wrong tag number " + t + " at constant pool index " + cpIdx + ", "
+ "cannot continue reading class. Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
}
if (cpIdxToUse < 1 || cpIdxToUse >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return entryOffset[cpIdxToUse];
}
/**
* Get a string from the constant pool, optionally replacing '/' with '.'.
*
* @param cpIdx
* the constant pool index
* @param replaceSlashWithDot
* if true, replace slash with dot in the result.
* @param stripLSemicolon
* if true, strip 'L' from the beginning and ';' from the end before returning (for class reference
* constants)
* @return the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolString(final int cpIdx, final boolean replaceSlashWithDot,
final boolean stripLSemicolon) throws ClassfileFormatException, IOException {
final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0);
if (constantPoolStringOffset == 0) {
return null;
}
final int utfLen = reader.readUnsignedShort(constantPoolStringOffset);
if (utfLen == 0) {
return "";
}
return intern(
reader.readString(constantPoolStringOffset + 2L, utfLen, replaceSlashWithDot, stripLSemicolon));
}
/**
* Get a string from the constant pool.
*
* @param cpIdx
* the constant pool index
* @param subFieldIdx
* should be 0 for CONSTANT_Utf8, CONSTANT_Class and CONSTANT_String, and for
* CONSTANT_NameAndType_info, fetches the name for value 0, or the type descriptor for value 1.
* @return the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolString(final int cpIdx, final int subFieldIdx)
throws ClassfileFormatException, IOException {
final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, subFieldIdx);
if (constantPoolStringOffset == 0) {
return null;
}
final int utfLen = reader.readUnsignedShort(constantPoolStringOffset);
if (utfLen == 0) {
return "";
}
return intern(reader.readString(constantPoolStringOffset + 2L, utfLen, /* replaceSlashWithDot = */ false,
/* stripLSemicolon = */ false));
}
/**
* Get a string from the constant pool.
*
* @param cpIdx
* the constant pool index
* @return the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolString(final int cpIdx) throws ClassfileFormatException, IOException {
return getConstantPoolString(cpIdx, /* subFieldIdx = */ 0);
}
/**
* Get the first UTF8 byte of a string in the constant pool, or '\0' if the string is null or empty.
*
* @param cpIdx
* the constant pool index
* @return the first byte of the constant pool string
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private byte getConstantPoolStringFirstByte(final int cpIdx) throws ClassfileFormatException, IOException {
final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0);
if (constantPoolStringOffset == 0) {
return '\0';
}
final int utfLen = reader.readUnsignedShort(constantPoolStringOffset);
if (utfLen == 0) {
return '\0';
}
return reader.readByte(constantPoolStringOffset + 2L);
}
/**
* Get a string from the constant pool, and interpret it as a class name by replacing '/' with '.'.
*
* @param cpIdx
* the constant pool index
* @return the constant pool class name
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolClassName(final int cpIdx) throws ClassfileFormatException, IOException {
return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ false);
}
/**
* Get a string from the constant pool representing an internal string descriptor for a class name
* ("Lcom/xyz/MyClass;"), and interpret it as a class name by replacing '/' with '.', and removing the leading
* "L" and the trailing ";".
*
* @param cpIdx
* the constant pool index
* @return the constant pool class descriptor
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private String getConstantPoolClassDescriptor(final int cpIdx) throws ClassfileFormatException, IOException {
return getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true, /* stripLSemicolon = */ true);
}
/**
* Compare a string in the constant pool with a given ASCII string, without constructing the constant pool
* String object.
*
* @param cpIdx
* the constant pool index
* @param asciiStr
* the ASCII string to compare to
* @return true, if successful
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private boolean constantPoolStringEquals(final int cpIdx, final String asciiStr)
throws ClassfileFormatException, IOException {
final int cpStrOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0);
if (cpStrOffset == 0) {
return asciiStr == null;
} else if (asciiStr == null) {
return false;
}
final int cpStrLen = reader.readUnsignedShort(cpStrOffset);
final int asciiStrLen = asciiStr.length();
if (cpStrLen != asciiStrLen) {
return false;
}
final int cpStrStart = cpStrOffset + 2;
reader.bufferTo(cpStrStart + cpStrLen);
final byte[] buf = reader.buf();
for (int i = 0; i < cpStrLen; i++) {
if ((char) (buf[cpStrStart + i] & 0xff) != asciiStr.charAt(i)) {
return false;
}
}
return true;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Read an unsigned short from the constant pool.
*
* @param cpIdx
* the constant pool index.
* @return the unsigned short
* @throws IOException
* If an I/O exception occurred.
*/
private int cpReadUnsignedShort(final int cpIdx) throws IOException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return reader.readUnsignedShort(entryOffset[cpIdx]);
}
/**
* Read an int from the constant pool.
*
* @param cpIdx
* the constant pool index.
* @return the int
* @throws IOException
* If an I/O exception occurred.
*/
private int cpReadInt(final int cpIdx) throws IOException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return reader.readInt(entryOffset[cpIdx]);
}
/**
* Read a long from the constant pool.
*
* @param cpIdx
* the constant pool index.
* @return the long
* @throws IOException
* If an I/O exception occurred.
*/
private long cpReadLong(final int cpIdx) throws IOException {
if (cpIdx < 1 || cpIdx >= cpCount) {
throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, "
+ (cpCount - 1) + "] -- cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
return reader.readLong(entryOffset[cpIdx]);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get a field constant from the constant pool.
*
* @param tag
* the tag
* @param fieldTypeDescriptorFirstChar
* the first char of the field type descriptor
* @param cpIdx
* the constant pool index
* @return the field constant pool value
* @throws ClassfileFormatException
* If a problem occurs.
* @throws IOException
* If an IO exception occurs.
*/
private Object getFieldConstantPoolValue(final int tag, final char fieldTypeDescriptorFirstChar,
final int cpIdx) throws ClassfileFormatException, IOException {
switch (tag) {
case 1: // Modified UTF8
case 7: // Class -- N.B. Unused? Class references do not seem to actually be stored as constant initalizers
case 8: // String
// Forward or backward indirect reference to a modified UTF8 entry
return getConstantPoolString(cpIdx);
case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER
final int intVal = cpReadInt(cpIdx);
switch (fieldTypeDescriptorFirstChar) {
case 'I':
return intVal;
case 'S':
return (short) intVal;
case 'C':
return (char) intVal;
case 'B':
return (byte) intVal;
case 'Z':
return intVal != 0;
default:
// Fall through
}
throw new ClassfileFormatException("Unknown Constant_INTEGER type " + fieldTypeDescriptorFirstChar
+ ", " + "cannot continue reading class. Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
case 4: // float
return Float.intBitsToFloat(cpReadInt(cpIdx));
case 5: // long
return cpReadLong(cpIdx);
case 6: // double
return Double.longBitsToDouble(cpReadLong(cpIdx));
default:
// ClassGraph doesn't expect other types
// (N.B. in particular, enum values are not stored in the constant pool, so don't need to be handled)
throw new ClassfileFormatException("Unknown constant pool tag " + tag + ", "
+ "cannot continue reading class. Please report this at "
+ "https://github.com/classgraph/classgraph/issues");
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Read annotation entry from classfile.
*
* @return the annotation, as an {@link AnnotationInfo} object.
* @throws IOException
* If an IO exception occurs.
*/
private AnnotationInfo readAnnotation() throws IOException {
// Lcom/xyz/Annotation; -> Lcom.xyz.Annotation;
final String annotationClassName = getConstantPoolClassDescriptor(reader.readUnsignedShort());
final int numElementValuePairs = reader.readUnsignedShort();
AnnotationParameterValueList paramVals = null;
if (numElementValuePairs > 0) {
paramVals = new AnnotationParameterValueList(numElementValuePairs);
for (int i = 0; i < numElementValuePairs; i++) {
final String paramName = getConstantPoolString(reader.readUnsignedShort());
final Object paramValue = readAnnotationElementValue();
paramVals.add(new AnnotationParameterValue(paramName, paramValue));
}
}
return new AnnotationInfo(annotationClassName, paramVals);
}
/**
* Read annotation element value from classfile.
*
* @return the annotation element value
* @throws IOException
* If an IO exception occurs.
*/
private Object readAnnotationElementValue() throws IOException {
final int tag = (char) reader.readUnsignedByte();
switch (tag) {
case 'B':
return (byte) cpReadInt(reader.readUnsignedShort());
case 'C':
return (char) cpReadInt(reader.readUnsignedShort());
case 'D':
return Double.longBitsToDouble(cpReadLong(reader.readUnsignedShort()));
case 'F':
return Float.intBitsToFloat(cpReadInt(reader.readUnsignedShort()));
case 'I':
return cpReadInt(reader.readUnsignedShort());
case 'J':
return cpReadLong(reader.readUnsignedShort());
case 'S':
return (short) cpReadUnsignedShort(reader.readUnsignedShort());
case 'Z':
return cpReadInt(reader.readUnsignedShort()) != 0;
case 's':
return getConstantPoolString(reader.readUnsignedShort());
case 'e': {
// Return type is AnnotationEnumVal.
final String annotationClassName = getConstantPoolClassDescriptor(reader.readUnsignedShort());
final String annotationConstName = getConstantPoolString(reader.readUnsignedShort());
return new AnnotationEnumValue(annotationClassName, annotationConstName);
}
case 'c':
// Return type is AnnotationClassRef (for class references in annotations)
final String classRefTypeDescriptor = getConstantPoolString(reader.readUnsignedShort());
return new AnnotationClassRef(classRefTypeDescriptor);
case '@':