Add classfile-api module: java.lang.classfile (JEP 484) parse, generate, transform with timing instrumentation, ASM 9.11.1 comparison, version limits, JDK 24/25/26 API diff
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4VQVEJWetTT1dYzyJ
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
package demo;
|
||||
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
|
||||
/** The GenerateDemo task done with ASM 9.11.1: the same class, demo.Generated, same four methods. */
|
||||
public class AsmGenerate implements Opcodes {
|
||||
|
||||
static byte[] generate() {
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
|
||||
cw.visit(V25, ACC_PUBLIC | ACC_SUPER, "demo/Generated", null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(ALOAD, 0);
|
||||
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||
mv.visitInsn(RETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
|
||||
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(ILOAD, 0);
|
||||
mv.visitVarInsn(ILOAD, 1);
|
||||
mv.visitInsn(IADD);
|
||||
mv.visitInsn(IRETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
|
||||
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "hello", "()Ljava/lang/String;", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitLdcInsn("Hello from generated bytecode");
|
||||
mv.visitInsn(ARETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
|
||||
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "sumTo", "(I)J", null, null);
|
||||
mv.visitCode();
|
||||
Label loop = new Label(), end = new Label();
|
||||
mv.visitInsn(LCONST_0);
|
||||
mv.visitVarInsn(LSTORE, 1);
|
||||
mv.visitInsn(ICONST_1);
|
||||
mv.visitVarInsn(ISTORE, 3);
|
||||
mv.visitLabel(loop);
|
||||
mv.visitVarInsn(ILOAD, 3);
|
||||
mv.visitVarInsn(ILOAD, 0);
|
||||
mv.visitJumpInsn(IF_ICMPGT, end);
|
||||
mv.visitVarInsn(LLOAD, 1);
|
||||
mv.visitVarInsn(ILOAD, 3);
|
||||
mv.visitInsn(I2L);
|
||||
mv.visitInsn(LADD);
|
||||
mv.visitVarInsn(LSTORE, 1);
|
||||
mv.visitIincInsn(3, 1);
|
||||
mv.visitJumpInsn(GOTO, loop);
|
||||
mv.visitLabel(end);
|
||||
mv.visitVarInsn(LLOAD, 1);
|
||||
mv.visitInsn(LRETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
|
||||
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "classify", "(I)Ljava/lang/String;", null, null);
|
||||
mv.visitCode();
|
||||
Label nonNeg = new Label(), done = new Label();
|
||||
mv.visitVarInsn(ILOAD, 0);
|
||||
mv.visitJumpInsn(IFGE, nonNeg);
|
||||
mv.visitLdcInsn("negative");
|
||||
mv.visitJumpInsn(GOTO, done);
|
||||
mv.visitLabel(nonNeg);
|
||||
mv.visitLdcInsn("non-negative");
|
||||
mv.visitLabel(done);
|
||||
mv.visitInsn(ARETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
|
||||
cw.visitEnd();
|
||||
return cw.toByteArray();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
byte[] asm = generate();
|
||||
byte[] cfApi = GenerateDemo.generate(java.lang.classfile.ClassFile.of());
|
||||
System.out.println("ASM generated " + asm.length + " bytes; java.lang.classfile generated " + cfApi.length + " bytes");
|
||||
Check.that(java.lang.classfile.ClassFile.of().verify(asm).isEmpty(), "ASM output passes ClassFile.verify()");
|
||||
Class<?> c = MethodHandles.lookup().defineClass(asm);
|
||||
GenerateDemo.exercise(c, "ASM-generated");
|
||||
var a = java.lang.classfile.ClassFile.of().parse(asm);
|
||||
var b = java.lang.classfile.ClassFile.of().parse(cfApi);
|
||||
Check.that(ParseDemo.methodLines(a).equals(ParseDemo.methodLines(b)), "both generators emit the same method list");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package demo;
|
||||
|
||||
/** The first thing that went wrong writing the ASM version: AdviceAdapter without ClassReader.EXPAND_FRAMES. */
|
||||
public class AsmGotcha {
|
||||
public static void main(String[] args) {
|
||||
AsmInstrument.readerFlags = 0; // what you get if you copy a ClassVisitor example and pass 0
|
||||
try {
|
||||
AsmInstrument.instrument(Bytes.of(Target.class));
|
||||
Check.that(false, "AdviceAdapter without EXPAND_FRAMES should have thrown");
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.out.println("readerFlags = 0 -> " + e.getClass().getName());
|
||||
System.out.println(" " + e.getMessage());
|
||||
Check.that(e.getMessage().contains("EXPAND_FRAMES"), "the message names the missing flag");
|
||||
}
|
||||
AsmInstrument.readerFlags = org.objectweb.asm.ClassReader.EXPAND_FRAMES;
|
||||
byte[] ok = AsmInstrument.instrument(Bytes.of(Target.class));
|
||||
System.out.println("readerFlags = EXPAND_FRAMES -> " + ok.length + " bytes, verify() problems: " + java.lang.classfile.ClassFile.of().verify(ok).size());
|
||||
Check.that(java.lang.classfile.ClassFile.of().verify(ok).isEmpty(), "with EXPAND_FRAMES the output verifies");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package demo;
|
||||
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.commons.AdviceAdapter;
|
||||
|
||||
/** The TimingTransform task done with ASM 9.11.1 (AdviceAdapter from asm-commons): same semantics as the "full" ClassFile version. */
|
||||
public class AsmInstrument {
|
||||
static int readerFlags = ClassReader.EXPAND_FRAMES; // AdviceAdapter extends LocalVariablesSorter, which throws without it
|
||||
|
||||
public static byte[] instrument(byte[] original) {
|
||||
ClassReader cr = new ClassReader(original);
|
||||
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
|
||||
String simple = cr.getClassName().substring(cr.getClassName().lastIndexOf('/') + 1);
|
||||
cr.accept(new ClassVisitor(Opcodes.ASM9, cw) {
|
||||
@Override public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] ex) {
|
||||
MethodVisitor mv = super.visitMethod(access, name, desc, sig, ex);
|
||||
if (name.equals("<init>") || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) return mv;
|
||||
return new AdviceAdapter(Opcodes.ASM9, mv, access, name, desc) {
|
||||
final Label tryStart = new Label(), tryEnd = new Label(), handler = new Label();
|
||||
int startSlot;
|
||||
|
||||
@Override protected void onMethodEnter() {
|
||||
startSlot = newLocal(Type.LONG_TYPE);
|
||||
invokeStatic(Type.getType(System.class), new org.objectweb.asm.commons.Method("nanoTime", "()J"));
|
||||
storeLocal(startSlot);
|
||||
visitLabel(tryStart);
|
||||
}
|
||||
|
||||
@Override protected void onMethodExit(int opcode) {
|
||||
if (opcode != ATHROW) emitRecord(); // athrow is covered by the catch-all handler below
|
||||
}
|
||||
|
||||
@Override public void visitMaxs(int maxStack, int maxLocals) {
|
||||
visitLabel(tryEnd);
|
||||
visitLabel(handler);
|
||||
int ex = newLocal(Type.getType(Throwable.class));
|
||||
storeLocal(ex);
|
||||
emitRecord();
|
||||
loadLocal(ex);
|
||||
visitInsn(ATHROW);
|
||||
visitTryCatchBlock(tryStart, tryEnd, handler, null);
|
||||
super.visitMaxs(maxStack, maxLocals);
|
||||
}
|
||||
|
||||
private void emitRecord() {
|
||||
visitLdcInsn(simple + "." + name);
|
||||
invokeStatic(Type.getType(System.class), new org.objectweb.asm.commons.Method("nanoTime", "()J"));
|
||||
loadLocal(startSlot);
|
||||
visitInsn(LSUB);
|
||||
invokeStatic(Type.getObjectType("demo/Timings"), new org.objectweb.asm.commons.Method("record", "(Ljava/lang/String;J)V"));
|
||||
}
|
||||
};
|
||||
}
|
||||
}, readerFlags);
|
||||
return cw.toByteArray();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
byte[] original = Bytes.of(Target.class);
|
||||
byte[] viaAsm = instrument(original);
|
||||
System.out.println("original " + original.length + " bytes, ASM-instrumented " + viaAsm.length + " bytes");
|
||||
Check.that(java.lang.classfile.ClassFile.of().verify(viaAsm).isEmpty(), "ASM output passes ClassFile.verify()");
|
||||
|
||||
TransformDemo.report("ASM AdviceAdapter version", viaAsm);
|
||||
Check.that(Timings.get("Target.boom").count() == 1 && Timings.get("Target.explode").count() == 1, "ASM version also records both throwing methods once");
|
||||
Check.that(Timings.get("Target.fib").count() == 177, "ASM version: fib recorded 177 times");
|
||||
Check.that(Timings.get("Target.pause").totalNanos() >= 50_000_000L, "ASM version: pause(50) recorded as at least 50 ms");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package demo;
|
||||
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** The ParseDemo task done with ASM 9.11.1 (visitor API): list methods, count invoke targets. */
|
||||
public class AsmParse {
|
||||
record Result(List<String> methodLines, TreeMap<String, Integer> invokes, int major) { }
|
||||
|
||||
static Result parse(byte[] bytes) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
TreeMap<String, Integer> invokes = new TreeMap<>();
|
||||
ClassReader cr = new ClassReader(bytes);
|
||||
cr.accept(new ClassVisitor(Opcodes.ASM9) {
|
||||
@Override public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] ex) {
|
||||
lines.add(flags(access) + name + desc);
|
||||
return new MethodVisitor(Opcodes.ASM9) {
|
||||
@Override public void visitMethodInsn(int op, String owner, String n, String d, boolean itf) {
|
||||
invokes.merge(owner + "." + n, 1, Integer::sum);
|
||||
}
|
||||
@Override public void visitInvokeDynamicInsn(String n, String d, org.objectweb.asm.Handle bsm, Object... args) {
|
||||
invokes.merge("indy:" + n, 1, Integer::sum);
|
||||
}
|
||||
};
|
||||
}
|
||||
}, ClassReader.SKIP_DEBUG);
|
||||
return new Result(lines, invokes, cr.readShort(6));
|
||||
}
|
||||
|
||||
/** Same format as ParseDemo.flags: lower-case names, sorted, comma-joined. */
|
||||
static String flags(int access) {
|
||||
List<String> f = new ArrayList<>();
|
||||
if ((access & Opcodes.ACC_PUBLIC) != 0) f.add("public");
|
||||
if ((access & Opcodes.ACC_STATIC) != 0) f.add("static");
|
||||
return String.join(",", f) + " ";
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
byte[] bytes = Bytes.of(Target.class);
|
||||
Result r = parse(bytes);
|
||||
System.out.println("ASM sees major version " + r.major());
|
||||
r.methodLines().forEach(l -> System.out.println(" " + l));
|
||||
r.invokes().forEach((k, v) -> System.out.println(" " + v + " x " + k));
|
||||
|
||||
var cf = java.lang.classfile.ClassFile.of().parse(bytes);
|
||||
Check.that(r.methodLines().equals(ParseDemo.methodLines(cf)), "ASM and java.lang.classfile list identical method lines");
|
||||
Check.that(r.invokes().equals(ParseDemo.invokeCounts(cf)), "ASM and java.lang.classfile count identical invoke targets");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package demo;
|
||||
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.classfile.ClassModel;
|
||||
import java.lang.classfile.ClassTransform;
|
||||
import java.lang.classfile.CodeElement;
|
||||
import java.lang.classfile.Instruction;
|
||||
import java.lang.classfile.MethodModel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.ToLongFunction;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* A deliberately simple, INDICATIVE comparison (no JMH): parse and visit every instruction of the first N java.base classes,
|
||||
* and parse + copy + write them back. Warm-up rounds first, then the median of the measured rounds.
|
||||
* Time is the benchmark thread's own CPU time (not wall-clock), because the sandbox is a shared 2-vCPU machine and wall-clock
|
||||
* numbers swing with whatever else is running. JIT and GC threads are therefore NOT included. Read the ratio, not the milliseconds.
|
||||
*/
|
||||
public class Bench {
|
||||
static final int N = 2000, WARMUP = 4, ROUNDS = 9;
|
||||
static final java.lang.management.ThreadMXBean CPU = java.lang.management.ManagementFactory.getThreadMXBean();
|
||||
|
||||
static long cfWalk(byte[] b) {
|
||||
ClassModel cm = ClassFile.of().parse(b);
|
||||
long n = 0;
|
||||
for (MethodModel m : cm.methods()) {
|
||||
if (m.code().isPresent()) {
|
||||
for (CodeElement e : m.code().get()) if (e instanceof Instruction) n++;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static long asmWalk(byte[] b) {
|
||||
long[] n = {0};
|
||||
new ClassReader(b).accept(new ClassVisitor(Opcodes.ASM9) {
|
||||
@Override public MethodVisitor visitMethod(int a, String nm, String d, String s, String[] e) {
|
||||
return new MethodVisitor(Opcodes.ASM9) {
|
||||
@Override public void visitInsn(int o) { n[0]++; }
|
||||
@Override public void visitIntInsn(int o, int x) { n[0]++; }
|
||||
@Override public void visitVarInsn(int o, int x) { n[0]++; }
|
||||
@Override public void visitTypeInsn(int o, String t) { n[0]++; }
|
||||
@Override public void visitFieldInsn(int o, String a, String b, String c) { n[0]++; }
|
||||
@Override public void visitMethodInsn(int o, String a, String b, String c, boolean i) { n[0]++; }
|
||||
@Override public void visitInvokeDynamicInsn(String a, String b, org.objectweb.asm.Handle h, Object... r) { n[0]++; }
|
||||
@Override public void visitJumpInsn(int o, org.objectweb.asm.Label l) { n[0]++; }
|
||||
@Override public void visitLdcInsn(Object v) { n[0]++; }
|
||||
@Override public void visitIincInsn(int v, int i) { n[0]++; }
|
||||
@Override public void visitTableSwitchInsn(int a, int b, org.objectweb.asm.Label d, org.objectweb.asm.Label... l) { n[0]++; }
|
||||
@Override public void visitLookupSwitchInsn(org.objectweb.asm.Label d, int[] k, org.objectweb.asm.Label[] l) { n[0]++; }
|
||||
@Override public void visitMultiANewArrayInsn(String d, int x) { n[0]++; }
|
||||
};
|
||||
}
|
||||
}, 0);
|
||||
return n[0];
|
||||
}
|
||||
|
||||
static long cfCopy(byte[] b) {
|
||||
ClassFile cf = ClassFile.of();
|
||||
return cf.transformClass(cf.parse(b), ClassTransform.ACCEPT_ALL).length;
|
||||
}
|
||||
|
||||
static long asmCopy(byte[] b) {
|
||||
ClassReader cr = new ClassReader(b);
|
||||
ClassWriter cw = new ClassWriter(cr, 0);
|
||||
cr.accept(cw, 0);
|
||||
return cw.toByteArray().length;
|
||||
}
|
||||
|
||||
static double medianMs(List<byte[]> classes, ToLongFunction<byte[]> f) {
|
||||
double[] t = new double[ROUNDS];
|
||||
long sink = 0;
|
||||
for (int i = 0; i < WARMUP; i++) for (byte[] b : classes) sink += f.applyAsLong(b);
|
||||
for (int r = 0; r < ROUNDS; r++) {
|
||||
long t0 = CPU.getCurrentThreadCpuTime();
|
||||
for (byte[] b : classes) sink += f.applyAsLong(b);
|
||||
t[r] = (CPU.getCurrentThreadCpuTime() - t0) / 1e6;
|
||||
}
|
||||
if (sink == 42) System.out.print("");
|
||||
Arrays.sort(t);
|
||||
return t[ROUNDS / 2];
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
List<byte[]> classes = new ArrayList<>();
|
||||
try (Stream<Path> s = Files.walk(Bytes.jrtRoot("java.base"))) {
|
||||
for (Path p : (Iterable<Path>) s.filter(x -> x.toString().endsWith(".class") && !x.toString().endsWith("module-info.class")).sorted().limit(N)::iterator) {
|
||||
classes.add(Files.readAllBytes(p));
|
||||
}
|
||||
}
|
||||
long total = classes.stream().mapToLong(b -> b.length).sum();
|
||||
long insnCf = 0, insnAsm = 0;
|
||||
for (byte[] b : classes) { insnCf += cfWalk(b); insnAsm += asmWalk(b); }
|
||||
System.out.println("running on Java " + Runtime.version() + ", ASM 9.11.1; INDICATIVE numbers, thread CPU time, shared 2-vCPU sandbox, no JMH");
|
||||
System.out.println(classes.size() + " classes from java.base, " + total / 1024 + " KiB; " + WARMUP + " warm-up rounds, median of " + ROUNDS);
|
||||
System.out.println("instructions seen: java.lang.classfile " + insnCf + ", ASM " + insnAsm);
|
||||
Check.that(insnCf > 0 && insnCf == insnAsm, "both walkers see exactly the same number of instructions");
|
||||
|
||||
double cfW = medianMs(classes, Bench::cfWalk), asmW = medianMs(classes, Bench::asmWalk);
|
||||
double cfC = medianMs(classes, Bench::cfCopy), asmC = medianMs(classes, Bench::asmCopy);
|
||||
System.out.printf("parse + visit every instruction : java.lang.classfile %7.1f ms ASM %7.1f ms (ASM / classfile = %.2f)%n", cfW, asmW, asmW / cfW);
|
||||
System.out.printf("parse + copy + write back : java.lang.classfile %7.1f ms ASM %7.1f ms (ASM / classfile = %.2f)%n", cfC, asmC, asmC / cfC);
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package demo;
|
||||
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.classfile.Label;
|
||||
import java.lang.classfile.TypeKind;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.lang.constant.MethodTypeDesc;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.util.List;
|
||||
|
||||
import static java.lang.constant.ConstantDescs.*;
|
||||
|
||||
/** Three ways to produce a bad class, and what each one looks like. */
|
||||
public class BrokenGenerate {
|
||||
static final ClassDesc C = ClassDesc.of("demo", "Broken");
|
||||
|
||||
/** static int pick(int n) { return n > 0 ? 1 : 2; } -- needs a StackMapTable because it branches. */
|
||||
static byte[] branching(ClassFile cf) {
|
||||
return cf.build(C, clb -> clb.withMethodBody("pick", MethodTypeDesc.of(CD_int, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||
Label other = cob.newLabel(), done = cob.newLabel();
|
||||
cob.iload(0).ifle(other).iconst_1().goto_(done).labelBinding(other).iconst_2().labelBinding(done).ireturn();
|
||||
}));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
// 1. Same method, stack maps dropped on request.
|
||||
byte[] noMaps = branching(ClassFile.of(ClassFile.StackMapsOption.DROP_STACK_MAPS));
|
||||
List<VerifyError> v = ClassFile.of().verify(noMaps);
|
||||
System.out.println("DROP_STACK_MAPS: verify() -> " + v.size() + " problem(s)");
|
||||
v.forEach(e -> System.out.println(" " + e.getMessage().lines().findFirst().orElse("")));
|
||||
try {
|
||||
MethodHandles.lookup().defineClass(noMaps);
|
||||
} catch (VerifyError e) {
|
||||
System.out.println("DROP_STACK_MAPS: defineClass -> java.lang.VerifyError");
|
||||
e.getMessage().lines().limit(3).forEach(l -> System.out.println(" " + l));
|
||||
}
|
||||
Check.that(!v.isEmpty(), "a branching method built without stack maps fails verification");
|
||||
|
||||
// 2. The default (stack maps generated when required) is fine for the very same code.
|
||||
Check.that(ClassFile.of().verify(branching(ClassFile.of())).isEmpty(), "the same code with default options verifies");
|
||||
|
||||
// 3. Type confusion: ireturn on a method declared to return String. The builder does not stop you.
|
||||
byte[] wrong = ClassFile.of().build(ClassDesc.of("demo", "Wrong"), clb -> clb.withMethodBody("bad",
|
||||
MethodTypeDesc.of(CD_String), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob.iconst_1().ireturn()));
|
||||
System.out.println("ireturn in a String method: build() succeeded (" + wrong.length + " bytes)");
|
||||
List<VerifyError> w = ClassFile.of().verify(wrong);
|
||||
w.forEach(e -> System.out.println(" verify: " + e.getMessage().lines().findFirst().orElse("")));
|
||||
Check.that(!w.isEmpty(), "verify() catches a wrongly typed return");
|
||||
|
||||
// 4. Stack underflow while generating with stack maps: the generator itself throws.
|
||||
try {
|
||||
ClassFile.of().build(ClassDesc.of("demo", "Under"), clb -> clb.withMethodBody("u", MethodTypeDesc.of(CD_int),
|
||||
ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||
Label l = cob.newLabel();
|
||||
cob.iadd().goto_(l).labelBinding(l).iconst_0().ireturn();
|
||||
}));
|
||||
System.out.println("underflow: build() succeeded");
|
||||
Check.that(false, "stack underflow is caught while building");
|
||||
} catch (RuntimeException e) {
|
||||
Check.that(e instanceof IllegalArgumentException, "stack underflow is caught while building");
|
||||
System.out.println("underflow: build() threw " + e.getClass().getName());
|
||||
System.out.println(" " + e.getMessage().lines().findFirst().orElse(""));
|
||||
}
|
||||
|
||||
// 5. exceptionCatchAll(start, end, handler): three Labels, so swapping them compiles. verify() says nothing; the JVM objects.
|
||||
byte[] swapped = ClassFile.of().build(ClassDesc.of("demo", "Swapped"), clb -> clb.withMethodBody("s",
|
||||
MethodTypeDesc.of(CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||
Label start = cob.newLabel(), end = cob.newLabel(), handler = cob.newLabel();
|
||||
cob.labelBinding(start).iconst_1().labelBinding(end).ireturn()
|
||||
.labelBinding(handler).pop().iconst_0().ireturn()
|
||||
.exceptionCatchAll(handler, start, end); // WRONG order on purpose; correct is (start, end, handler)
|
||||
}));
|
||||
System.out.println("swapped labels: build() succeeded (" + swapped.length + " bytes), verify() -> " + ClassFile.of().verify(swapped).size() + " problem(s)");
|
||||
try {
|
||||
MethodHandles.lookup().defineClass(swapped);
|
||||
Check.that(false, "the JVM rejects the swapped exception-table labels");
|
||||
} catch (ClassFormatError e) {
|
||||
System.out.println("swapped labels: defineClass -> " + e.getClass().getName() + ": " + e.getMessage());
|
||||
Check.that(true, "the JVM rejects the swapped exception-table labels");
|
||||
}
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package demo;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Where class-file bytes come from in the demos. */
|
||||
public final class Bytes {
|
||||
private Bytes() { }
|
||||
|
||||
/** The bytes javac produced for one of our own classes, read from the class path. */
|
||||
public static byte[] of(Class<?> c) {
|
||||
try (InputStream in = c.getResourceAsStream(c.getSimpleName() + ".class")) {
|
||||
return in.readAllBytes();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** A JDK class, read from the runtime image through the jrt: file system. */
|
||||
public static byte[] jdk(String module, String internalName) {
|
||||
try {
|
||||
FileSystem jrt = FileSystems.getFileSystem(URI.create("jrt:/"));
|
||||
return Files.readAllBytes(jrt.getPath("modules", module, internalName + ".class"));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Path jrtRoot(String module) {
|
||||
return FileSystems.getFileSystem(URI.create("jrt:/")).getPath("modules", module);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package demo;
|
||||
|
||||
/** Tiny assertion helper: prints PASS/FAIL and fails the process at the end, like the other standalone modules. */
|
||||
public final class Check {
|
||||
private static int failures;
|
||||
|
||||
private Check() { }
|
||||
|
||||
public static void that(boolean ok, String what) {
|
||||
System.out.println((ok ? "PASS " : "FAIL ") + what);
|
||||
if (!ok) failures++;
|
||||
}
|
||||
|
||||
public static void finish() {
|
||||
if (failures > 0) {
|
||||
System.out.println(failures + " check(s) FAILED");
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package demo;
|
||||
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.classfile.Label;
|
||||
import java.lang.classfile.TypeKind;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.lang.constant.MethodTypeDesc;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static java.lang.constant.ConstantDescs.*;
|
||||
|
||||
/** Generating a class from scratch with ClassFile.build, then defining it at runtime. */
|
||||
public class GenerateDemo {
|
||||
static final ClassDesc GENERATED = ClassDesc.of("demo", "Generated");
|
||||
|
||||
/** public class demo.Generated { add(int,int), hello(), sumTo(int), classify(int) }. */
|
||||
static byte[] generate(ClassFile cf) {
|
||||
return cf.build(GENERATED, clb -> clb
|
||||
.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_SUPER)
|
||||
.withMethodBody(INIT_NAME, MTD_void, ClassFile.ACC_PUBLIC, cob -> cob
|
||||
.aload(0)
|
||||
.invokespecial(CD_Object, INIT_NAME, MTD_void)
|
||||
.return_())
|
||||
// static int add(int a, int b) { return a + b; }
|
||||
.withMethodBody("add", MethodTypeDesc.of(CD_int, CD_int, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob
|
||||
.iload(0).iload(1).iadd().ireturn())
|
||||
// static String hello() { return "Hello from generated bytecode"; }
|
||||
.withMethodBody("hello", MethodTypeDesc.of(CD_String), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob
|
||||
.ldc("Hello from generated bytecode").areturn())
|
||||
// static long sumTo(int n) { long s = 0; for (int i = 1; i <= n; i++) s += i; return s; }
|
||||
.withMethodBody("sumTo", MethodTypeDesc.of(CD_long, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||
int s = cob.allocateLocal(TypeKind.LONG);
|
||||
int i = cob.allocateLocal(TypeKind.INT);
|
||||
Label loop = cob.newLabel(), end = cob.newLabel();
|
||||
cob.lconst_0().lstore(s)
|
||||
.iconst_1().istore(i)
|
||||
.labelBinding(loop)
|
||||
.iload(i).iload(0).if_icmpgt(end)
|
||||
.lload(s).iload(i).i2l().ladd().lstore(s)
|
||||
.iinc(i, 1)
|
||||
.goto_(loop)
|
||||
.labelBinding(end)
|
||||
.lload(s).lreturn();
|
||||
})
|
||||
// static String classify(int n) { return n < 0 ? "negative" : "non-negative"; }
|
||||
.withMethodBody("classify", MethodTypeDesc.of(CD_String, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob
|
||||
.iload(0)
|
||||
.ifThenElse(java.lang.classfile.Opcode.IFLT,
|
||||
t -> t.ldc("negative"),
|
||||
e -> e.ldc("non-negative"))
|
||||
.areturn()));
|
||||
}
|
||||
|
||||
static void exercise(Class<?> c, String how) throws Throwable {
|
||||
MethodHandles.Lookup l = MethodHandles.publicLookup();
|
||||
MethodHandle add = l.findStatic(c, "add", MethodType.methodType(int.class, int.class, int.class));
|
||||
MethodHandle hello = l.findStatic(c, "hello", MethodType.methodType(String.class));
|
||||
MethodHandle sum = l.findStatic(c, "sumTo", MethodType.methodType(long.class, int.class));
|
||||
MethodHandle cls = l.findStatic(c, "classify", MethodType.methodType(String.class, int.class));
|
||||
int a = (int) add.invoke(2, 3);
|
||||
String h = (String) hello.invoke();
|
||||
long s = (long) sum.invoke(100);
|
||||
String neg = (String) cls.invoke(-4), pos = (String) cls.invoke(4);
|
||||
System.out.println("[" + how + "] add(2,3)=" + a + " hello()=" + h + " sumTo(100)=" + s
|
||||
+ " classify(-4)=" + neg + " classify(4)=" + pos);
|
||||
Check.that(a == 5 && s == 5050L && "negative".equals(neg) && "non-negative".equals(pos), how + ": generated methods return the right values");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ClassFile cf = ClassFile.of();
|
||||
byte[] bytes = generate(cf);
|
||||
Path outDir = Path.of(args.length > 0 ? args[0] : "target/gen/demo");
|
||||
Files.createDirectories(outDir);
|
||||
Files.write(outDir.resolve("Generated.class"), bytes);
|
||||
System.out.println("generated " + bytes.length + " bytes, major version " + cf.parse(bytes).majorVersion()
|
||||
+ " (wrote " + outDir.resolve("Generated.class") + ")");
|
||||
|
||||
// 1. Verify without loading: returns a list of VerifyError, empty if the class is well formed.
|
||||
List<VerifyError> problems = cf.verify(bytes);
|
||||
System.out.println("ClassFile.verify(bytes) -> " + problems.size() + " problem(s)");
|
||||
Check.that(problems.isEmpty(), "verify() finds nothing wrong with the generated class");
|
||||
|
||||
// 2. Define it as an ordinary class in this package (Lookup.defineClass needs the same package as the lookup class).
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
Class<?> normal = lookup.defineClass(bytes);
|
||||
System.out.println("defineClass -> " + normal.getName() + " hidden=" + normal.isHidden()
|
||||
+ " findable by name=" + (Class.forName("demo.Generated") == normal));
|
||||
exercise(normal, "defineClass");
|
||||
|
||||
// 3. Define the same bytes as a hidden class: no name anyone can resolve, unloadable with its defining loader's GC.
|
||||
MethodHandles.Lookup hiddenLookup = lookup.defineHiddenClass(bytes, true);
|
||||
Class<?> hidden = hiddenLookup.lookupClass();
|
||||
System.out.println("defineHiddenClass -> name starts with 'demo.Generated/': " + hidden.getName().startsWith("demo.Generated/")
|
||||
+ " hidden=" + hidden.isHidden() + " distinct from the normal class=" + (hidden != normal));
|
||||
exercise(hidden, "hidden");
|
||||
try {
|
||||
Class.forName(hidden.getName());
|
||||
} catch (ClassNotFoundException e) {
|
||||
System.out.println("Class.forName(hidden name) -> ClassNotFoundException (hidden classes cannot be found by name)");
|
||||
}
|
||||
Check.that(hidden.isHidden() && !normal.isHidden(), "hidden class is hidden, the other is not");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package demo;
|
||||
|
||||
import java.lang.classfile.ClassElement;
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.classfile.ClassModel;
|
||||
import java.lang.classfile.CodeElement;
|
||||
import java.lang.classfile.FieldModel;
|
||||
import java.lang.classfile.Instruction;
|
||||
import java.lang.classfile.MethodModel;
|
||||
import java.lang.classfile.attribute.SourceFileAttribute;
|
||||
import java.lang.classfile.instruction.InvokeDynamicInstruction;
|
||||
import java.lang.classfile.instruction.InvokeInstruction;
|
||||
import java.lang.reflect.AccessFlag;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Reading a class with java.lang.classfile: ClassFile.of().parse(...) and walking the model. */
|
||||
public class ParseDemo {
|
||||
|
||||
/** One line per method: flags name descriptor. Shared with the ASM comparison, which must print the same lines. */
|
||||
static List<String> methodLines(ClassModel cm) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
for (MethodModel m : cm.methods()) {
|
||||
lines.add(flags(m.flags().flags()) + m.methodName().stringValue() + m.methodType().stringValue());
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
static String flags(java.util.Set<AccessFlag> fs) {
|
||||
return fs.stream().map(f -> f.name().toLowerCase()).sorted().collect(Collectors.joining(",")) + " ";
|
||||
}
|
||||
|
||||
/** Calls per "owner.name" in all method bodies, using a pattern-matching switch over code elements. */
|
||||
static TreeMap<String, Integer> invokeCounts(ClassModel cm) {
|
||||
TreeMap<String, Integer> counts = new TreeMap<>();
|
||||
for (MethodModel m : cm.methods()) {
|
||||
m.code().ifPresent(code -> {
|
||||
for (CodeElement e : code) {
|
||||
switch (e) {
|
||||
case InvokeInstruction i -> counts.merge(
|
||||
i.owner().asInternalName() + "." + i.name().stringValue(), 1, Integer::sum);
|
||||
case InvokeDynamicInstruction i -> counts.merge(
|
||||
"indy:" + i.name().stringValue(), 1, Integer::sum);
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
byte[] bytes = Bytes.of(Target.class);
|
||||
ClassModel cm = ClassFile.of().parse(bytes);
|
||||
|
||||
System.out.println("== header ==");
|
||||
System.out.println("bytes : " + bytes.length);
|
||||
System.out.println("this : " + cm.thisClass().asInternalName());
|
||||
System.out.println("super : " + cm.superclass().orElseThrow().asInternalName());
|
||||
System.out.println("version : " + cm.majorVersion() + "." + cm.minorVersion()
|
||||
+ " (ClassFile.JAVA_25_VERSION = " + ClassFile.JAVA_25_VERSION + ")");
|
||||
System.out.println("flags : " + flags(cm.flags().flags()));
|
||||
System.out.println("constant pool : " + cm.constantPool().size() + " slots");
|
||||
|
||||
System.out.println("\n== fields ==");
|
||||
for (FieldModel f : cm.fields()) {
|
||||
System.out.println(flags(f.flags().flags()) + f.fieldName().stringValue() + " " + f.fieldType().stringValue());
|
||||
}
|
||||
|
||||
System.out.println("\n== methods ==");
|
||||
methodLines(cm).forEach(System.out::println);
|
||||
|
||||
System.out.println("\n== class elements, in file order (the model is a stream of elements) ==");
|
||||
for (ClassElement ce : cm) {
|
||||
String d = switch (ce) {
|
||||
case MethodModel m -> "method " + m.methodName().stringValue();
|
||||
case FieldModel f -> "field " + f.fieldName().stringValue();
|
||||
case SourceFileAttribute a -> "SourceFile=" + a.sourceFile().stringValue();
|
||||
default -> ce.getClass().getSimpleName().replaceAll("Impl$", "");
|
||||
};
|
||||
System.out.println(" " + d);
|
||||
}
|
||||
|
||||
System.out.println("\n== fib(I)I, instruction by instruction ==");
|
||||
MethodModel fib = cm.methods().stream().filter(m -> m.methodName().equalsString("fib")).findFirst().orElseThrow();
|
||||
for (CodeElement e : fib.code().orElseThrow()) {
|
||||
if (e instanceof Instruction i) {
|
||||
String extra = e instanceof InvokeInstruction inv
|
||||
? " " + inv.owner().asInternalName() + "." + inv.name().stringValue() + inv.type().stringValue() : "";
|
||||
System.out.println(" " + i.opcode() + extra);
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("\n== invoke targets in the whole class ==");
|
||||
TreeMap<String, Integer> counts = invokeCounts(cm);
|
||||
counts.forEach((k, v) -> System.out.println(" " + v + " x " + k));
|
||||
|
||||
System.out.println("\n== a JDK class from the runtime image: java.lang.String ==");
|
||||
byte[] sb = Bytes.jdk("java.base", "java/lang/String");
|
||||
ClassModel string = ClassFile.of().parse(sb);
|
||||
System.out.println("bytes " + sb.length + ", major " + string.majorVersion() + ", methods " + string.methods().size()
|
||||
+ ", fields " + string.fields().size() + ", interfaces " + string.interfaces().size());
|
||||
|
||||
Check.that(cm.majorVersion() == ClassFile.JAVA_25_VERSION, "Target.class is class-file version 69 (compiled with --release 25)");
|
||||
Check.that(cm.methods().size() == 8, "Target has 8 methods (constructor + 7)");
|
||||
Check.that(counts.getOrDefault("demo/Target.fib", 0) == 2, "fib calls itself twice");
|
||||
Check.that(counts.containsKey("indy:makeConcatWithConstants"), "greet() uses invokedynamic string concatenation");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package demo;
|
||||
|
||||
/** The class we inspect and instrument. Deliberately small, and it covers the interesting shapes:
|
||||
* a recursive method, a loop, string concatenation (invokedynamic), a method that sleeps and one that throws. */
|
||||
public class Target {
|
||||
private final String name;
|
||||
private int calls;
|
||||
|
||||
public Target(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static int fib(int n) {
|
||||
return n < 2 ? n : fib(n - 1) + fib(n - 2);
|
||||
}
|
||||
|
||||
public static long sumTo(int n) {
|
||||
long s = 0;
|
||||
for (int i = 1; i <= n; i++) {
|
||||
s += i;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
public String greet(String who) {
|
||||
calls++;
|
||||
return "Hello, " + who + " from " + name;
|
||||
}
|
||||
|
||||
public void pause(long millis) throws InterruptedException {
|
||||
Thread.sleep(millis);
|
||||
}
|
||||
|
||||
public static void boom() {
|
||||
throw new IllegalStateException("boom");
|
||||
}
|
||||
|
||||
public static int explode(int[] a) {
|
||||
return a[5]; // throws from the JVM (AIOOBE), not from an explicit athrow
|
||||
}
|
||||
|
||||
public int calls() {
|
||||
return calls;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package demo;
|
||||
|
||||
import java.lang.classfile.ClassBuilder;
|
||||
import java.lang.classfile.ClassElement;
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.classfile.ClassModel;
|
||||
import java.lang.classfile.ClassTransform;
|
||||
import java.lang.classfile.CodeBuilder;
|
||||
import java.lang.classfile.CodeElement;
|
||||
import java.lang.classfile.CodeTransform;
|
||||
import java.lang.classfile.Label;
|
||||
import java.lang.classfile.MethodModel;
|
||||
import java.lang.classfile.MethodTransform;
|
||||
import java.lang.classfile.TypeKind;
|
||||
import java.lang.classfile.instruction.ReturnInstruction;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.lang.constant.MethodTypeDesc;
|
||||
|
||||
import static java.lang.constant.ConstantDescs.*;
|
||||
|
||||
/**
|
||||
* Inserts timing around every method body of a class using java.lang.classfile transforms.
|
||||
*
|
||||
* <pre>
|
||||
* ClassTransform -- looks at each class element; for a method it hands the MethodModel to a MethodTransform
|
||||
* MethodTransform -- transformingCode(...) forwards the Code attribute to a CodeTransform
|
||||
* CodeTransform -- sees every instruction; atStart/atEnd bracket the whole body
|
||||
* </pre>
|
||||
*/
|
||||
public final class TimingTransform {
|
||||
static final ClassDesc SYSTEM = ClassDesc.of("java.lang.System");
|
||||
static final ClassDesc TIMINGS = ClassDesc.of("demo.Timings");
|
||||
static final MethodTypeDesc NANO_TIME = MethodTypeDesc.of(CD_long);
|
||||
static final MethodTypeDesc RECORD = MethodTypeDesc.of(CD_void, CD_String, CD_long);
|
||||
|
||||
private TimingTransform() { }
|
||||
|
||||
/** @param alsoOnException false = time only normal returns (the naive version); true = also when an exception leaves the method */
|
||||
public static byte[] instrument(byte[] original, boolean alsoOnException) {
|
||||
ClassFile cf = ClassFile.of();
|
||||
ClassModel model = cf.parse(original);
|
||||
String owner = model.thisClass().asInternalName();
|
||||
|
||||
ClassTransform perClass = (ClassBuilder cb, ClassElement ce) -> {
|
||||
if (ce instanceof MethodModel mm && mm.code().isPresent() && !mm.methodName().equalsString("<init>")) {
|
||||
String label = owner.substring(owner.lastIndexOf('/') + 1) + "." + mm.methodName().stringValue();
|
||||
cb.transformMethod(mm, MethodTransform.transformingCode(
|
||||
CodeTransform.ofStateful(() -> new Timer(label, alsoOnException))));
|
||||
} else {
|
||||
cb.with(ce); // everything else is copied unchanged
|
||||
}
|
||||
};
|
||||
return cf.transformClass(model, perClass);
|
||||
}
|
||||
|
||||
/** One instance per method body (ofStateful), so the local-variable slot and labels are per method. */
|
||||
private static final class Timer implements CodeTransform {
|
||||
private final String label;
|
||||
private final boolean alsoOnException;
|
||||
private int startSlot;
|
||||
private Label tryStart, tryEnd;
|
||||
|
||||
Timer(String label, boolean alsoOnException) {
|
||||
this.label = label;
|
||||
this.alsoOnException = alsoOnException;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void atStart(CodeBuilder b) {
|
||||
startSlot = b.allocateLocal(TypeKind.LONG); // a fresh local; max_locals is recomputed for us
|
||||
b.invokestatic(SYSTEM, "nanoTime", NANO_TIME).lstore(startSlot);
|
||||
if (alsoOnException) {
|
||||
tryStart = b.newLabel();
|
||||
tryEnd = b.newLabel();
|
||||
b.labelBinding(tryStart);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(CodeBuilder b, CodeElement e) {
|
||||
if (e instanceof ReturnInstruction) {
|
||||
emitRecord(b); // the return value is on the stack; our code is stack-neutral
|
||||
}
|
||||
b.with(e); // forward the original element
|
||||
}
|
||||
|
||||
@Override
|
||||
public void atEnd(CodeBuilder b) {
|
||||
if (!alsoOnException) return;
|
||||
b.labelBinding(tryEnd);
|
||||
Label handler = b.newLabel();
|
||||
b.labelBinding(handler);
|
||||
int ex = b.allocateLocal(TypeKind.REFERENCE);
|
||||
b.astore(ex);
|
||||
emitRecord(b);
|
||||
b.aload(ex).athrow();
|
||||
b.exceptionCatchAll(tryStart, tryEnd, handler); // (start, end, handler): catch-any over the original body
|
||||
}
|
||||
|
||||
private void emitRecord(CodeBuilder b) {
|
||||
b.ldc(label)
|
||||
.invokestatic(SYSTEM, "nanoTime", NANO_TIME)
|
||||
.lload(startSlot)
|
||||
.lsub()
|
||||
.invokestatic(TIMINGS, "record", RECORD);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package demo;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
/** Sink for the timing code we inject. Public, because the injected bytecode calls it from another class loader. */
|
||||
public final class Timings {
|
||||
public record Stat(long count, long totalNanos) { }
|
||||
|
||||
private static final Map<String, LongAdder> COUNT = new ConcurrentHashMap<>();
|
||||
private static final Map<String, LongAdder> NANOS = new ConcurrentHashMap<>();
|
||||
|
||||
private Timings() { }
|
||||
|
||||
/** Called from instrumented code. Signature (String, long) is mirrored in the ClassFile and ASM transformers. */
|
||||
public static void record(String method, long nanos) {
|
||||
COUNT.computeIfAbsent(method, k -> new LongAdder()).increment();
|
||||
NANOS.computeIfAbsent(method, k -> new LongAdder()).add(nanos);
|
||||
}
|
||||
|
||||
public static Stat get(String method) {
|
||||
LongAdder c = COUNT.get(method);
|
||||
return c == null ? new Stat(0, 0) : new Stat(c.sum(), NANOS.get(method).sum());
|
||||
}
|
||||
|
||||
public static void reset() {
|
||||
COUNT.clear();
|
||||
NANOS.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package demo;
|
||||
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** Instrument demo.Target with TimingTransform, load the result in an isolated class loader, call it, read the timings. */
|
||||
public class TransformDemo {
|
||||
|
||||
/** Defines `transformed` as demo.Target in its own loader; everything else (Timings, ...) comes from the parent. */
|
||||
static final class Loader extends ClassLoader {
|
||||
private final byte[] target;
|
||||
Loader(byte[] target) { super(TransformDemo.class.getClassLoader()); this.target = target; }
|
||||
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
|
||||
if (name.equals("demo.Target")) {
|
||||
synchronized (getClassLoadingLock(name)) {
|
||||
Class<?> c = findLoadedClass(name);
|
||||
if (c == null) c = defineClass(name, target, 0, target.length);
|
||||
return c;
|
||||
}
|
||||
}
|
||||
return super.loadClass(name, resolve);
|
||||
}
|
||||
}
|
||||
|
||||
static void drive(Class<?> target) throws Throwable {
|
||||
var fib = target.getMethod("fib", int.class);
|
||||
var sum = target.getMethod("sumTo", int.class);
|
||||
var boom = target.getMethod("boom");
|
||||
var explode = target.getMethod("explode", int[].class);
|
||||
var pause = target.getMethod("pause", long.class);
|
||||
var greet = target.getMethod("greet", String.class);
|
||||
Object t = target.getConstructor(String.class).newInstance("loader-2");
|
||||
|
||||
fib.invoke(null, 10);
|
||||
sum.invoke(null, 1000);
|
||||
greet.invoke(t, "Ankur");
|
||||
pause.invoke(t, 50L);
|
||||
try { boom.invoke(null); } catch (java.lang.reflect.InvocationTargetException e) { System.out.println(" boom() threw " + e.getCause()); }
|
||||
try { explode.invoke(null, (Object) new int[3]); } catch (java.lang.reflect.InvocationTargetException e) { System.out.println(" explode() threw " + e.getCause().getClass().getSimpleName()); }
|
||||
}
|
||||
|
||||
static void report(String title, byte[] bytes) throws Throwable {
|
||||
Timings.reset();
|
||||
System.out.println("-- " + title + " (" + bytes.length + " bytes; verify() problems: " + ClassFile.of().verify(bytes).size() + ")");
|
||||
Class<?> c = new Loader(bytes).loadClass("demo.Target");
|
||||
Check.that(c != Target.class, title + ": demo.Target here is a different Class object than the one on the class path");
|
||||
drive(c);
|
||||
for (String m : List.of("fib", "sumTo", "greet", "pause", "boom", "explode")) {
|
||||
Timings.Stat s = Timings.get("Target." + m);
|
||||
System.out.printf(" %-8s recorded %3d call(s)%n", m, s.count());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
byte[] original = Bytes.of(Target.class);
|
||||
Path dir = Path.of(args.length > 0 ? args[0] : "target/instrumented");
|
||||
Files.createDirectories(dir.resolve("naive/demo"));
|
||||
Files.createDirectories(dir.resolve("full/demo"));
|
||||
|
||||
byte[] naive = TimingTransform.instrument(original, false);
|
||||
byte[] full = TimingTransform.instrument(original, true);
|
||||
Files.write(dir.resolve("naive/demo/Target.class"), naive);
|
||||
Files.write(dir.resolve("full/demo/Target.class"), full);
|
||||
System.out.println("original " + original.length + " bytes, naive " + naive.length + " bytes, with exception handler " + full.length + " bytes");
|
||||
|
||||
report("naive: time normal returns only", naive);
|
||||
Timings.Stat naiveBoom = Timings.get("Target.boom"), naiveExplode = Timings.get("Target.explode"), naiveFib = Timings.get("Target.fib");
|
||||
Check.that(naiveBoom.count() == 0 && naiveExplode.count() == 0, "naive version never records the two methods that throw");
|
||||
Check.that(naiveFib.count() == 177, "fib(10) makes 177 calls and 177 timings were recorded (recursion included)");
|
||||
|
||||
report("full: also time when an exception leaves the method", full);
|
||||
Check.that(Timings.get("Target.boom").count() == 1 && Timings.get("Target.explode").count() == 1, "exception-safe version records boom() and explode() once each");
|
||||
Check.that(Timings.get("Target.fib").count() == 177, "fib still recorded 177 times");
|
||||
Check.that(Timings.get("Target.sumTo").count() == 1 && Timings.get("Target.greet").count() == 1, "sumTo and greet recorded once each");
|
||||
Check.that(Timings.get("Target.pause").totalNanos() >= 50_000_000L, "pause(50) was recorded as at least 50 ms (>= 50,000,000 ns)");
|
||||
|
||||
// Behaviour is unchanged: the transformed class still computes the same answers.
|
||||
Class<?> c = new Loader(full).loadClass("demo.Target");
|
||||
Check.that((int) c.getMethod("fib", int.class).invoke(null, 20) == Target.fib(20), "fib(20) gives the same answer before and after");
|
||||
Check.that(((Long) c.getMethod("sumTo", int.class).invoke(null, 12345)) == Target.sumTo(12345), "sumTo(12345) gives the same answer before and after");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package demo;
|
||||
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
import java.lang.classfile.ClassFile;
|
||||
|
||||
/** What happens when the class file is newer than the reader. Patches the major-version bytes of Target.class. */
|
||||
public class VersionLimits {
|
||||
static byte[] withMajor(byte[] original, int major) {
|
||||
byte[] b = original.clone();
|
||||
b[6] = (byte) (major >> 8);
|
||||
b[7] = (byte) major;
|
||||
return b;
|
||||
}
|
||||
|
||||
static String tryClassFile(byte[] b) {
|
||||
try {
|
||||
var cm = ClassFile.of().parse(b);
|
||||
return "parsed, " + cm.methods().size() + " methods";
|
||||
} catch (Throwable t) {
|
||||
return t.getClass().getName() + ": " + t.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
static String tryAsm(byte[] b) {
|
||||
try {
|
||||
int[] n = {0};
|
||||
new ClassReader(b).accept(new ClassVisitor(Opcodes.ASM9) {
|
||||
@Override public org.objectweb.asm.MethodVisitor visitMethod(int a, String nm, String d, String s, String[] e) { n[0]++; return null; }
|
||||
}, 0);
|
||||
return "parsed, " + n[0] + " methods";
|
||||
} catch (Throwable t) {
|
||||
return t.getClass().getName() + ": " + t.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
byte[] t = Bytes.of(Target.class);
|
||||
System.out.println("running on Java " + Runtime.version().feature() + "; ClassFile.latestMajorVersion() = " + ClassFile.latestMajorVersion()
|
||||
+ "; ASM Opcodes.V25=" + Opcodes.V25 + ", V28=" + Opcodes.V28);
|
||||
for (int major : new int[]{69, 70, 72, 73, 99}) {
|
||||
byte[] b = withMajor(t, major);
|
||||
System.out.println("major " + major + ":");
|
||||
System.out.println(" java.lang.classfile : " + tryClassFile(b));
|
||||
System.out.println(" ASM 9.11.1 : " + tryAsm(b));
|
||||
}
|
||||
Check.that(tryClassFile(withMajor(t, 69)).startsWith("parsed"), "major 69 parses with java.lang.classfile");
|
||||
Check.that(tryClassFile(withMajor(t, ClassFile.latestMajorVersion() + 1)).startsWith("java.lang.IllegalArgumentException"), "one version above the JDK's own is rejected by java.lang.classfile");
|
||||
Check.that(tryAsm(withMajor(t, Opcodes.V28)).startsWith("parsed"), "ASM 9.11.1 still reads major 72 (Java 28)");
|
||||
Check.that(tryAsm(withMajor(t, Opcodes.V28 + 1)).startsWith("java.lang.IllegalArgumentException"), "ASM 9.11.1 rejects major 73");
|
||||
Check.finish();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user