< 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             }

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.util.AbstractList;
 41 import java.util.Collection;
 42 import java.util.List;
 43 import java.util.function.Consumer;
 44 import java.util.function.Function;
 45 
 46 import jdk.internal.access.SharedSecrets;
 47 import jdk.internal.constant.ClassOrInterfaceDescImpl;
 48 import jdk.internal.vm.annotation.ForceInline;
 49 import jdk.internal.vm.annotation.Stable;
 50 
 51 import static java.lang.classfile.ClassFile.ACC_STATIC;
 52 import static java.lang.constant.ConstantDescs.INIT_NAME;
 53 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_double;
 54 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_long;
 55 import static jdk.internal.constant.PrimitiveClassDescImpl.CD_void;
 56 
 57 /**
 58  * Helper to create and manipulate type descriptors, where type descriptors are
 59  * represented as JVM type descriptor strings and symbols are represented as
 60  * name strings
 61  */
 62 public class Util {
 63 
 64     private Util() {
 65     }
 66 
 67     public static <T> Consumer<Consumer<T>> writingAll(Iterable<T> container) {
 68         record ForEachConsumer<T>(Iterable<T> container) implements Consumer<Consumer<T>> {
 69             @Override
 70             public void accept(Consumer<T> consumer) {
 71                 container.forEach(consumer);
 72             }

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

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