1 /*
  2  * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2024, Alibaba Group Holding Limited. All Rights Reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.  Oracle designates this
  9  * particular file as subject to the "Classpath" exception as provided
 10  * by Oracle in the LICENSE file that accompanied this code.
 11  *
 12  * This code is distributed in the hope that it will be useful, but WITHOUT
 13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 15  * version 2 for more details (a copy is included in the LICENSE file that
 16  * accompanied this code).
 17  *
 18  * You should have received a copy of the GNU General Public License version
 19  * 2 along with this work; if not, write to the Free Software Foundation,
 20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 21  *
 22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 23  * or visit www.oracle.com if you need additional information or have any
 24  * questions.
 25  */
 26 
 27 package jdk.internal.classfile.impl;
 28 
 29 import java.lang.classfile.*;
 30 import java.lang.classfile.constantpool.ClassEntry;
 31 import java.lang.classfile.constantpool.Utf8Entry;
 32 import java.lang.constant.ConstantDescs;
 33 import java.util.Arrays;
 34 import java.util.Collections;
 35 import java.util.List;
 36 import java.util.function.Consumer;
 37 
 38 import static java.lang.classfile.ClassFile.PREVIEW_MINOR_VERSION;
 39 import static java.util.Objects.requireNonNull;
 40 
 41 public final class DirectClassBuilder
 42         extends AbstractDirectBuilder<ClassModel>
 43         implements ClassBuilder {
 44 
 45     /** The value of default class access flags */
 46     static final int DEFAULT_CLASS_FLAGS = ClassFile.ACC_PUBLIC | ClassFile.ACC_SUPER;
 47     static final Util.Writable[] EMPTY_WRITABLE_ARRAY = {};
 48     static final WritableField[] EMPTY_WRITABLE_FIELD_ARRAY = {};
 49     static final ClassEntry[] EMPTY_CLASS_ENTRY_ARRAY = {};
 50     final ClassEntry thisClassEntry;
 51     private WritableField[] fields = EMPTY_WRITABLE_FIELD_ARRAY;
 52     private Util.Writable[] methods = EMPTY_WRITABLE_ARRAY;
 53     private int fieldsCount = 0;
 54     private int methodsCount = 0;
 55     private ClassEntry superclassEntry;
 56     private List<ClassEntry> interfaceEntries;
 57     private int majorVersion;
 58     private int minorVersion;
 59     private int flags;
 60     private int sizeHint;
 61 
 62     public DirectClassBuilder(SplitConstantPool constantPool,
 63                               ClassFileImpl context,
 64                               ClassEntry thisClass) {
 65         super(constantPool, context);
 66         this.thisClassEntry = AbstractPoolEntry.maybeClone(constantPool, thisClass);
 67         this.flags = DEFAULT_CLASS_FLAGS;
 68         this.superclassEntry = null;
 69         this.interfaceEntries = Collections.emptyList();
 70         this.majorVersion = ClassFile.latestMajorVersion();
 71         this.minorVersion = ClassFile.latestMinorVersion();
 72     }
 73 
 74     @Override
 75     public ClassBuilder with(ClassElement element) {
 76         if (element instanceof AbstractElement ae) {
 77             ae.writeTo(this);
 78         } else {
 79             writeAttribute((CustomAttribute<?>) requireNonNull(element));
 80         }
 81         return this;
 82     }
 83 
 84     @Override
 85     public ClassBuilder withFlags(int flags) {
 86         setFlags(Util.checkFlags(flags));
 87         return this;
 88     }
 89 
 90     @Override
 91     public ClassBuilder withField(Utf8Entry name,
 92                                   Utf8Entry descriptor,
 93                                   int flags) {
 94         return withField(new DirectFieldBuilder(constantPool, context, name, descriptor, flags, null));
 95     }
 96 
 97     @Override
 98     public ClassBuilder withField(Utf8Entry name,
 99                                   Utf8Entry descriptor,
100                                   Consumer<? super FieldBuilder> handler) {
101         return withField(new DirectFieldBuilder(constantPool, context, name, descriptor, 0, null)
102                                  .run(handler));
103     }
104 
105     @Override
106     public ClassBuilder transformField(FieldModel field, FieldTransform transform) {
107         DirectFieldBuilder builder = new DirectFieldBuilder(constantPool, context, field.fieldName(),
108                                                             field.fieldType(), 0, field);
109         builder.transform(field, transform);
110         return withField(builder);
111     }
112 
113     @Override
114     public ClassBuilder withMethod(Utf8Entry name,
115                                    Utf8Entry descriptor,
116                                    int flags,
117                                    Consumer<? super MethodBuilder> handler) {
118         return withMethod(new DirectMethodBuilder(constantPool, context, name, descriptor, flags, null)
119                                   .run(handler));
120     }
121 
122     @Override
123     public ClassBuilder transformMethod(MethodModel method, MethodTransform transform) {
124         DirectMethodBuilder builder = new DirectMethodBuilder(constantPool, context, method.methodName(),
125                                                               method.methodType(),
126                                                               method.flags().flagsMask(),
127                                                               method);
128         builder.transform(method, transform);
129         return withMethod(builder);
130     }
131 
132     // internal / for use by elements
133 
134     ClassBuilder withField(WritableField field) {
135         if (fieldsCount >= fields.length) {
136             int newCapacity = fieldsCount + 8;
137             this.fields = Arrays.copyOf(fields, newCapacity);
138         }
139         fields[fieldsCount++] = field;
140         return this;
141     }
142 
143     ClassBuilder withMethod(Util.Writable method) {
144         if (methodsCount >= methods.length) {
145             int newCapacity = methodsCount + 8;
146             this.methods = Arrays.copyOf(methods, newCapacity);
147         }
148         methods[methodsCount++] = method;
149         return this;
150     }
151 
152     void setSuperclass(ClassEntry superclassEntry) {
153         this.superclassEntry = superclassEntry;
154     }
155 
156     void setInterfaces(List<ClassEntry> interfaces) {
157         this.interfaceEntries = interfaces;
158     }
159 
160     void setVersion(int major, int minor) {
161         this.majorVersion = major;
162         this.minorVersion = minor;
163     }
164 
165     void setFlags(int flags) {
166         this.flags = flags;
167     }
168 
169     public void setSizeHint(int sizeHint) {
170         this.sizeHint = sizeHint;
171     }
172 
173     public byte[] build() {
174 
175         // The logic of this is very carefully ordered.  We want to avoid
176         // repeated buffer copyings, so we accumulate lists of writers which
177         // all get written later into the same buffer.  But, writing can often
178         // trigger CP / BSM insertions, so we cannot run the CP writer or
179         // BSM writers until everything else is written.
180 
181         // Do this early because it might trigger CP activity
182         var constantPool = this.constantPool;
183         ClassEntry superclass = superclassEntry;
184         if (superclass != null)
185             superclass = AbstractPoolEntry.maybeClone(constantPool, superclass);
186         else if ((flags & ClassFile.ACC_MODULE) == 0 && !"java/lang/Object".equals(thisClassEntry.asInternalName()))
187             superclass = constantPool.classEntry(ConstantDescs.CD_Object);
188         int interfaceEntriesSize = interfaceEntries.size();
189         ClassEntry[] ies = interfaceEntriesSize == 0 ? EMPTY_CLASS_ENTRY_ARRAY : buildInterfaceEnties(interfaceEntriesSize);
190 
191         // We maintain two writers, and then we join them at the end
192         int size = sizeHint == 0 ? 256 : sizeHint;
193         BufWriterImpl head = new BufWriterImpl(constantPool, context, size);
194         BufWriterImpl tail = new BufWriterImpl(constantPool, context, size, thisClassEntry, majorVersion);
195 
196         // The tail consists of fields and methods, and attributes
197         // This should trigger all the CP/BSM mutation
198         Util.writeList(tail, fields, fieldsCount);
199         WritableField.UnsetField[] strictInstanceFields;
200         if (minorVersion == PREVIEW_MINOR_VERSION && majorVersion >= Util.VALUE_OBJECTS_MAJOR) {
201             strictInstanceFields = WritableField.filterStrictInstanceFields(constantPool, fields, fieldsCount);
202         } else {
203             strictInstanceFields = WritableField.UnsetField.EMPTY_ARRAY;
204         }
205         tail.setStrictInstanceFields(strictInstanceFields);
206         Util.writeList(tail, methods, methodsCount);
207         int attributesOffset = tail.size();
208         attributes.writeTo(tail);
209 
210         // Now we have to append the BSM, if there is one
211         if (constantPool.writeBootstrapMethods(tail)) {
212             // Update attributes count
213             tail.patchU2(attributesOffset, attributes.size() + 1);
214         }
215 
216         // Now we can make the head
217         head.writeInt(ClassFile.MAGIC_NUMBER);
218         head.writeU2U2(minorVersion, majorVersion);
219         constantPool.writeTo(head);
220         head.writeU2U2U2(flags, head.cpIndex(thisClassEntry), head.cpIndexOrZero(superclass));
221         head.writeU2(interfaceEntriesSize);
222         for (int i = 0; i < interfaceEntriesSize; i++) {
223             head.writeIndex(ies[i]);
224         }
225 
226         // Join head and tail into an exact-size buffer
227         return BufWriterImpl.join(head, tail);
228     }
229 
230     private ClassEntry[] buildInterfaceEnties(int interfaceEntriesSize) {
231         var ies = new ClassEntry[interfaceEntriesSize];
232         for (int i = 0; i < interfaceEntriesSize; i++)
233             ies[i] = AbstractPoolEntry.maybeClone(constantPool, interfaceEntries.get(i));
234         return ies;
235     }
236 }