8345486: Reevaluate the classes in java.lang.classfile.components package

Reviewed-by: mcimadamore, asotona
This commit is contained in:
Chen Liang 2024-12-04 17:30:01 +00:00
parent f3b4350e0f
commit 79eb77b782
33 changed files with 54 additions and 158 deletions

View file

@ -60,12 +60,7 @@ import java.util.function.Supplier;
* its state must be reset for each traversal; this will happen automatically if
* the transform is created with {@link ClassTransform#ofStateful(Supplier)} (or
* corresponding methods for other classfile locations.)
* <p>
* Class transformation sample where code transformation is stateful:
* {@snippet lang="java" class="PackageSnippets" region="codeRelabeling"}
* <p>
* Complex class instrumentation sample chaining multiple transformations:
* {@snippet lang="java" class="PackageSnippets" region="classInstrumentation"}
*
* @param <C> the transform type
* @param <E> the element type
* @param <B> the builder type

View file

@ -1,221 +0,0 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.classfile.components;
import java.lang.classfile.ClassModel;
import java.lang.classfile.CodeModel;
import java.lang.classfile.CompoundElement;
import java.lang.classfile.FieldModel;
import java.lang.classfile.MethodModel;
import java.lang.constant.ConstantDesc;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
import jdk.internal.classfile.impl.ClassPrinterImpl;
/**
* A printer of classfiles and its elements.
* <p>
* Any {@link ClassModel}, {@link FieldModel}, {@link MethodModel}, or {@link CodeModel}
* can be printed to a human-readable structured text in JSON, XML, or YAML format.
* Or it can be exported into a tree of traversable and printable nodes,
* more exactly into a tree of {@link MapNode}, {@link ListNode}, and {@link LeafNode} instances.
* <p>
* Level of details to print or to export is driven by {@link Verbosity} option.
* <p>
* Printing is for debugging purposes only. Printed text schema, tree content and structure
* not guaranteed. It may change anytime in a future.
* <p>
* The most frequent use case is to simply print a class:
* {@snippet lang="java" class="PackageSnippets" region="printClass"}
* <p>
* {@link ClassPrinter} allows to traverse tree of simple printable nodes to hook custom printer:
* {@snippet lang="java" class="PackageSnippets" region="customPrint"}
* <p>
* Another use case for {@link ClassPrinter} is to simplify writing of automated tests:
* {@snippet lang="java" class="PackageSnippets" region="printNodesInTest"}
*
* @since 24
*/
public final class ClassPrinter {
private ClassPrinter() {
}
/**
* Level of detail to print or export.
*
* @since 24
*/
public enum Verbosity {
/**
* Only top level class info, class members and attribute names are printed.
*/
MEMBERS_ONLY,
/**
* Top level class info, class members, and critical attributes are printed.
* <p>
* Critical attributes are:
* <ul>
* <li>ConstantValue
* <li>Code
* <li>StackMapTable
* <li>BootstrapMethods
* <li>NestHost
* <li>NestMembers
* <li>PermittedSubclasses
* </ul>
* @jvms 4.7 Attributes
*/
CRITICAL_ATTRIBUTES,
/**
* All class content is printed, including constant pool.
*/
TRACE_ALL }
/**
* Named, traversable, and printable node parent.
*
* @since 24
*/
public sealed interface Node {
/**
* Printable name of the node.
* @return name of the node
*/
ConstantDesc name();
/**
* Walks through the underlying tree.
* @return ordered stream of nodes
*/
Stream<Node> walk();
/**
* Prints the node and its sub-tree into JSON format.
* @param out consumer of the printed fragments
*/
default void toJson(Consumer<String> out) {
ClassPrinterImpl.toJson(this, out);
}
/**
* Prints the node and its sub-tree into XML format.
* @param out consumer of the printed fragments
*/
default void toXml(Consumer<String> out) {
ClassPrinterImpl.toXml(this, out);
}
/**
* Prints the node and its sub-tree into YAML format.
* @param out consumer of the printed fragments
*/
default void toYaml(Consumer<String> out) {
ClassPrinterImpl.toYaml(this, out);
}
}
/**
* A leaf node holding single printable value.
*
* @since 24
*/
public sealed interface LeafNode extends Node
permits ClassPrinterImpl.LeafNodeImpl {
/**
* Printable node value
* @return node value
*/
ConstantDesc value();
}
/**
* A tree node holding {@link List} of nested nodes.
*
* @since 24
*/
public sealed interface ListNode extends Node, List<Node>
permits ClassPrinterImpl.ListNodeImpl {
}
/**
* A tree node holding {@link Map} of nested nodes.
* <p>
* Each {@link Map.Entry#getKey()} == {@link Map.Entry#getValue()}.{@link #name()}.
*
* @since 24
*/
public sealed interface MapNode extends Node, Map<ConstantDesc, Node>
permits ClassPrinterImpl.MapNodeImpl {
}
/**
* Exports provided model into a tree of printable nodes.
* @param model a {@link ClassModel}, {@link FieldModel}, {@link MethodModel}, or {@link CodeModel} to export
* @param verbosity level of details to export
* @return root node of the exported tree
*/
public static MapNode toTree(CompoundElement<?> model, Verbosity verbosity) {
return ClassPrinterImpl.modelToTree(model, verbosity);
}
/**
* Prints provided model as structured text in JSON format.
* @param model a {@link ClassModel}, {@link FieldModel}, {@link MethodModel}, or {@link CodeModel} to print
* @param verbosity level of details to print
* @param out consumer of the print fragments
*/
public static void toJson(CompoundElement<?> model, Verbosity verbosity, Consumer<String> out) {
toTree(model, verbosity).toJson(out);
}
/**
* Prints provided model as structured text in XML format.
* @param model a {@link ClassModel}, {@link FieldModel}, {@link MethodModel}, or {@link CodeModel} to print
* @param verbosity level of details to print
* @param out consumer of the print fragments
*/
public static void toXml(CompoundElement<?> model, Verbosity verbosity, Consumer<String> out) {
toTree(model, verbosity).toXml(out);
}
/**
* Prints provided model as structured text in YAML format.
* @param model a {@link ClassModel}, {@link FieldModel}, {@link MethodModel}, or {@link CodeModel} to print
* @param verbosity level of details to print
* @param out consumer of the print fragments
*/
public static void toYaml(CompoundElement<?> model, Verbosity verbosity, Consumer<String> out) {
toTree(model, verbosity).toYaml(out);
}
}

View file

@ -1,114 +0,0 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.classfile.components;
import java.lang.classfile.ClassFile;
import java.lang.classfile.ClassModel;
import java.lang.classfile.ClassTransform;
import java.lang.classfile.CodeTransform;
import java.lang.classfile.FieldTransform;
import java.lang.classfile.MethodTransform;
import java.lang.constant.ClassDesc;
import java.util.Map;
import java.util.function.Function;
import jdk.internal.classfile.impl.ClassRemapperImpl;
import static java.util.Objects.requireNonNull;
/**
* {@code ClassRemapper} is a {@link ClassTransform}, {@link FieldTransform},
* {@link MethodTransform} and {@link CodeTransform}
* deeply re-mapping all class references in any form, according to given map or
* map function.
* <p>
* The re-mapping is applied to superclass, interfaces, all kinds of descriptors
* and signatures, all attributes referencing classes in any form (including all
* types of annotations), and to all instructions referencing to classes.
* <p>
* Primitive types and arrays are never subjects of mapping and are not allowed
* targets of mapping.
* <p>
* Arrays of reference types are always decomposed, mapped as the base reference
* types and composed back to arrays.
*
* @since 24
*/
public sealed interface ClassRemapper extends ClassTransform permits ClassRemapperImpl {
/**
* Creates new instance of {@code ClassRemapper} instructed with a class map.
* Map may contain only re-mapping entries, identity mapping is applied by default.
* @param classMap class map
* @return new instance of {@code ClassRemapper}
*/
static ClassRemapper of(Map<ClassDesc, ClassDesc> classMap) {
requireNonNull(classMap);
return of(desc -> classMap.getOrDefault(desc, desc));
}
/**
* Creates new instance of {@code ClassRemapper} instructed with a map function.
* Map function must return valid {@link java.lang.constant.ClassDesc} of an interface
* or a class, even for identity mappings.
* @param mapFunction class map function
* @return new instance of {@code ClassRemapper}
*/
static ClassRemapper of(Function<ClassDesc, ClassDesc> mapFunction) {
return new ClassRemapperImpl(requireNonNull(mapFunction));
}
/**
* Access method to internal class mapping function.
* @param desc source class
* @return target class
*/
ClassDesc map(ClassDesc desc);
/**
* {@return this {@code ClassRemapper} as {@link FieldTransform} instance}
*/
FieldTransform asFieldTransform();
/**
* {@return this {@code ClassRemapper} as {@link MethodTransform} instance}
*/
MethodTransform asMethodTransform();
/**
* {@return this {@code ClassRemapper} as {@link CodeTransform} instance}
*/
CodeTransform asCodeTransform();
/**
* Remaps the whole ClassModel into a new class file, including the class name.
* @param context ClassFile context
* @param clm class model to re-map
* @return re-mapped class file bytes
*/
default byte[] remapClass(ClassFile context, ClassModel clm) {
return context.transformClass(clm, map(clm.thisClass().asSymbol()), this);
}
}

View file

@ -1,58 +0,0 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.classfile.components;
import java.lang.classfile.AccessFlags;
import java.lang.classfile.CodeTransform;
import java.lang.classfile.TypeKind;
import java.lang.constant.MethodTypeDesc;
import java.lang.reflect.AccessFlag;
import jdk.internal.classfile.impl.CodeLocalsShifterImpl;
/**
* {@link CodeLocalsShifter} is a {@link CodeTransform} shifting locals to
* newly allocated positions to avoid conflicts during code injection.
* Locals pointing to the receiver or to method arguments slots are never shifted.
* All locals pointing beyond the method arguments are re-indexed in order of appearance.
*
* @since 24
*/
public sealed interface CodeLocalsShifter extends CodeTransform permits CodeLocalsShifterImpl {
/**
* Creates a new instance of {@link CodeLocalsShifter}
* with fixed local slots calculated from provided method information.
* @param methodFlags flags of the method to construct {@link CodeLocalsShifter} for
* @param methodDescriptor descriptor of the method to construct {@link CodeLocalsShifter} for
* @return new instance of {@link CodeLocalsShifter}
*/
static CodeLocalsShifter of(AccessFlags methodFlags, MethodTypeDesc methodDescriptor) {
int fixed = methodFlags.has(AccessFlag.STATIC) ? 0 : 1;
for (var param : methodDescriptor.parameterList())
fixed += TypeKind.from(param).slotSize();
return new CodeLocalsShifterImpl(fixed);
}
}

View file

@ -1,79 +0,0 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.classfile.components;
import java.lang.classfile.CodeBuilder;
import java.lang.classfile.CodeTransform;
import java.lang.classfile.Label;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.function.BiFunction;
import jdk.internal.classfile.impl.CodeRelabelerImpl;
import static java.util.Objects.requireNonNull;
/**
* A code relabeler is a {@link CodeTransform} replacing all occurrences
* of {@link java.lang.classfile.Label} in the transformed code with new instances.
* All {@link java.lang.classfile.instruction.LabelTarget} instructions are adjusted accordingly.
* Relabeled code graph is identical to the original.
* <p>
* Primary purpose of CodeRelabeler is for repeated injections of the same code blocks.
* Repeated injection of the same code block must be relabeled, so each instance of
* {@link java.lang.classfile.Label} is bound in the target bytecode exactly once.
*
* @since 24
*/
public sealed interface CodeRelabeler extends CodeTransform permits CodeRelabelerImpl {
/**
* Creates a new instance of CodeRelabeler.
* @return a new instance of CodeRelabeler
*/
static CodeRelabeler of() {
return of(new IdentityHashMap<>());
}
/**
* Creates a new instance of CodeRelabeler storing the label mapping into the provided map.
* @param map label map actively used for relabeling
* @return a new instance of CodeRelabeler
*/
static CodeRelabeler of(Map<Label, Label> map) {
requireNonNull(map);
return of((l, cob) -> map.computeIfAbsent(l, ll -> cob.newLabel()));
}
/**
* Creates a new instance of CodeRelabeler using provided {@link java.util.function.BiFunction}
* to re-label the code.
* @param mapFunction function for remapping labels in the source code model
* @return a new instance of CodeRelabeler
*/
static CodeRelabeler of(BiFunction<Label, CodeBuilder, Label> mapFunction) {
return new CodeRelabelerImpl(requireNonNull(mapFunction));
}
}

View file

@ -1,89 +0,0 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.classfile.components;
import java.lang.classfile.CodeTransform;
import java.lang.classfile.Label;
import java.lang.classfile.TypeKind;
import java.util.Collection;
import java.util.Optional;
import jdk.internal.classfile.impl.CodeStackTrackerImpl;
/**
* {@link CodeStackTracker} is a {@link CodeTransform} tracking stack content
* and calculating max stack size.
* <p>
* Sample use:
*
* {@snippet lang=java :
* var stackTracker = CodeStackTracker.of();
* codeBuilder.transforming(stackTracker, trackedBuilder -> {
* trackedBuilder.aload(0);
* trackedBuilder.lconst_0();
* trackedBuilder.ifThen(...);
* ...
* var stack = stackTracker.stack().get();
* int maxStack = stackTracker.maxStackSize().get();
* });
* }
*
* @since 24
*/
public sealed interface CodeStackTracker extends CodeTransform permits CodeStackTrackerImpl {
/**
* Creates new instance of {@link CodeStackTracker} initialized with provided stack items.
* @param initialStack initial stack content
* @return new instance of {@link CodeStackTracker}
*/
static CodeStackTracker of(TypeKind... initialStack) {
return new CodeStackTrackerImpl(initialStack);
}
/**
* Returns {@linkplain Collection} of {@linkplain TypeKind} representing current stack.
* Returns an empty {@linkplain Optional} when the Stack content is unknown
* (right after {@code xRETURN, ATHROW, GOTO, GOTO_W, LOOKUPSWITCH, TABLESWITCH} instructions).
* <p>
* Temporary unknown stack content can be recovered by binding of a {@linkplain Label} used as
* target of a branch instruction from existing code with known stack (forward branch target),
* or by binding of a {@linkplain Label} defining an exception handler (exception handler code start).
*
* @return actual stack content, or an empty {@linkplain Optional} if unknown
*/
Optional<Collection<TypeKind>> stack();
/**
* Returns tracked max stack size.
* Returns an empty {@linkplain Optional} when max stack size tracking has been lost.
* <p>
* Max stack size tracking is permanently lost when a stack instruction appears
* and the actual stack content is unknown.
*
* @return tracked max stack size, or an empty {@linkplain Optional} if tracking has been lost
*/
Optional<Integer> maxStackSize();
}

View file

@ -1,117 +0,0 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* <h2>Provides specific components, transformations, and tools built on top of the
* {@link java.lang.classfile} library.</h2>
*
* The {@code java.lang.classfile.components} package contains specific
* transformation components and utility classes helping to compose very complex
* tasks with minimal effort.
*
* <h3>{@link ClassPrinter}</h3>
* <p>
* {@link ClassPrinter} is a helper class providing seamless export of a {@link
* java.lang.classfile.ClassModel}, {@link java.lang.classfile.FieldModel},
* {@link java.lang.classfile.MethodModel}, or {@link
* java.lang.classfile.CodeModel} into human-readable structured text in
* JSON, XML, or YAML format, or into a tree of traversable and printable nodes.
* <p>
* Primary purpose of {@link ClassPrinter} is to provide human-readable class
* info for debugging, exception handling and logging purposes. The printed
* class also conforms to a standard format to support automated offline
* processing.
* <p>
* The most frequent use case is to simply print a class:
* {@snippet lang="java" class="PackageSnippets" region="printClass"}
* <p>
* {@link ClassPrinter} allows to traverse tree of simple printable nodes to
* hook custom printer:
* {@snippet lang="java" class="PackageSnippets" region="customPrint"}
* <p>
* Another use case for {@link ClassPrinter} is to simplify writing of automated
* tests:
* {@snippet lang="java" class="PackageSnippets" region="printNodesInTest"}
*
* <h3>{@link ClassRemapper}</h3>
* ClassRemapper is a {@link java.lang.classfile.ClassTransform}, {@link
* java.lang.classfile.FieldTransform}, {@link
* java.lang.classfile.MethodTransform} and {@link
* java.lang.classfile.CodeTransform} deeply re-mapping all class references
* in any form, according to given map or map function.
* <p>
* The re-mapping is applied to superclass, interfaces, all kinds of descriptors
* and signatures, all attributes referencing classes in any form (including all
* types of annotations), and to all instructions referencing to classes.
* <p>
* Primitive types and arrays are never subjects of mapping and are not allowed
* targets of mapping.
* <p>
* Arrays of reference types are always decomposed, mapped as the base reference
* types and composed back to arrays.
* <p>
* Single class remapping example:
* {@snippet lang="java" class="PackageSnippets" region="singleClassRemap"}
* <p>
* Remapping of all classes under specific package:
* {@snippet lang="java" class="PackageSnippets" region="allPackageRemap"}
*
* <h3>{@link CodeLocalsShifter}</h3>
* {@link CodeLocalsShifter} is a {@link java.lang.classfile.CodeTransform}
* shifting locals to newly allocated positions to avoid conflicts during code
* injection. Locals pointing to the receiver or to method arguments slots are
* never shifted. All locals pointing beyond the method arguments are re-indexed
* in order of appearance.
* <p>
* Sample of code transformation shifting all locals in all methods:
* {@snippet lang="java" class="PackageSnippets" region="codeLocalsShifting"}
*
* <h3>{@link CodeRelabeler}</h3>
* {@link CodeRelabeler} is a {@link java.lang.classfile.CodeTransform}
* replacing all occurrences of {@link java.lang.classfile.Label} in the
* transformed code with new instances.
* All {@link java.lang.classfile.instruction.LabelTarget} instructions are
* adjusted accordingly.
* Relabeled code graph is identical to the original.
* <p>
* Primary purpose of {@link CodeRelabeler} is for repeated injections of the
* same code blocks.
* Repeated injection of the same code block must be relabeled, so each instance
* of {@link java.lang.classfile.Label} is bound in the target bytecode
* exactly once.
* <p>
* Sample transformation relabeling all methods:
* {@snippet lang="java" class="PackageSnippets" region="codeRelabeling"}
*
* <h3>Class Instrumentation Sample</h3>
* Following snippet is sample composition of {@link ClassRemapper}, {@link
* CodeLocalsShifter} and {@link CodeRelabeler} into fully functional class
* instrumenting transformation:
* {@snippet lang="java" class="PackageSnippets" region="classInstrumentation"}
*
* @since 24
*/
package java.lang.classfile.components;

View file

@ -1,212 +0,0 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.classfile.components.snippets;
import java.lang.classfile.*;
import java.lang.classfile.components.ClassPrinter;
import java.lang.classfile.components.ClassRemapper;
import java.lang.classfile.components.CodeLocalsShifter;
import java.lang.classfile.components.CodeRelabeler;
import java.lang.classfile.instruction.InvokeInstruction;
import java.lang.classfile.instruction.ReturnInstruction;
import java.lang.classfile.instruction.StoreInstruction;
import java.lang.constant.ClassDesc;
import java.lang.constant.ConstantDesc;
import java.lang.constant.ConstantDescs;
import java.lang.reflect.AccessFlag;
import java.util.ArrayDeque;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class PackageSnippets {
void printClass(ClassModel classModel) {
// @start region="printClass"
ClassPrinter.toJson(classModel, ClassPrinter.Verbosity.TRACE_ALL, System.out::print);
// @end
}
// @start region="customPrint"
void customPrint(ClassModel classModel) {
print(ClassPrinter.toTree(classModel, ClassPrinter.Verbosity.TRACE_ALL));
}
void print(ClassPrinter.Node node) {
switch (node) {
case ClassPrinter.MapNode mn -> {
// print map header
mn.values().forEach(this::print);
}
case ClassPrinter.ListNode ln -> {
// print list header
ln.forEach(this::print);
}
case ClassPrinter.LeafNode n -> {
// print leaf node
}
}
}
// @end
// @start region="printNodesInTest"
@Test
void printNodesInTest(ClassModel classModel) {
var classNode = ClassPrinter.toTree(classModel, ClassPrinter.Verbosity.TRACE_ALL);
assertContains(classNode, "method name", "myFooMethod");
assertContains(classNode, "field name", "myBarField");
assertContains(classNode, "inner class", "MyInnerFooClass");
}
void assertContains(ClassPrinter.Node node, ConstantDesc key, ConstantDesc value) {
if (!node.walk().anyMatch(n -> n instanceof ClassPrinter.LeafNode ln
&& ln.name().equals(key)
&& ln.value().equals(value))) {
node.toYaml(System.out::print);
throw new AssertionError("expected %s: %s".formatted(key, value));
}
}
// @end
@interface Test{}
private static final ClassDesc CD_Foo = ClassDesc.of("Foo");
private static final ClassDesc CD_Bar = ClassDesc.of("Bar");
void singleClassRemap(ClassModel... allMyClasses) {
// @start region="singleClassRemap"
var classRemapper = ClassRemapper.of(
Map.of(CD_Foo, CD_Bar));
var cc = ClassFile.of();
for (var classModel : allMyClasses) {
byte[] newBytes = classRemapper.remapClass(cc, classModel);
}
// @end
}
void allPackageRemap(ClassModel... allMyClasses) {
// @start region="allPackageRemap"
var classRemapper = ClassRemapper.of(cd ->
ClassDesc.ofDescriptor(cd.descriptorString().replace("Lcom/oldpackage/", "Lcom/newpackage/")));
var cc = ClassFile.of();
for (var classModel : allMyClasses) {
byte[] newBytes = classRemapper.remapClass(cc, classModel);
}
// @end
}
void codeLocalsShifting(ClassModel classModel) {
// @start region="codeLocalsShifting"
byte[] newBytes = ClassFile.of().transformClass(
classModel,
(classBuilder, classElement) -> {
if (classElement instanceof MethodModel method)
classBuilder.transformMethod(method,
MethodTransform.transformingCode(
CodeLocalsShifter.of(method.flags(), method.methodTypeSymbol())));
else
classBuilder.accept(classElement);
});
// @end
}
void codeRelabeling(ClassModel classModel) {
// @start region="codeRelabeling"
byte[] newBytes = ClassFile.of().transformClass(
classModel,
ClassTransform.transformingMethodBodies(
CodeTransform.ofStateful(CodeRelabeler::of)));
// @end
}
// @start region="classInstrumentation"
byte[] classInstrumentation(ClassModel target, ClassModel instrumentor, Predicate<MethodModel> instrumentedMethodsFilter) {
var instrumentorCodeMap = instrumentor.methods().stream()
.filter(instrumentedMethodsFilter)
.collect(Collectors.toMap(mm -> mm.methodName().stringValue() + mm.methodType().stringValue(), mm -> mm.code().orElseThrow()));
var targetFieldNames = target.fields().stream().map(f -> f.fieldName().stringValue()).collect(Collectors.toSet());
var targetMethods = target.methods().stream().map(m -> m.methodName().stringValue() + m.methodType().stringValue()).collect(Collectors.toSet());
var instrumentorClassRemapper = ClassRemapper.of(Map.of(instrumentor.thisClass().asSymbol(), target.thisClass().asSymbol()));
return ClassFile.of().transformClass(target,
ClassTransform.transformingMethods(
instrumentedMethodsFilter,
(mb, me) -> {
if (me instanceof CodeModel targetCodeModel) {
var mm = targetCodeModel.parent().get();
//instrumented methods code is taken from instrumentor
mb.transformCode(instrumentorCodeMap.get(mm.methodName().stringValue() + mm.methodType().stringValue()),
//all references to the instrumentor class are remapped to target class
instrumentorClassRemapper.asCodeTransform()
.andThen((codeBuilder, instrumentorCodeElement) -> {
//all invocations of target methods from instrumentor are inlined
if (instrumentorCodeElement instanceof InvokeInstruction inv
&& target.thisClass().asInternalName().equals(inv.owner().asInternalName())
&& mm.methodName().stringValue().equals(inv.name().stringValue())
&& mm.methodType().stringValue().equals(inv.type().stringValue())) {
//store stacked method parameters into locals
var storeStack = new ArrayDeque<StoreInstruction>();
int slot = 0;
if (!mm.flags().has(AccessFlag.STATIC))
storeStack.push(StoreInstruction.of(TypeKind.REFERENCE, slot++));
for (var pt : mm.methodTypeSymbol().parameterList()) {
var tk = TypeKind.from(pt);
storeStack.push(StoreInstruction.of(tk, slot));
slot += tk.slotSize();
}
storeStack.forEach(codeBuilder::with);
//inlined target locals must be shifted based on the actual instrumentor locals
codeBuilder.block(inlinedBlockBuilder -> inlinedBlockBuilder
.transform(targetCodeModel, CodeLocalsShifter.of(mm.flags(), mm.methodTypeSymbol())
.andThen(CodeRelabeler.of())
.andThen((innerBuilder, shiftedTargetCode) -> {
//returns must be replaced with jump to the end of the inlined method
if (shiftedTargetCode instanceof ReturnInstruction)
innerBuilder.goto_(inlinedBlockBuilder.breakLabel());
else
innerBuilder.with(shiftedTargetCode);
})));
} else
codeBuilder.with(instrumentorCodeElement);
}));
} else
mb.with(me);
})
.andThen(ClassTransform.endHandler(clb ->
//remaining instrumentor fields and methods are injected at the end
clb.transform(instrumentor,
ClassTransform.dropping(cle ->
!(cle instanceof FieldModel fm
&& !targetFieldNames.contains(fm.fieldName().stringValue()))
&& !(cle instanceof MethodModel mm
&& !ConstantDescs.INIT_NAME.equals(mm.methodName().stringValue())
&& !targetMethods.contains(mm.methodName().stringValue() + mm.methodType().stringValue())))
//and instrumentor class references remapped to target class
.andThen(instrumentorClassRemapper)))));
}
// @end
}

View file

@ -25,21 +25,13 @@
package java.lang.classfile.snippets;
import java.lang.classfile.*;
import java.lang.classfile.components.ClassRemapper;
import java.lang.classfile.components.CodeLocalsShifter;
import java.lang.classfile.components.CodeRelabeler;
import java.lang.classfile.instruction.*;
import java.lang.constant.ClassDesc;
import java.lang.constant.ConstantDescs;
import java.lang.constant.MethodTypeDesc;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.AccessFlag;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toSet;
@ -326,82 +318,6 @@ class PackageSnippets {
// @end
}
void codeRelabeling(ClassModel classModel) {
// @start region="codeRelabeling"
byte[] newBytes = ClassFile.of().transformClass(classModel,
ClassTransform.transformingMethodBodies(
CodeTransform.ofStateful(CodeRelabeler::of)));
// @end
}
// @start region="classInstrumentation"
byte[] classInstrumentation(ClassModel target, ClassModel instrumentor, Predicate<MethodModel> instrumentedMethodsFilter) {
var instrumentorCodeMap = instrumentor.methods().stream()
.filter(instrumentedMethodsFilter)
.collect(Collectors.toMap(mm -> mm.methodName().stringValue() + mm.methodType().stringValue(), mm -> mm.code().orElseThrow()));
var targetFieldNames = target.fields().stream().map(f -> f.fieldName().stringValue()).collect(Collectors.toSet());
var targetMethods = target.methods().stream().map(m -> m.methodName().stringValue() + m.methodType().stringValue()).collect(Collectors.toSet());
var instrumentorClassRemapper = ClassRemapper.of(Map.of(instrumentor.thisClass().asSymbol(), target.thisClass().asSymbol()));
return ClassFile.of().transformClass(target,
ClassTransform.transformingMethods(
instrumentedMethodsFilter,
(mb, me) -> {
if (me instanceof CodeModel targetCodeModel) {
var mm = targetCodeModel.parent().get();
//instrumented methods code is taken from instrumentor
mb.transformCode(instrumentorCodeMap.get(mm.methodName().stringValue() + mm.methodType().stringValue()),
//all references to the instrumentor class are remapped to target class
instrumentorClassRemapper.asCodeTransform()
.andThen((codeBuilder, instrumentorCodeElement) -> {
//all invocations of target methods from instrumentor are inlined
if (instrumentorCodeElement instanceof InvokeInstruction inv
&& target.thisClass().asInternalName().equals(inv.owner().asInternalName())
&& mm.methodName().stringValue().equals(inv.name().stringValue())
&& mm.methodType().stringValue().equals(inv.type().stringValue())) {
//store stacked method parameters into locals
var storeStack = new ArrayDeque<StoreInstruction>();
int slot = 0;
if (!mm.flags().has(AccessFlag.STATIC))
storeStack.push(StoreInstruction.of(TypeKind.REFERENCE, slot++));
for (var pt : mm.methodTypeSymbol().parameterList()) {
var tk = TypeKind.from(pt);
storeStack.push(StoreInstruction.of(tk, slot));
slot += tk.slotSize();
}
storeStack.forEach(codeBuilder::with);
//inlined target locals must be shifted based on the actual instrumentor locals
codeBuilder.block(inlinedBlockBuilder -> inlinedBlockBuilder
.transform(targetCodeModel, CodeLocalsShifter.of(mm.flags(), mm.methodTypeSymbol())
.andThen(CodeRelabeler.of())
.andThen((innerBuilder, shiftedTargetCode) -> {
//returns must be replaced with jump to the end of the inlined method
if (shiftedTargetCode instanceof ReturnInstruction)
innerBuilder.goto_(inlinedBlockBuilder.breakLabel());
else
innerBuilder.with(shiftedTargetCode);
})));
} else
codeBuilder.with(instrumentorCodeElement);
}));
} else
mb.with(me);
})
.andThen(ClassTransform.endHandler(clb ->
//remaining instrumentor fields and methods are injected at the end
clb.transform(instrumentor,
ClassTransform.dropping(cle ->
!(cle instanceof FieldModel fm
&& !targetFieldNames.contains(fm.fieldName().stringValue()))
&& !(cle instanceof MethodModel mm
&& !ConstantDescs.INIT_NAME.equals(mm.methodName().stringValue())
&& !targetMethods.contains(mm.methodName().stringValue() + mm.methodType().stringValue())))
//and instrumentor class references remapped to target class
.andThen(instrumentorClassRemapper)))));
}
// @end
void resolverExample() {
// @start region="lookup-class-hierarchy-resolver"
MethodHandles.Lookup lookup = MethodHandles.lookup(); // @replace regex="MethodHandles\.lookup\(\)" replacement="..."