forked from eclipse-jdt/eclipse.jdt.core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClassFile.java
7951 lines (7613 loc) · 330 KB
/
ClassFile.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
/*******************************************************************************
* Copyright (c) 2000, 2023 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Jesper S Moller - Contributions for
* Bug 405066 - [1.8][compiler][codegen] Implement code generation infrastructure for JSR335
* Bug 406982 - [1.8][compiler] Generation of MethodParameters Attribute in classfile
* Bug 416885 - [1.8][compiler]IncompatibleClassChange error (edit)
* Bug 412149 - [1.8][compiler] Emit repeated annotations into the designated container
* Andy Clement (GoPivotal, Inc) aclement@gopivotal.com - Contributions for
* Bug 383624 - [1.8][compiler] Revive code generation support for type annotations (from Olivier's work)
* Bug 409236 - [1.8][compiler] Type annotations on intersection cast types dropped by code generator
* Bug 409246 - [1.8][compiler] Type annotations on catch parameters not handled properly
* Bug 415541 - [1.8][compiler] Type annotations in the body of static initializer get dropped
* Bug 415399 - [1.8][compiler] Type annotations on constructor results dropped by the code generator
* Bug 415470 - [1.8][compiler] Type annotations on class declaration go vanishing
* Bug 405104 - [1.8][compiler][codegen] Implement support for serializeable lambdas
* Bug 434556 - Broken class file generated for incorrect annotation usage
* Bug 442416 - $deserializeLambda$ missing cases for nested lambdas
* Stephan Herrmann - Contribution for
* Bug 438458 - [1.8][null] clean up handling of null type annotations wrt type variables
* Olivier Tardieu tardieu@us.ibm.com - Contributions for
* Bug 442416 - $deserializeLambda$ missing cases for nested lambdas
*******************************************************************************/
package org.eclipse.jdt.internal.compiler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.eclipse.jdt.core.compiler.CategorizedProblem;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer;
import org.eclipse.jdt.internal.compiler.ast.CaseStatement;
import org.eclipse.jdt.internal.compiler.ast.CaseStatement.ResolvedCase;
import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ExportsStatement;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FunctionalExpression;
import org.eclipse.jdt.internal.compiler.ast.LambdaExpression;
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
import org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ModuleDeclaration;
import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
import org.eclipse.jdt.internal.compiler.ast.OpensStatement;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.Receiver;
import org.eclipse.jdt.internal.compiler.ast.RecordComponent;
import org.eclipse.jdt.internal.compiler.ast.ReferenceExpression;
import org.eclipse.jdt.internal.compiler.ast.RequiresStatement;
import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.eclipse.jdt.internal.compiler.ast.StringTemplate;
import org.eclipse.jdt.internal.compiler.ast.SwitchStatement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.codegen.AnnotationContext;
import org.eclipse.jdt.internal.compiler.codegen.AnnotationTargetTypeConstants;
import org.eclipse.jdt.internal.compiler.codegen.AttributeNamesConstants;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.ConstantPool;
import org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel;
import org.eclipse.jdt.internal.compiler.codegen.Opcodes;
import org.eclipse.jdt.internal.compiler.codegen.StackMapFrame;
import org.eclipse.jdt.internal.compiler.codegen.StackMapFrameCodeStream;
import org.eclipse.jdt.internal.compiler.codegen.StackMapFrameCodeStream.ExceptionMarker;
import org.eclipse.jdt.internal.compiler.codegen.TypeAnnotationCodeStream;
import org.eclipse.jdt.internal.compiler.codegen.VerificationTypeInfo;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.impl.StringConstant;
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.lookup.ModuleBinding;
import org.eclipse.jdt.internal.compiler.lookup.PolymorphicMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.RecordComponentBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticArgumentBinding;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TagBits;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
import org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.eclipse.jdt.internal.compiler.problem.AbortMethod;
import org.eclipse.jdt.internal.compiler.problem.AbortType;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
import org.eclipse.jdt.internal.compiler.problem.ShouldNotImplement;
import org.eclipse.jdt.internal.compiler.util.Messages;
import org.eclipse.jdt.internal.compiler.util.Util;
/**
* Represents a class file wrapper on bytes, it is aware of its actual
* type name.
*
* Public APIs are listed below:
*
* byte[] getBytes();
* Answer the actual bytes of the class file
*
* char[][] getCompoundName();
* Answer the compound name of the class file.
* For example, {{java}, {util}, {Hashtable}}.
*
* byte[] getReducedBytes();
* Answer a smaller byte format, which is only contains some structural
* information. Those bytes are decodable with a regular class file reader,
* such as DietClassFileReader
*/
public class ClassFile implements TypeConstants, TypeIds {
private byte[] bytes;
public CodeStream codeStream;
public ConstantPool constantPool;
public int constantPoolOffset;
// the header contains all the bytes till the end of the constant pool
public byte[] contents;
public int contentsOffset;
protected boolean creatingProblemType;
public ClassFile enclosingClassFile;
public byte[] header;
// that collection contains all the remaining bytes of the .class file
public int headerOffset;
public Map<TypeBinding, Boolean> innerClassesBindings;
public Set<SourceTypeBinding> nestMembers;
public List<Object> bootstrapMethods = null;
public int methodCount;
public int methodCountOffset;
// pool managment
boolean isShared = false;
// used to generate private access methods
// debug and stack map attributes
public int produceAttributes;
public SourceTypeBinding referenceBinding;
public boolean isNestedType;
public long targetJDK;
public List<TypeBinding> missingTypes = null;
public Set<TypeBinding> visitedTypes;
public static final int INITIAL_CONTENTS_SIZE = 400;
public static final int INITIAL_HEADER_SIZE = 1500;
public static final int INNER_CLASSES_SIZE = 5;
public static final int NESTED_MEMBER_SIZE = 5;
// TODO: Move these to an enum?
public static final String ALTMETAFACTORY_STRING = new String(ConstantPool.ALTMETAFACTORY);
public static final String METAFACTORY_STRING = new String(ConstantPool.METAFACTORY);
public static final String BOOTSTRAP_STRING = new String(ConstantPool.BOOTSTRAP);
public static final String TYPESWITCH_STRING = new String(ConstantPool.TYPESWITCH);
public static final String ENUMSWITCH_STRING = new String(ConstantPool.ENUMSWITCH);
public static final String CONCAT_CONSTANTS = new String(ConstantPool.ConcatWithConstants);
public static final String INVOKE_STRING = new String(ConstantPool.INVOKE_METHOD_METHOD_NAME);
public static final String ENUMDESC_OF = "EnumDesc.of"; //$NON-NLS-1$
public static final String CLASSDESC = "ClassDesc"; //$NON-NLS-1$
public static final String CLASSDESC_OF = "ClassDesc.of"; //$NON-NLS-1$
public static final String PROCESS_STRING = "process"; //$NON-NLS-1$
public static final String NEW_STRING_TEMPLATE = "newStringTemplate"; //$NON-NLS-1$
public static final String[] BOOTSTRAP_METHODS = { ALTMETAFACTORY_STRING, METAFACTORY_STRING, BOOTSTRAP_STRING,
TYPESWITCH_STRING, ENUMSWITCH_STRING, CONCAT_CONSTANTS, INVOKE_STRING, ENUMDESC_OF, CLASSDESC, CLASSDESC_OF, PROCESS_STRING, NEW_STRING_TEMPLATE};
/**
* INTERNAL USE-ONLY
* Request the creation of a ClassFile compatible representation of a problematic type
*
* @param typeDeclaration org.eclipse.jdt.internal.compiler.ast.TypeDeclaration
* @param unitResult org.eclipse.jdt.internal.compiler.CompilationUnitResult
*/
public static void createProblemType(TypeDeclaration typeDeclaration, CompilationResult unitResult) {
createProblemType(typeDeclaration, null, unitResult);
}
private static void createProblemType(TypeDeclaration typeDeclaration, ClassFile parentClassFile, CompilationResult unitResult) {
SourceTypeBinding typeBinding = typeDeclaration.binding;
ClassFile classFile = ClassFile.getNewInstance(typeBinding);
classFile.initialize(typeBinding, parentClassFile, true);
if (typeBinding.hasMemberTypes()) {
// see bug 180109
ReferenceBinding[] members = typeBinding.memberTypes;
for (ReferenceBinding member : members)
classFile.recordInnerClasses(member);
}
// TODO (olivier) handle cases where a field cannot be generated (name too long)
// TODO (olivier) handle too many methods
// inner attributes
if (typeBinding.isNestedType()) {
classFile.recordInnerClasses(typeBinding);
}
TypeVariableBinding[] typeVariables = typeBinding.typeVariables();
for (TypeVariableBinding typeVariableBinding : typeVariables) {
if ((typeVariableBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0) {
Util.recordNestedType(classFile, typeVariableBinding);
}
}
// add its fields
FieldBinding[] fields = typeBinding.fields();
if ((fields != null) && (fields != Binding.NO_FIELDS)) {
classFile.addFieldInfos();
} else {
// we have to set the number of fields to be equals to 0
if (classFile.contentsOffset + 2 >= classFile.contents.length) {
classFile.resizeContents(2);
}
classFile.contents[classFile.contentsOffset++] = 0;
classFile.contents[classFile.contentsOffset++] = 0;
}
// leave some space for the methodCount
classFile.setForMethodInfos();
// add its user defined methods
int problemsLength;
CategorizedProblem[] problems = unitResult.getErrors();
if (problems == null) {
problems = new CategorizedProblem[0];
}
CategorizedProblem[] problemsCopy = new CategorizedProblem[problemsLength = problems.length];
System.arraycopy(problems, 0, problemsCopy, 0, problemsLength);
AbstractMethodDeclaration[] methodDecls = typeDeclaration.methods;
boolean abstractMethodsOnly = false;
if (methodDecls != null) {
if (typeBinding.isInterface()) {
if (typeBinding.scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_8)
abstractMethodsOnly = true;
// We generate a clinit which contains all the problems, since we may not be able to generate problem methods (< 1.8) and problem constructors (all levels).
classFile.addProblemClinit(problemsCopy);
}
for (AbstractMethodDeclaration methodDecl : methodDecls) {
MethodBinding method = methodDecl.binding;
if (method == null) continue;
if (abstractMethodsOnly) {
method.modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccAbstract;
}
if (method.isConstructor()) {
if (typeBinding.isInterface()) continue;
classFile.addProblemConstructor(methodDecl, method, problemsCopy);
} else if (method.isAbstract()) {
classFile.addAbstractMethod(methodDecl, method);
} else {
classFile.addProblemMethod(methodDecl, method, problemsCopy);
}
}
// add abstract methods
classFile.addDefaultAbstractMethods();
}
// propagate generation of (problem) member types
if (typeDeclaration.memberTypes != null) {
for (TypeDeclaration memberType : typeDeclaration.memberTypes) {
if (memberType.binding != null) {
ClassFile.createProblemType(memberType, classFile, unitResult);
}
}
}
classFile.addAttributes();
unitResult.record(typeBinding.constantPoolName(), classFile);
}
public static ClassFile getNewInstance(SourceTypeBinding typeBinding) {
LookupEnvironment env = typeBinding.scope.environment();
return env.classFilePool.acquire(typeBinding);
}
/**
* INTERNAL USE-ONLY
* This methods creates a new instance of the receiver.
*/
protected ClassFile() {
// default constructor for subclasses
}
public ClassFile(SourceTypeBinding typeBinding) {
// default constructor for subclasses
this.constantPool = new ConstantPool(this);
final CompilerOptions options = typeBinding.scope.compilerOptions();
this.targetJDK = options.targetJDK;
this.produceAttributes = options.produceDebugAttributes;
this.referenceBinding = typeBinding;
this.isNestedType = typeBinding.isNestedType();
if (this.targetJDK >= ClassFileConstants.JDK1_6) {
this.produceAttributes |= ClassFileConstants.ATTR_STACK_MAP_TABLE;
if (this.targetJDK >= ClassFileConstants.JDK1_8) {
this.produceAttributes |= ClassFileConstants.ATTR_TYPE_ANNOTATION;
this.codeStream = new TypeAnnotationCodeStream(this);
if (options.produceMethodParameters) {
this.produceAttributes |= ClassFileConstants.ATTR_METHOD_PARAMETERS;
}
} else {
this.codeStream = new StackMapFrameCodeStream(this);
}
} else if (this.targetJDK == ClassFileConstants.CLDC_1_1) {
this.targetJDK = ClassFileConstants.JDK1_1; // put back 45.3
this.produceAttributes |= ClassFileConstants.ATTR_STACK_MAP;
this.codeStream = new StackMapFrameCodeStream(this);
} else {
this.codeStream = new CodeStream(this);
}
initByteArrays(this.referenceBinding.methods().length + this.referenceBinding.fields().length);
}
public ClassFile(ModuleBinding moduleBinding, CompilerOptions options) {
this.constantPool = new ConstantPool(this);
this.targetJDK = options.targetJDK;
this.produceAttributes = ClassFileConstants.ATTR_SOURCE;
this.isNestedType = false;
this.codeStream = new StackMapFrameCodeStream(this);
initByteArrays(0);
}
/**
* INTERNAL USE-ONLY
* Generate the byte for a problem method info that correspond to a bogus method.
*
* @param method org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration
* @param methodBinding org.eclipse.jdt.internal.compiler.nameloopkup.MethodBinding
*/
public void addAbstractMethod(
AbstractMethodDeclaration method,
MethodBinding methodBinding) {
this.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = this.contentsOffset;
int attributeNumber = this.generateMethodInfoAttributes(methodBinding);
completeMethodInfo(methodBinding, methodAttributeOffset, attributeNumber);
}
/**
* INTERNAL USE-ONLY
* This methods generate all the attributes for the receiver.
* For a class they could be:
* - source file attribute
* - inner classes attribute
* - deprecated attribute
*/
public void addAttributes() {
// update the method count
this.contents[this.methodCountOffset++] = (byte) (this.methodCount >> 8);
this.contents[this.methodCountOffset] = (byte) this.methodCount;
int attributesNumber = 0;
// leave two bytes for the number of attributes and store the current offset
int attributeOffset = this.contentsOffset;
this.contentsOffset += 2;
// source attribute
if ((this.produceAttributes & ClassFileConstants.ATTR_SOURCE) != 0) {
String fullFileName =
new String(this.referenceBinding.scope.referenceCompilationUnit().getFileName());
fullFileName = fullFileName.replace('\\', '/');
int lastIndex = fullFileName.lastIndexOf('/');
if (lastIndex != -1) {
fullFileName = fullFileName.substring(lastIndex + 1, fullFileName.length());
}
attributesNumber += generateSourceAttribute(fullFileName);
}
// Deprecated attribute
if (this.referenceBinding.isDeprecated()) {
// check that there is enough space to write all the bytes for the field info corresponding
// to the @fieldBinding
attributesNumber += generateDeprecatedAttribute();
}
// add signature attribute
char[] genericSignature = this.referenceBinding.genericSignature();
if (genericSignature != null) {
attributesNumber += generateSignatureAttribute(genericSignature);
}
if (this.targetJDK >= ClassFileConstants.JDK1_5
&& this.referenceBinding.isNestedType()
&& !this.referenceBinding.isMemberType()) {
// add enclosing method attribute (1.5 mode only)
attributesNumber += generateEnclosingMethodAttribute();
}
if (this.targetJDK >= ClassFileConstants.JDK1_4) {
TypeDeclaration typeDeclaration = this.referenceBinding.scope.referenceContext;
if (typeDeclaration != null) {
final Annotation[] annotations = typeDeclaration.annotations;
if (annotations != null) {
long targetMask;
if (typeDeclaration.isPackageInfo())
targetMask = TagBits.AnnotationForPackage;
else if (this.referenceBinding.isAnnotationType())
targetMask = TagBits.AnnotationForType | TagBits.AnnotationForAnnotationType;
else
targetMask = TagBits.AnnotationForType | TagBits.AnnotationForTypeUse; // 9.7.4 ... applicable to type declarations or in type contexts
attributesNumber += generateRuntimeAnnotations(annotations, targetMask);
}
}
}
if (this.referenceBinding.isHierarchyInconsistent()) {
ReferenceBinding superclass = this.referenceBinding.superclass;
if (superclass != null) {
this.missingTypes = superclass.collectMissingTypes(this.missingTypes);
}
ReferenceBinding[] superInterfaces = this.referenceBinding.superInterfaces();
for (ReferenceBinding superInterface : superInterfaces) {
this.missingTypes = superInterface.collectMissingTypes(this.missingTypes);
}
attributesNumber += generateHierarchyInconsistentAttribute();
}
// Functional expression, lambda bootstrap methods and record bootstrap methods
if (this.bootstrapMethods != null && !this.bootstrapMethods.isEmpty()) {
attributesNumber += generateBootstrapMethods(this.bootstrapMethods);
}
if (this.targetJDK >= ClassFileConstants.JDK17) {
// add record attributes
attributesNumber += generatePermittedTypeAttributes();
}
// Inner class attribute
int numberOfInnerClasses = this.innerClassesBindings == null ? 0 : this.innerClassesBindings.size();
if (numberOfInnerClasses != 0) {
ReferenceBinding[] innerClasses = new ReferenceBinding[numberOfInnerClasses];
this.innerClassesBindings.keySet().toArray(innerClasses);
Arrays.sort(innerClasses, new Comparator<ReferenceBinding>() {
@Override
public int compare(ReferenceBinding o1, ReferenceBinding o2) {
Boolean onBottom1 = ClassFile.this.innerClassesBindings.get(o1);
Boolean onBottom2 = ClassFile.this.innerClassesBindings.get(o2);
if (onBottom1) {
if (!onBottom2) {
return 1;
}
} else {
if (onBottom2) {
return -1;
}
}
return CharOperation.compareTo(o1.constantPoolName(), o2.constantPoolName());
}
});
attributesNumber += generateInnerClassAttribute(numberOfInnerClasses, innerClasses);
}
if (this.missingTypes != null) {
generateMissingTypesAttribute();
attributesNumber++;
}
attributesNumber += generateTypeAnnotationAttributeForTypeDeclaration();
if (this.targetJDK >= ClassFileConstants.JDK11) {
// add nestMember and nestHost attributes
attributesNumber += generateNestAttributes();
}
if (this.targetJDK >= ClassFileConstants.JDK14) {
// add record attributes
attributesNumber += generateRecordAttributes();
}
// update the number of attributes
if (attributeOffset + 2 >= this.contents.length) {
resizeContents(2);
}
this.contents[attributeOffset++] = (byte) (attributesNumber >> 8);
this.contents[attributeOffset] = (byte) attributesNumber;
// resynchronize all offsets of the classfile
this.header = this.constantPool.poolContent;
this.headerOffset = this.constantPool.currentOffset;
int constantPoolCount = this.constantPool.currentIndex;
this.header[this.constantPoolOffset++] = (byte) (constantPoolCount >> 8);
this.header[this.constantPoolOffset] = (byte) constantPoolCount;
}
/**
* INTERNAL USE-ONLY
* This methods generate all the module attributes for the receiver.
*/
public void addModuleAttributes(ModuleBinding module, Annotation[] annotations, CompilationUnitDeclaration cud) {
int attributesNumber = 0;
// leave two bytes for the number of attributes and store the current offset
int attributeOffset = this.contentsOffset;
this.contentsOffset += 2;
// source attribute
if ((this.produceAttributes & ClassFileConstants.ATTR_SOURCE) != 0) {
String fullFileName =
new String(cud.getFileName());
fullFileName = fullFileName.replace('\\', '/');
int lastIndex = fullFileName.lastIndexOf('/');
if (lastIndex != -1) {
fullFileName = fullFileName.substring(lastIndex + 1, fullFileName.length());
}
attributesNumber += generateSourceAttribute(fullFileName);
}
attributesNumber += generateModuleAttribute(cud.moduleDeclaration);
if (annotations != null) {
long targetMask = TagBits.AnnotationForModule;
attributesNumber += generateRuntimeAnnotations(annotations, targetMask);
}
char[] mainClass = cud.moduleDeclaration.binding.mainClassName;
if (mainClass != null) {
attributesNumber += generateModuleMainClassAttribute(CharOperation.replaceOnCopy(mainClass, '.', '/'));
}
char[][] packageNames = cud.moduleDeclaration.binding.getPackageNamesForClassFile();
if (packageNames != null) {
attributesNumber += generateModulePackagesAttribute(packageNames);
}
// update the number of attributes
if (attributeOffset + 2 >= this.contents.length) {
resizeContents(2);
}
this.contents[attributeOffset++] = (byte) (attributesNumber >> 8);
this.contents[attributeOffset] = (byte) attributesNumber;
// resynchronize all offsets of the classfile
this.header = this.constantPool.poolContent;
this.headerOffset = this.constantPool.currentOffset;
int constantPoolCount = this.constantPool.currentIndex;
this.header[this.constantPoolOffset++] = (byte) (constantPoolCount >> 8);
this.header[this.constantPoolOffset] = (byte) constantPoolCount;
}
/**
* INTERNAL USE-ONLY
* This methods generate all the default abstract method infos that correpond to
* the abstract methods inherited from superinterfaces.
*/
public void addDefaultAbstractMethods() { // default abstract methods
MethodBinding[] defaultAbstractMethods =
this.referenceBinding.getDefaultAbstractMethods();
for (MethodBinding methodBinding : defaultAbstractMethods) {
generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = this.contentsOffset;
int attributeNumber = generateMethodInfoAttributes(methodBinding);
completeMethodInfo(methodBinding, methodAttributeOffset, attributeNumber);
}
}
private int addFieldAttributes(FieldBinding fieldBinding, int fieldAttributeOffset) {
int attributesNumber = 0;
// 4.7.2 only static constant fields get a ConstantAttribute
// Generate the constantValueAttribute
Constant fieldConstant = fieldBinding.constant();
if (fieldConstant != Constant.NotAConstant){
attributesNumber += generateConstantValueAttribute(fieldConstant, fieldBinding, fieldAttributeOffset);
}
if (this.targetJDK < ClassFileConstants.JDK1_5 && fieldBinding.isSynthetic()) {
attributesNumber += generateSyntheticAttribute();
}
if (fieldBinding.isDeprecated()) {
attributesNumber += generateDeprecatedAttribute();
}
// add signature attribute
char[] genericSignature = fieldBinding.genericSignature();
if (genericSignature != null) {
attributesNumber += generateSignatureAttribute(genericSignature);
}
if (this.targetJDK >= ClassFileConstants.JDK1_4) {
FieldDeclaration fieldDeclaration = fieldBinding.sourceField();
if (fieldDeclaration != null) {
try {
if (fieldDeclaration.isARecordComponent) {
long rcMask = TagBits.AnnotationForField | TagBits.AnnotationForTypeUse;
RecordComponent comp = getRecordComponent(fieldBinding.declaringClass, fieldBinding.name);
if (comp != null)
fieldDeclaration.annotations = ASTNode.getRelevantAnnotations(comp.annotations, rcMask, null);
}
Annotation[] annotations = fieldDeclaration.annotations;
if (annotations != null) {
attributesNumber += generateRuntimeAnnotations(annotations, TagBits.AnnotationForField);
}
if ((this.produceAttributes & ClassFileConstants.ATTR_TYPE_ANNOTATION) != 0) {
List<AnnotationContext> allTypeAnnotationContexts = new ArrayList<>();
if (annotations != null && (fieldDeclaration.bits & ASTNode.HasTypeAnnotations) != 0) {
fieldDeclaration.getAllAnnotationContexts(AnnotationTargetTypeConstants.FIELD, allTypeAnnotationContexts);
}
TypeReference fieldType = fieldDeclaration.type;
if (fieldType != null && ((fieldType.bits & ASTNode.HasTypeAnnotations) != 0)) {
fieldType.getAllAnnotationContexts(AnnotationTargetTypeConstants.FIELD, allTypeAnnotationContexts);
}
int size = allTypeAnnotationContexts.size();
attributesNumber = completeRuntimeTypeAnnotations(attributesNumber,
null,
node -> size > 0,
() -> allTypeAnnotationContexts);
}
} finally {
if (fieldDeclaration.isARecordComponent) {
fieldDeclaration.annotations = null;
}
}
}
}
if ((fieldBinding.tagBits & TagBits.HasMissingType) != 0) {
this.missingTypes = fieldBinding.type.collectMissingTypes(this.missingTypes);
}
return attributesNumber;
}
private RecordComponent getRecordComponent(ReferenceBinding declaringClass, char[] name) {
if (declaringClass instanceof SourceTypeBinding) {
SourceTypeBinding sourceTypeBinding = (SourceTypeBinding) declaringClass;
RecordComponentBinding rcb = sourceTypeBinding.getRecordComponent(name);
if (rcb != null) {
RecordComponent recordComponent = rcb.sourceRecordComponent();
return recordComponent;
}
}
return null;
}
private int addComponentAttributes(RecordComponentBinding recordComponentBinding, int componetAttributeOffset) {
// See JVMS 14 Table 4.7-C - Record Preview for allowed attributes
int attributesNumber = 0;
// add signature attribute
char[] genericSignature = recordComponentBinding.genericSignature();
if (genericSignature != null) {
attributesNumber += generateSignatureAttribute(genericSignature);
}
RecordComponent recordComponent = recordComponentBinding.sourceRecordComponent();
if (recordComponent != null) {
Annotation[] annotations = recordComponent.annotations;
if (annotations != null) {
attributesNumber += generateRuntimeAnnotations(annotations, TagBits.AnnotationForRecordComponent);
}
if ((this.produceAttributes & ClassFileConstants.ATTR_TYPE_ANNOTATION) != 0) {
List<AnnotationContext> allTypeAnnotationContexts = new ArrayList<>();
if (annotations != null && (recordComponent.bits & ASTNode.HasTypeAnnotations) != 0) {
recordComponent.getAllAnnotationContexts(AnnotationTargetTypeConstants.RECORD_COMPONENT, allTypeAnnotationContexts);
}
TypeReference recordComponentType = recordComponent.type;
if (recordComponentType != null && ((recordComponentType.bits & ASTNode.HasTypeAnnotations) != 0)) {
recordComponentType.getAllAnnotationContexts(AnnotationTargetTypeConstants.RECORD_COMPONENT, allTypeAnnotationContexts);
}
int size = allTypeAnnotationContexts.size();
attributesNumber = completeRuntimeTypeAnnotations(attributesNumber,
null,
node -> size > 0,
() -> allTypeAnnotationContexts);
}
}
if ((recordComponentBinding.tagBits & TagBits.HasMissingType) != 0) {
this.missingTypes = recordComponentBinding.type.collectMissingTypes(this.missingTypes);
}
return attributesNumber;
}
private void addComponentInfo(RecordComponentBinding recordComponentBinding) {
// check that there is enough space to write all the bytes for the field info corresponding
// to the @fieldBinding sans accessflags for component
/* record_component_info {
* u2 name_index;
* u2 descriptor_index;
* u2 attributes_count;
* attribute_info attributes[attributes_count];
} */
if (this.contentsOffset + 6 >= this.contents.length) {
resizeContents(6);
}
// Now we can generate all entries into the byte array
int nameIndex = this.constantPool.literalIndex(recordComponentBinding.name);
this.contents[this.contentsOffset++] = (byte) (nameIndex >> 8);
this.contents[this.contentsOffset++] = (byte) nameIndex;
// Then the descriptorIndex
int descriptorIndex = this.constantPool.literalIndex(recordComponentBinding.type);
this.contents[this.contentsOffset++] = (byte) (descriptorIndex >> 8);
this.contents[this.contentsOffset++] = (byte) descriptorIndex;
int componentAttributeOffset = this.contentsOffset;
int attributeNumber = 0;
// leave some space for the number of attributes
this.contentsOffset += 2;
attributeNumber += addComponentAttributes(recordComponentBinding, componentAttributeOffset);
if (this.contentsOffset + 2 >= this.contents.length) {
resizeContents(2);
}
this.contents[componentAttributeOffset++] = (byte) (attributeNumber >> 8);
this.contents[componentAttributeOffset] = (byte) attributeNumber;
}
/**
* INTERNAL USE-ONLY
* This methods generates the bytes for the given field binding
* @param fieldBinding the given field binding
*/
private void addFieldInfo(FieldBinding fieldBinding) {
// check that there is enough space to write all the bytes for the field info corresponding
// to the @fieldBinding
if (this.contentsOffset + 8 >= this.contents.length) {
resizeContents(8);
}
// Now we can generate all entries into the byte array
// First the accessFlags
int accessFlags = fieldBinding.getAccessFlags();
if (this.targetJDK < ClassFileConstants.JDK1_5) {
// pre 1.5, synthetic was an attribute, not a modifier
accessFlags &= ~ClassFileConstants.AccSynthetic;
}
this.contents[this.contentsOffset++] = (byte) (accessFlags >> 8);
this.contents[this.contentsOffset++] = (byte) accessFlags;
// Then the nameIndex
int nameIndex = this.constantPool.literalIndex(fieldBinding.name);
this.contents[this.contentsOffset++] = (byte) (nameIndex >> 8);
this.contents[this.contentsOffset++] = (byte) nameIndex;
// Then the descriptorIndex
int descriptorIndex = this.constantPool.literalIndex(fieldBinding.type);
this.contents[this.contentsOffset++] = (byte) (descriptorIndex >> 8);
this.contents[this.contentsOffset++] = (byte) descriptorIndex;
int fieldAttributeOffset = this.contentsOffset;
int attributeNumber = 0;
// leave some space for the number of attributes
this.contentsOffset += 2;
attributeNumber += addFieldAttributes(fieldBinding, fieldAttributeOffset);
if (this.contentsOffset + 2 >= this.contents.length) {
resizeContents(2);
}
this.contents[fieldAttributeOffset++] = (byte) (attributeNumber >> 8);
this.contents[fieldAttributeOffset] = (byte) attributeNumber;
}
/**
* INTERNAL USE-ONLY
* This methods generate all the fields infos for the receiver.
* This includes:
* - a field info for each defined field of that class
* - a field info for each synthetic field (e.g. this$0)
*/
/**
* INTERNAL USE-ONLY
* This methods generate all the fields infos for the receiver.
* This includes:
* - a field info for each defined field of that class
* - a field info for each synthetic field (e.g. this$0)
*/
public void addFieldInfos() {
SourceTypeBinding currentBinding = this.referenceBinding;
FieldBinding[] syntheticFields = currentBinding.syntheticFields();
int fieldCount = currentBinding.fieldCount() + (syntheticFields == null ? 0 : syntheticFields.length);
// write the number of fields
if (fieldCount > 0xFFFF) {
this.referenceBinding.scope.problemReporter().tooManyFields(this.referenceBinding.scope.referenceType());
}
if (this.contentsOffset + 2 >= this.contents.length) {
resizeContents(2);
}
this.contents[this.contentsOffset++] = (byte) (fieldCount >> 8);
this.contents[this.contentsOffset++] = (byte) fieldCount;
FieldDeclaration[] fieldDecls = currentBinding.scope.referenceContext.fields;
for (int i = 0, max = fieldDecls == null ? 0 : fieldDecls.length; i < max; i++) {
FieldDeclaration fieldDecl = fieldDecls[i];
if (fieldDecl.binding != null) {
addFieldInfo(fieldDecl.binding);
}
}
if (syntheticFields != null) {
for (FieldBinding syntheticField : syntheticFields) {
addFieldInfo(syntheticField);
}
}
}
private void addMissingAbstractProblemMethod(MethodDeclaration methodDeclaration, MethodBinding methodBinding, CategorizedProblem problem, CompilationResult compilationResult) {
// always clear the strictfp/native/abstract bit for a problem method
generateMethodInfoHeader(methodBinding, methodBinding.modifiers & ~(ClassFileConstants.AccStrictfp | ClassFileConstants.AccNative | ClassFileConstants.AccAbstract));
int methodAttributeOffset = this.contentsOffset;
int attributeNumber = generateMethodInfoAttributes(methodBinding);
// Code attribute
attributeNumber++;
int codeAttributeOffset = this.contentsOffset;
generateCodeAttributeHeader();
StringBuilder buffer = new StringBuilder(25);
buffer.append("\t" + problem.getMessage() + "\n" ); //$NON-NLS-1$ //$NON-NLS-2$
buffer.insert(0, Messages.compilation_unresolvedProblem);
String problemString = buffer.toString();
this.codeStream.init(this);
this.codeStream.preserveUnusedLocals = true;
this.codeStream.initializeMaxLocals(methodBinding);
// return codeStream.generateCodeAttributeForProblemMethod(comp.options.runtimeExceptionNameForCompileError, "")
this.codeStream.generateCodeAttributeForProblemMethod(problemString);
completeCodeAttributeForMissingAbstractProblemMethod(
methodBinding,
codeAttributeOffset,
compilationResult.getLineSeparatorPositions(),
problem.getSourceLineNumber());
completeMethodInfo(methodBinding, methodAttributeOffset, attributeNumber);
}
/**
* INTERNAL USE-ONLY
* Generate the byte for a problem clinit method info that correspond to a boggus method.
*
* @param problems org.eclipse.jdt.internal.compiler.problem.Problem[]
*/
public void addProblemClinit(CategorizedProblem[] problems) {
generateMethodInfoHeaderForClinit();
// leave two spaces for the number of attributes
this.contentsOffset -= 2;
int attributeOffset = this.contentsOffset;
this.contentsOffset += 2;
int attributeNumber = 0;
int codeAttributeOffset = this.contentsOffset;
generateCodeAttributeHeader();
this.codeStream.resetForProblemClinit(this);
String problemString = "" ; //$NON-NLS-1$
int problemLine = 0;
if (problems != null) {
int max = problems.length;
StringBuilder buffer = new StringBuilder(25);
int count = 0;
for (int i = 0; i < max; i++) {
CategorizedProblem problem = problems[i];
if ((problem != null) && (problem.isError())) {
buffer.append("\t" +problem.getMessage() + "\n" ); //$NON-NLS-1$ //$NON-NLS-2$
count++;
if (problemLine == 0) {
problemLine = problem.getSourceLineNumber();
}
problems[i] = null;
}
} // insert the top line afterwards, once knowing how many problems we have to consider
if (count > 1) {
buffer.insert(0, Messages.compilation_unresolvedProblems);
} else {
buffer.insert(0, Messages.compilation_unresolvedProblem);
}
problemString = buffer.toString();
}
// return codeStream.generateCodeAttributeForProblemMethod(comp.options.runtimeExceptionNameForCompileError, "")
this.codeStream.generateCodeAttributeForProblemMethod(problemString);
attributeNumber++; // code attribute
completeCodeAttributeForClinit(
codeAttributeOffset,
problemLine,
null);
if (this.contentsOffset + 2 >= this.contents.length) {
resizeContents(2);
}
this.contents[attributeOffset++] = (byte) (attributeNumber >> 8);
this.contents[attributeOffset] = (byte) attributeNumber;
}
/**
* INTERNAL USE-ONLY
* Generate the byte for a problem method info that correspond to a boggus constructor.
*
* @param method org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration
* @param methodBinding org.eclipse.jdt.internal.compiler.nameloopkup.MethodBinding
* @param problems org.eclipse.jdt.internal.compiler.problem.Problem[]
*/
public void addProblemConstructor(
AbstractMethodDeclaration method,
MethodBinding methodBinding,
CategorizedProblem[] problems) {
if (methodBinding.declaringClass.isInterface()) {
method.abort(ProblemSeverities.AbortType, null);
}
// always clear the strictfp/native/abstract bit for a problem method
generateMethodInfoHeader(methodBinding, methodBinding.modifiers & ~(ClassFileConstants.AccStrictfp | ClassFileConstants.AccNative | ClassFileConstants.AccAbstract));
int methodAttributeOffset = this.contentsOffset;
int attributesNumber = generateMethodInfoAttributes(methodBinding);
// Code attribute
attributesNumber++;
int codeAttributeOffset = this.contentsOffset;
generateCodeAttributeHeader();
this.codeStream.reset(method, this);
String problemString = "" ; //$NON-NLS-1$
int problemLine = 0;
if (problems != null) {
int max = problems.length;
StringBuilder buffer = new StringBuilder(25);
int count = 0;
for (int i = 0; i < max; i++) {
CategorizedProblem problem = problems[i];
if ((problem != null) && (problem.isError())) {
buffer.append("\t" +problem.getMessage() + "\n" ); //$NON-NLS-1$ //$NON-NLS-2$
count++;
if (problemLine == 0) {
problemLine = problem.getSourceLineNumber();
}
}
} // insert the top line afterwards, once knowing how many problems we have to consider
if (count > 1) {
buffer.insert(0, Messages.compilation_unresolvedProblems);
} else {
buffer.insert(0, Messages.compilation_unresolvedProblem);
}
problemString = buffer.toString();
}
// return codeStream.generateCodeAttributeForProblemMethod(comp.options.runtimeExceptionNameForCompileError, "")
this.codeStream.generateCodeAttributeForProblemMethod(problemString);
completeCodeAttributeForProblemMethod(
method,
methodBinding,
codeAttributeOffset,
((SourceTypeBinding) methodBinding.declaringClass)
.scope
.referenceCompilationUnit()
.compilationResult
.getLineSeparatorPositions(),
problemLine);
completeMethodInfo(methodBinding, methodAttributeOffset, attributesNumber);
}
/**
* INTERNAL USE-ONLY
* Generate the byte for a problem method info that correspond to a boggus constructor.
* Reset the position inside the contents byte array to the savedOffset.
*
* @param method org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration
* @param methodBinding org.eclipse.jdt.internal.compiler.nameloopkup.MethodBinding
* @param problems org.eclipse.jdt.internal.compiler.problem.Problem[]
* @param savedOffset <CODE>int</CODE>
*/
public void addProblemConstructor(
AbstractMethodDeclaration method,
MethodBinding methodBinding,
CategorizedProblem[] problems,
int savedOffset) {
// we need to move back the contentsOffset to the value at the beginning of the method
this.contentsOffset = savedOffset;
this.methodCount--; // we need to remove the method that causes the problem
addProblemConstructor(method, methodBinding, problems);
}
/**
* INTERNAL USE-ONLY
* Generate the byte for a problem method info that correspond to a boggus method.
*
* @param method org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration
* @param methodBinding org.eclipse.jdt.internal.compiler.nameloopkup.MethodBinding
* @param problems org.eclipse.jdt.internal.compiler.problem.Problem[]
*/
public void addProblemMethod(
AbstractMethodDeclaration method,
MethodBinding methodBinding,
CategorizedProblem[] problems) {
if (methodBinding.isAbstract() && methodBinding.declaringClass.isInterface()) {
method.abort(ProblemSeverities.AbortType, null);
}
// always clear the strictfp/native/abstract bit for a problem method
generateMethodInfoHeader(methodBinding, methodBinding.modifiers & ~(ClassFileConstants.AccStrictfp | ClassFileConstants.AccNative | ClassFileConstants.AccAbstract));
int methodAttributeOffset = this.contentsOffset;
int attributesNumber = generateMethodInfoAttributes(methodBinding);
// Code attribute
attributesNumber++;
int codeAttributeOffset = this.contentsOffset;
generateCodeAttributeHeader();
this.codeStream.reset(method, this);
String problemString = "" ; //$NON-NLS-1$
int problemLine = 0;
if (problems != null) {