< prev index next >

src/java.base/share/classes/jdk/internal/classfile/impl/Util.java

Print this page

  1 /*
  2  * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 package jdk.internal.classfile.impl;
 26 
 27 import java.lang.classfile.*;
 28 import java.lang.classfile.attribute.CodeAttribute;
 29 import jdk.internal.classfile.components.ClassPrinter;
 30 import java.lang.classfile.constantpool.ClassEntry;


 31 import java.lang.classfile.constantpool.ModuleEntry;
 32 import java.lang.classfile.constantpool.PoolEntry;
 33 import java.lang.classfile.constantpool.Utf8Entry;
 34 import java.lang.constant.ClassDesc;
 35 import java.lang.constant.MethodTypeDesc;
 36 import java.lang.constant.ModuleDesc;
 37 import java.lang.reflect.AccessFlag;

 38 import java.util.AbstractList;
 39 import java.util.Collection;
 40 import java.util.List;
 41 import java.util.function.Consumer;
 42 import java.util.function.Function;
 43 
 44 import jdk.internal.access.SharedSecrets;
 45 import jdk.internal.constant.ClassOrInterfaceDescImpl;
 46 import jdk.internal.vm.annotation.ForceInline;
 47 import jdk.internal.vm.annotation.Stable;
 48 
 49 import static java.lang.classfile.ClassFile.ACC_STATIC;

 50 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_double;
 51 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_long;
 52 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_void;
 53 
 54 /**
 55  * Helper to create and manipulate type descriptors, where type descriptors are
 56  * represented as JVM type descriptor strings and symbols are represented as
 57  * name strings
 58  */
 59 public class Util {
 60 
 61     private Util() {
 62     }
 63 
 64     public static <T> Consumer<Consumer<T>> writingAll(Iterable<T> container) {
 65         record ForEachConsumer<T>(Iterable<T> container) implements Consumer<Consumer<T>> {
 66             @Override
 67             public void accept(Consumer<T> consumer) {
 68                 container.forEach(consumer);
 69             }

183 
184     public static IllegalArgumentException badOpcodeKindException(Opcode op, Opcode.Kind k) {
185         return new IllegalArgumentException(
186                 String.format("Wrong opcode kind specified; found %s(%s), expected %s", op, op.kind(), k));
187     }
188 
189     public static int flagsToBits(AccessFlag.Location location, Collection<AccessFlag> flags) {
190         int i = 0;
191         for (AccessFlag f : flags) {
192             if (!f.locations().contains(location)) {
193                 throw new IllegalArgumentException("unexpected flag: " + f + " use in target location: " + location);
194             }
195             i |= f.mask();
196         }
197         return i;
198     }
199 
200     public static int flagsToBits(AccessFlag.Location location, AccessFlag... flags) {
201         int i = 0;
202         for (AccessFlag f : flags) {
203             if (!f.locations().contains(location)) {
204                 throw new IllegalArgumentException("unexpected flag: " + f + " use in target location: " + location);
205             }
206             i |= f.mask();
207         }
208         return i;
209     }
210 
211     public static boolean has(AccessFlag.Location location, int flagsMask, AccessFlag flag) {
212         return (flag.mask() & flagsMask) == flag.mask() && flag.locations().contains(location);

213     }
214 
215     public static ClassDesc fieldTypeSymbol(Utf8Entry utf8) {
216         return ((AbstractPoolEntry.Utf8EntryImpl) utf8).fieldTypeSymbol();
217     }
218 
219     public static MethodTypeDesc methodTypeSymbol(Utf8Entry utf8) {
220         return ((AbstractPoolEntry.Utf8EntryImpl) utf8).methodTypeSymbol();
221     }
222 
223     @SuppressWarnings("unchecked")
224     public static <T extends Attribute<T>> void writeAttribute(BufWriterImpl writer, Attribute<?> attr) {
225         if (attr instanceof CustomAttribute<?> ca) {
226             var mapper = (AttributeMapper<T>) ca.attributeMapper();
227             mapper.writeAttribute(writer, (T) ca);
228         } else {
229             assert attr instanceof BoundAttribute || attr instanceof UnboundAttribute;
230             ((Writable) attr).writeTo(writer);
231         }
232     }

243     @ForceInline
244     static void writeList(BufWriterImpl buf, Writable[] array, int size) {
245         buf.writeU2(size);
246         for (int i = 0; i < size; i++) {
247             array[i].writeTo(buf);
248         }
249     }
250 
251     public static int slotSize(ClassDesc desc) {
252         return desc == CD_void ? 0 : isDoubleSlot(desc) ? 2 : 1;
253     }
254 
255     public static int paramSlotSize(ClassDesc desc) {
256         return isDoubleSlot(desc) ? 2 : 1;
257     }
258 
259     public static boolean isDoubleSlot(ClassDesc desc) {
260         return desc == CD_double || desc == CD_long;
261     }
262 








263     public static void dumpMethod(SplitConstantPool cp,
264                                   ClassDesc cls,
265                                   String methodName,
266                                   MethodTypeDesc methodDesc,
267                                   int acc,
268                                   RawBytecodeHelper.CodeRange bytecode,
269                                   Consumer<String> dump) {
270 
271         // try to dump debug info about corrupted bytecode
272         try {
273             var cc = ClassFile.of();
274             var clm = cc.parse(cc.build(cp.classEntry(cls), cp, clb ->
275                     clb.withMethod(methodName, methodDesc, acc, mb ->
276                             ((DirectMethodBuilder)mb).writeAttribute(new UnboundAttribute.AdHocAttribute<CodeAttribute>(Attributes.code()) {
277                                 @Override
278                                 public void writeBody(BufWriterImpl b) {
279                                     b.writeU2U2(-1, -1);//max stack & locals
280                                     b.writeInt(bytecode.length());
281                                     b.writeBytes(bytecode.array(), 0, bytecode.length());
282                                     b.writeU2U2(0, 0);//exception handlers & attributes

286                                 public Utf8Entry attributeName() {
287                                     return cp.utf8Entry(Attributes.NAME_CODE);
288                                 }
289                     }))));
290             ClassPrinter.toYaml(clm.methods().get(0).code().get(), ClassPrinter.Verbosity.TRACE_ALL, dump);
291         } catch (Error | Exception _) {
292             // fallback to bytecode hex dump
293             dumpBytesHex(dump, bytecode.array(), bytecode.length());
294         }
295     }
296 
297     public static void dumpBytesHex(Consumer<String> dump, byte[] bytes, int length) {
298         for (int i = 0; i < length; i++) {
299             if (i % 16 == 0) {
300                 dump.accept("%n%04x:".formatted(i));
301             }
302             dump.accept(" %02x".formatted(bytes[i]));
303         }
304     }
305 











306     public static void writeListIndices(BufWriter writer, List<? extends PoolEntry> list) {
307         writer.writeU2(list.size());
308         for (PoolEntry info : list) {
309             writer.writeIndex(info);
310         }
311     }
312 
313     public static boolean writeLocalVariable(BufWriterImpl buf, PseudoInstruction lvOrLvt) {
314         return ((WritableLocalVariable) lvOrLvt).writeLocalTo(buf);
315     }
316 
317     /**
318      * A generic interface for objects to write to a
319      * buf writer. Do not implement unless necessary,
320      * as this writeTo is public, which can be troublesome.
321      */
322     interface Writable {
323         void writeTo(BufWriterImpl writer);
324     }
325 

  1 /*
  2  * Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 package jdk.internal.classfile.impl;
 26 
 27 import java.lang.classfile.*;
 28 import java.lang.classfile.attribute.CodeAttribute;
 29 import jdk.internal.classfile.components.ClassPrinter;
 30 import java.lang.classfile.constantpool.ClassEntry;
 31 import java.lang.classfile.constantpool.ConstantPool;
 32 import java.lang.classfile.constantpool.ConstantPoolBuilder;
 33 import java.lang.classfile.constantpool.ModuleEntry;
 34 import java.lang.classfile.constantpool.PoolEntry;
 35 import java.lang.classfile.constantpool.Utf8Entry;
 36 import java.lang.constant.ClassDesc;
 37 import java.lang.constant.MethodTypeDesc;
 38 import java.lang.constant.ModuleDesc;
 39 import java.lang.reflect.AccessFlag;
 40 import java.lang.reflect.ClassFileFormatVersion;
 41 import java.util.AbstractList;
 42 import java.util.Collection;
 43 import java.util.List;
 44 import java.util.function.Consumer;
 45 import java.util.function.Function;
 46 
 47 import jdk.internal.access.SharedSecrets;
 48 import jdk.internal.constant.ClassOrInterfaceDescImpl;
 49 import jdk.internal.vm.annotation.ForceInline;
 50 import jdk.internal.vm.annotation.Stable;
 51 
 52 import static java.lang.classfile.ClassFile.ACC_STATIC;
 53 import static java.lang.constant.ConstantDescs.INIT_NAME;
 54 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_double;
 55 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_long;
 56 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_void;
 57 
 58 /**
 59  * Helper to create and manipulate type descriptors, where type descriptors are
 60  * represented as JVM type descriptor strings and symbols are represented as
 61  * name strings
 62  */
 63 public class Util {
 64 
 65     private Util() {
 66     }
 67 
 68     public static <T> Consumer<Consumer<T>> writingAll(Iterable<T> container) {
 69         record ForEachConsumer<T>(Iterable<T> container) implements Consumer<Consumer<T>> {
 70             @Override
 71             public void accept(Consumer<T> consumer) {
 72                 container.forEach(consumer);
 73             }

187 
188     public static IllegalArgumentException badOpcodeKindException(Opcode op, Opcode.Kind k) {
189         return new IllegalArgumentException(
190                 String.format("Wrong opcode kind specified; found %s(%s), expected %s", op, op.kind(), k));
191     }
192 
193     public static int flagsToBits(AccessFlag.Location location, Collection<AccessFlag> flags) {
194         int i = 0;
195         for (AccessFlag f : flags) {
196             if (!f.locations().contains(location)) {
197                 throw new IllegalArgumentException("unexpected flag: " + f + " use in target location: " + location);
198             }
199             i |= f.mask();
200         }
201         return i;
202     }
203 
204     public static int flagsToBits(AccessFlag.Location location, AccessFlag... flags) {
205         int i = 0;
206         for (AccessFlag f : flags) {
207             if (!f.locations().contains(location) && !f.locations(ClassFileFormatVersion.CURRENT_PREVIEW_FEATURES).contains(location)) {
208                 throw new IllegalArgumentException("unexpected flag: " + f + " use in target location: " + location);
209             }
210             i |= f.mask();
211         }
212         return i;
213     }
214 
215     public static boolean has(AccessFlag.Location location, int flagsMask, AccessFlag flag) {
216         return (flag.mask() & flagsMask) == flag.mask() && (flag.locations().contains(location)
217                 || flag.locations(ClassFileFormatVersion.CURRENT_PREVIEW_FEATURES).contains(location));
218     }
219 
220     public static ClassDesc fieldTypeSymbol(Utf8Entry utf8) {
221         return ((AbstractPoolEntry.Utf8EntryImpl) utf8).fieldTypeSymbol();
222     }
223 
224     public static MethodTypeDesc methodTypeSymbol(Utf8Entry utf8) {
225         return ((AbstractPoolEntry.Utf8EntryImpl) utf8).methodTypeSymbol();
226     }
227 
228     @SuppressWarnings("unchecked")
229     public static <T extends Attribute<T>> void writeAttribute(BufWriterImpl writer, Attribute<?> attr) {
230         if (attr instanceof CustomAttribute<?> ca) {
231             var mapper = (AttributeMapper<T>) ca.attributeMapper();
232             mapper.writeAttribute(writer, (T) ca);
233         } else {
234             assert attr instanceof BoundAttribute || attr instanceof UnboundAttribute;
235             ((Writable) attr).writeTo(writer);
236         }
237     }

248     @ForceInline
249     static void writeList(BufWriterImpl buf, Writable[] array, int size) {
250         buf.writeU2(size);
251         for (int i = 0; i < size; i++) {
252             array[i].writeTo(buf);
253         }
254     }
255 
256     public static int slotSize(ClassDesc desc) {
257         return desc == CD_void ? 0 : isDoubleSlot(desc) ? 2 : 1;
258     }
259 
260     public static int paramSlotSize(ClassDesc desc) {
261         return isDoubleSlot(desc) ? 2 : 1;
262     }
263 
264     public static boolean isDoubleSlot(ClassDesc desc) {
265         return desc == CD_double || desc == CD_long;
266     }
267 
268     public static boolean checkConstantPoolsCompatible(ConstantPool one, ConstantPool two) {
269         if (one.equals(two))
270             return true;
271         if (one instanceof ConstantPoolBuilder cpb && cpb.canWriteDirect(two))
272             return true;
273         return two instanceof ConstantPoolBuilder cpb && cpb.canWriteDirect(one);
274     }
275 
276     public static void dumpMethod(SplitConstantPool cp,
277                                   ClassDesc cls,
278                                   String methodName,
279                                   MethodTypeDesc methodDesc,
280                                   int acc,
281                                   RawBytecodeHelper.CodeRange bytecode,
282                                   Consumer<String> dump) {
283 
284         // try to dump debug info about corrupted bytecode
285         try {
286             var cc = ClassFile.of();
287             var clm = cc.parse(cc.build(cp.classEntry(cls), cp, clb ->
288                     clb.withMethod(methodName, methodDesc, acc, mb ->
289                             ((DirectMethodBuilder)mb).writeAttribute(new UnboundAttribute.AdHocAttribute<CodeAttribute>(Attributes.code()) {
290                                 @Override
291                                 public void writeBody(BufWriterImpl b) {
292                                     b.writeU2U2(-1, -1);//max stack & locals
293                                     b.writeInt(bytecode.length());
294                                     b.writeBytes(bytecode.array(), 0, bytecode.length());
295                                     b.writeU2U2(0, 0);//exception handlers & attributes

299                                 public Utf8Entry attributeName() {
300                                     return cp.utf8Entry(Attributes.NAME_CODE);
301                                 }
302                     }))));
303             ClassPrinter.toYaml(clm.methods().get(0).code().get(), ClassPrinter.Verbosity.TRACE_ALL, dump);
304         } catch (Error | Exception _) {
305             // fallback to bytecode hex dump
306             dumpBytesHex(dump, bytecode.array(), bytecode.length());
307         }
308     }
309 
310     public static void dumpBytesHex(Consumer<String> dump, byte[] bytes, int length) {
311         for (int i = 0; i < length; i++) {
312             if (i % 16 == 0) {
313                 dump.accept("%n%04x:".formatted(i));
314             }
315             dump.accept(" %02x".formatted(bytes[i]));
316         }
317     }
318 
319     public static boolean canSkipMethodInflation(ClassReader cr, MethodInfo method, BufWriterImpl buf) {
320         if (!buf.canWriteDirect(cr)) {
321             return false;
322         }
323         if (method.methodName().equalsString(INIT_NAME) &&
324                 !buf.strictFieldsMatch(((ClassReaderImpl) cr).getContainedClass())) {
325             return false;
326         }
327         return true;
328     }
329 
330     public static void writeListIndices(BufWriter writer, List<? extends PoolEntry> list) {
331         writer.writeU2(list.size());
332         for (PoolEntry info : list) {
333             writer.writeIndex(info);
334         }
335     }
336 
337     public static boolean writeLocalVariable(BufWriterImpl buf, PseudoInstruction lvOrLvt) {
338         return ((WritableLocalVariable) lvOrLvt).writeLocalTo(buf);
339     }
340 
341     /**
342      * A generic interface for objects to write to a
343      * buf writer. Do not implement unless necessary,
344      * as this writeTo is public, which can be troublesome.
345      */
346     interface Writable {
347         void writeTo(BufWriterImpl writer);
348     }
349 
< prev index next >