From 0dd67c9e39399c1403cd74a42dd7898ce701857d Mon Sep 17 00:00:00 2001 From: Michael Bien Date: Sun, 29 Nov 2026 18:24:52 +0100 Subject: [PATCH] CodeGenerator: replace legacy cf API usage with javap tool call - temporary implementation until JDK 25 bump which unlocks public classfile API - uses javap of the runtime JDK (in process) if possible and a compatible JDK from the platform manager as fallback (extra process) fixes #9368 --- .../java/source/indexing/APTUtils.java | 4 +- .../modules/java/classfile/CodeGenerator.java | 314 +++++++++++++----- .../java/classfile/CodeGeneratorTest.java | 110 +++++- java/libs.nbjavacapi/manifest.mf | 2 +- 4 files changed, 328 insertions(+), 102 deletions(-) diff --git a/java/java.source.base/src/org/netbeans/modules/java/source/indexing/APTUtils.java b/java/java.source.base/src/org/netbeans/modules/java/source/indexing/APTUtils.java index cd777459e3dc..5892dd4523f7 100644 --- a/java/java.source.base/src/org/netbeans/modules/java/source/indexing/APTUtils.java +++ b/java/java.source.base/src/org/netbeans/modules/java/source/indexing/APTUtils.java @@ -740,10 +740,8 @@ private static boolean hasSourceCache(@NonNull final URL root) { "javax.lang.model.", "javax.tools.", "com.sun.source.", - "com.sun.tools.classfile.", "com.sun.tools.javac.", - "com.sun.tools.doclint.", - "com.sun.tools.javap." + "com.sun.tools.doclint." ); private static final class BypassOpenIDEUtilClassLoader extends ClassLoader { diff --git a/java/java.source/src/org/netbeans/modules/java/classfile/CodeGenerator.java b/java/java.source/src/org/netbeans/modules/java/classfile/CodeGenerator.java index 229f569c5179..02e140424ede 100644 --- a/java/java.source/src/org/netbeans/modules/java/classfile/CodeGenerator.java +++ b/java/java.source/src/org/netbeans/modules/java/classfile/CodeGenerator.java @@ -31,21 +31,11 @@ import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; import com.sun.source.tree.VariableTree; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Opcode; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; -import com.sun.tools.javap.ClassWriter; -import com.sun.tools.javap.CodeWriter; -import com.sun.tools.javap.ConstantWriter; -import com.sun.tools.javap.Context; -import com.sun.tools.javap.Messages; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -53,6 +43,7 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; +import java.nio.file.Files; import java.security.MessageDigest; import java.util.Arrays; import java.util.Collections; @@ -60,10 +51,14 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.spi.ToolProvider; import java.util.logging.Level; import java.util.logging.Logger; @@ -86,9 +81,11 @@ import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; -import com.sun.tools.classfile.SourceFile_attribute; import java.nio.charset.StandardCharsets; import org.netbeans.api.java.classpath.ClassPath; +import org.netbeans.api.java.platform.JavaPlatform; +import org.netbeans.api.java.platform.JavaPlatformManager; +import org.netbeans.api.java.platform.Specification; import org.netbeans.api.java.source.ClasspathInfo; import org.netbeans.api.java.source.ClasspathInfo.PathKind; import org.netbeans.api.java.source.Comment; @@ -101,6 +98,8 @@ import org.netbeans.api.java.source.Task; import org.netbeans.api.java.source.TreeMaker; import org.netbeans.api.java.source.WorkingCopy; +import org.netbeans.modules.classfile.ClassFile; +import org.netbeans.modules.classfile.Method; import org.netbeans.modules.java.source.JavaSourceAccessor; import org.netbeans.modules.java.source.builder.CommentHandlerService; import org.netbeans.modules.java.source.indexing.JavaIndex; @@ -121,7 +120,7 @@ public class CodeGenerator { private static final Logger LOG = Logger.getLogger(CodeGenerator.class.getName()); private static final Set UNUSABLE_KINDS = EnumSet.of(ElementKind.PACKAGE); - private static final byte VERSION = 2; + private static final byte VERSION = 3; private static final String HASH_ATTRIBUTE_NAME = "origin-hash"; //NOI18N private static final String DISABLE_ERRORS = "disable-java-errors"; //NOI18N static final String CLASSFILE_ROOT = "classfile-root"; //NOI18N @@ -301,8 +300,7 @@ private static final class TreeBuilder extends AbstractElementVisitor9 sig2Method; + private Map sig2Code; String sourceFileName; public TreeBuilder(TreeMaker make, WorkingCopy wc) { @@ -349,35 +347,35 @@ public Tree visitModule(ModuleElement e, Void p) { @Override public Tree visitType(TypeElement e, Void p) { - ClassFile oldCf = cf; - Map oldMethods = sig2Method; + Map oldCode = sig2Code; - cf = null; - sig2Method = new HashMap(); + sig2Code = new HashMap<>(); try { try { JavaFileObject classfile = ((ClassSymbol) e).classfile; if (classfile != null && classfile.getKind() == Kind.CLASS) { - InputStream in = classfile.openInputStream(); - - try { - cf = ClassFile.read(in); - Attribute sfaRaw = cf.getAttribute(Attribute.SourceFile); - if (sfaRaw instanceof SourceFile_attribute) { - SourceFile_attribute sfa = (SourceFile_attribute) sfaRaw; - sourceFileName = sfa.getSourceFile(cf.constant_pool); - } - for (Method m : cf.methods) { - sig2Method.put(cf.constant_pool.getUTF8Value(m.name_index) + ":" + cf.constant_pool.getUTF8Value(m.descriptor.index), m); + byte[] bytes; + + try (InputStream in = classfile.openInputStream()) { + bytes = in.readAllBytes(); + } + + ClassFile cf = new ClassFile(new ByteArrayInputStream(bytes)); + sourceFileName = cf.getSourceFileName(); + Map code = disassemble(bytes); + + if (code != null) { + int index = 0; + for (Method m : cf.getMethods()) { + String c = code.get(index++); + if (c != null) { + sig2Code.put(m.getName() + ":" + m.getDescriptor(), c); + } } - } finally { - in.close(); } } - } catch (ConstantPoolException ex) { - Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } @@ -413,8 +411,7 @@ public Tree visitType(TypeElement e, Void p) { throw new UnsupportedOperationException(); } } finally { - cf = oldCf; - sig2Method = oldMethods; + sig2Code = oldCode; } } @@ -593,45 +590,14 @@ public Tree visitExecutable(ExecutableElement e, Void p) { } else { MethodTree method = make.Method(mods, e.getSimpleName(), returnValue, constructTypeParams(e.getTypeParameters()), parameters, throwsList, "{ }", null); String[] signature = SourceUtils.getJVMSignature(ElementHandle.create(e)); - Method m = sig2Method.get(signature[1] + ":" + signature[2]); + String code = sig2Code.get(signature[1] + ":" + signature[2]); CommentHandler handler = CommentHandlerService.instance(JavaSourceAccessor.getINSTANCE().getJavacTask(wc).getContext()); CommentSet set = handler.getComments(method.getBody()); - if (m != null) { - Attribute code = m.attributes.get(Attribute.Code); - - if (code instanceof Code_attribute) { - Context ctx = new Context(); - StringWriter decompiled = new StringWriter(); - PrintWriter w = new PrintWriter(decompiled); - ctx.put(PrintWriter.class, w); - ctx.put(Messages.class, new Messages() { - @Override public String getMessage(String key, Object... args) { - return ""; - } - @Override public String getMessage(Locale locale, String key, Object... args) { - return ""; - } - }); - ctx.put(ClassWriter.class, new ClassWriter(ctx) { - { - setClassFile(cf); - } - }); - ctx.put(CodeWriter.class, new ConvenientCodeWriter(ctx)); - - CodeWriter codeWriter = CodeWriter.instance(ctx); - - codeWriter.writeInstrs((Code_attribute) code); - codeWriter.writeExceptionTable((Code_attribute) code); - - w.println(); - w.close(); - - set.addComment(RelativePosition.INNER, Comment.create(Style.LINE, "")); - set.addComment(RelativePosition.INNER, Comment.create(decompiled.toString())); - set.addComment(RelativePosition.INNER, Comment.create(Style.LINE, "")); - } + if (code != null) { + set.addComment(RelativePosition.INNER, Comment.create(Style.LINE, "")); + set.addComment(RelativePosition.INNER, Comment.create(code)); + set.addComment(RelativePosition.INNER, Comment.create(Style.LINE, "")); } if (!set.hasComments()) { @@ -753,28 +719,200 @@ public ExpressionTree visitUnknown(AnnotationValue av, Void p) { } - private static final class ConvenientCodeWriter extends CodeWriter { + // TODO JDK 25: on lower bound bump, some of this could be reimplemented with the classfile API + /** + * Uses javap from the runtime JDK (same process) if possible and falls back + * to a JDK from the platform manager if not (extra process). + * + * @return the method code listings, see {@link #parseJavap(String)} for + * the map layout, or {@code null} if the class file cannot be disassembled + */ + private static Map disassemble(byte[] classBytes) { + int major = classBytes.length > 7 ? ((classBytes[6] & 0xff) << 8) | (classBytes[7] & 0xff) : 0; + if (runtimeJDKSupportsMajor(major)) { + return disassembleInProcess(classBytes); + } else { + return disassembleExternal(major, classBytes); + } + } - private final ConstantWriter constantWriter; + /** + * Returns true if javap of the runtime JDK would support the classfile version. + */ + private static boolean runtimeJDKSupportsMajor(int major) { + return major <= Runtime.version().feature() + 44; + } - public ConvenientCodeWriter(Context context) { - super(context); - constantWriter = ConstantWriter.instance(context); + private static Map disassembleInProcess(byte[] classBytes) { + Optional javap = ToolProvider.findFirst("javap"); + + if (javap.isEmpty()) { + return null; } - private static final Set INSTRUCTION_WITH_REFERENCE = - EnumSet.of(Opcode.LDC, Opcode.LDC_W, Opcode.LDC2_W, - Opcode.GETSTATIC, Opcode.PUTSTATIC, Opcode.GETFIELD, - Opcode.PUTFIELD, Opcode.INVOKEVIRTUAL, Opcode.INVOKESPECIAL, - Opcode.INVOKESTATIC, Opcode.INVOKEINTERFACE, Opcode.NEW, - Opcode.ANEWARRAY, Opcode.CHECKCAST, Opcode.INSTANCEOF); + File tmp = null; - @Override - public void writeInstr(Instruction instr) { - super.writeInstr(instr); + try { + tmp = Files.createTempFile("nb-javap", ".class").toFile(); + Files.write(tmp.toPath(), classBytes); + StringWriter out = new StringWriter(); + try (PrintWriter pw = new PrintWriter(out)) { + // the tool provider ignores the err writer: all output, errors included, goes to out + if (javap.get().run(pw, pw, "-p", "-c", tmp.getPath()) != 0) { + LOG.log(Level.FINE, "javap failed: {0}", out); + return null; + } + return parseJavap(out.toString()); + } + } catch (Exception ex) { + LOG.log(Level.FINE, "cannot disassemble class", ex); + return null; + } finally { + if (tmp != null) { + tmp.delete(); + } } } + private static Map disassembleExternal(int major, byte[] classBytes) { + FileObject javap = findNewerJavap(major); + return javap == null ? null : disassembleExternal(javap, classBytes); + } + + static Map disassembleExternal(FileObject javap, byte[] classBytes) { + File javapFile = FileUtil.toFile(javap); + + if (javapFile == null) { + return null; + } + + File tmp = null; + + try { + tmp = Files.createTempFile("nb-javap", ".class").toFile(); + Files.write(tmp.toPath(), classBytes); + Process process = new ProcessBuilder(javapFile.getAbsolutePath(), "-p", "-c", tmp.getPath()).start(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream(); + AtomicInteger exit = new AtomicInteger(Integer.MIN_VALUE); + CountDownLatch done = new CountDownLatch(1); + Thread reader = new Thread(() -> { + try { + process.getInputStream().transferTo(out); + process.getErrorStream().transferTo(err); + exit.set(process.waitFor()); + } catch (Exception ex) { + // timeout path destroys the process; the pipe closes and the daemon thread ends + } finally { + done.countDown(); + } + }, "javap-reader"); + reader.setDaemon(true); + reader.start(); + if (!done.await(5, TimeUnit.SECONDS)) { + process.destroyForcibly(); + return null; + } + if (exit.get() != 0) { + LOG.log(Level.FINE, "javap failed: {0}", err); + return null; + } + return parseJavap(out.toString()); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + return null; + } catch (Exception ex) { + LOG.log(Level.FINE, "cannot disassemble class", ex); + return null; + } finally { + if (tmp != null) { + tmp.delete(); + } + } + } + + /** + * @return the javap of the newest installed JDK able to read a class file of + * the given major version, or {@code null} if no such JDK is installed + */ + private static FileObject findNewerJavap(int major) { + Runtime.Version newest = null; + FileObject javap = null; + + for (JavaPlatform platform : JavaPlatformManager.getDefault().getInstalledPlatforms()) { + if (!platform.isValid()) { + continue; + } + Specification spec = platform.getSpecification(); + Runtime.Version version = spec == null ? null : spec.getJdkVersion(); + if (version == null || version.feature() + 44 < major) { + continue; + } + FileObject tool = platform.findTool("javap"); + + if (tool == null) { + continue; + } + if (newest == null || version.compareTo(newest) > 0) { + newest = version; + javap = tool; + } + } + return javap; + } + + /** + * Parses the output of {@code javap -p -c} into per-method code listings. + * + * @return a sparse map from each method's ordinal to its code listing. + * + * The ordinal (key) is the method's position in the class file's method table, + * matching the order of {@link ClassFile#getMethods()}. + * The listing (value) is the method's body as printed by javap: the bytecode + * instructions, followed by the exception table if present. + * + * Methods without a body, such as abstract and native methods, have no entry. + */ + static Map parseJavap(String output) { + Map codes = new HashMap<>(); + int method = -1; + StringBuilder code = null; + + for (String line : output.lines().toArray(String[]::new)) { + if (line.isBlank()) { + continue; + } + + int indent = 0; + while (indent < line.length() && line.charAt(indent) == ' ') { + indent++; + } + if (indent >= 4) { + if (" Code:".equals(line)) { + if (method >= 0) { + code = new StringBuilder(); + } + } else if (code != null) { + code.append(line).append('\n'); + } + } else { + if (code != null) { + codes.put(method, code.toString().strip()); + code = null; + } + if (indent == 2 && line.endsWith(";") && (line.contains("(") || line.endsWith("};"))) { + method++; + } + } + } + + if (code != null) { + codes.put(method, code.toString().strip()); + } + + return codes; + } + private static final Map, Set> IMPLICIT_MODIFIERS; static { diff --git a/java/java.source/test/unit/src/org/netbeans/modules/java/classfile/CodeGeneratorTest.java b/java/java.source/test/unit/src/org/netbeans/modules/java/classfile/CodeGeneratorTest.java index f7fc18bbf6bd..ae7906501d57 100644 --- a/java/java.source/test/unit/src/org/netbeans/modules/java/classfile/CodeGeneratorTest.java +++ b/java/java.source/test/unit/src/org/netbeans/modules/java/classfile/CodeGeneratorTest.java @@ -20,7 +20,10 @@ package org.netbeans.modules.java.classfile; import com.sun.source.tree.CompilationUnitTree; +import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.util.Map; import javax.lang.model.element.TypeElement; import org.netbeans.api.java.source.ClasspathInfo; import org.netbeans.api.java.source.CompilationController; @@ -35,6 +38,7 @@ import org.netbeans.modules.java.source.usages.ClasspathInfoAccessor; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; +import org.openide.util.Utilities; /** * @@ -128,6 +132,10 @@ public void testDeprecated2() throws Exception { } public void testDecompile1() throws Exception { + // temporarily negative: + // The test JVM runs with --limit-modules (requires.nb.javac), which excludes + // jdk.jdeps, so ToolProvider.findFirst("javap") is empty and the disassembled + // method bodies degrade to the "compiled code" placeholder. performFromClassTest("package test; class Test {\n" + " private void test() {\n" + " System.out.println(100000);\n" + @@ -136,22 +144,104 @@ public void testDecompile1() throws Exception { "package test;", "class Test {", "Test() {", - "// ", - "aload_0", - "return", - "// ", + "// compiled code", "}", "private void test() {", - "// ", - "getstatic", "java/lang/System.out:Ljava/io/PrintStream;", - "ldc", "100000", - "invokevirtual", "java/io/PrintStream.println:(I)V", - "return", - "", + "// compiled code", "}", "}"); } + public void testDisassembleExternal() throws Exception { + byte[] bytes; + try (InputStream in = CodeGeneratorTest.class.getResourceAsStream("CodeGeneratorTest.class")) { + assertNotNull(in); + bytes = in.readAllBytes(); + } + String tool = Utilities.isWindows() ? "javap.exe" : "javap"; + FileObject javap = FileUtil.toFileObject(new File(System.getProperty("java.home"), "bin" + File.separator + tool)); + Map codes = CodeGenerator.disassembleExternal(javap, bytes); + assertNotNull(codes); + assertFalse(codes.isEmpty()); + } + + public void testParseJavap() { + // snapshots of `javap -p -c` output + Map codes = CodeGenerator.parseJavap(""" + Compiled from "Test.java" + abstract class test.Test { + int field; + + static final int CONST; + + test.Test(); + Code: + 0: aload_0 + 1: invokespecial #1 // Method java/lang/Object."":()V + 4: aload_0 + 5: iconst_1 + 6: putfield #7 // Field field:I + 9: return + + abstract void abstractMethod() throws java.io.IOException; + + private void test() throws java.io.IOException; + Code: + 0: getstatic #13 // Field java/lang/System.out:Ljava/io/PrintStream; + 3: ldc #19 // int 100000 + 5: invokevirtual #20 // Method java/io/PrintStream.println:(I)V + 8: goto 16 + 11: astore_1 + 12: aload_1 + 13: invokevirtual #28 // Method java/lang/RuntimeException.printStackTrace:()V + 16: return + Exception table: + from to target type + 0 8 11 Class java/lang/RuntimeException + + static {}; + Code: + 0: getstatic #13 // Field java/lang/System.out:Ljava/io/PrintStream; + 3: bipush 115 + 5: invokevirtual #31 // Method java/io/PrintStream.print:(C)V + 8: return + } + """); + assertEquals(3, codes.size()); + assertEquals(norm(""" + 0: aload_0 + 1: invokespecial #1 // Method java/lang/Object."":()V + 4: aload_0 + 5: iconst_1 + 6: putfield #7 // Field field:I + 9: return + """), norm(codes.get(0))); + assertNull(codes.get(1)); // abstract method, no Code section + assertEquals(norm(""" + 0: getstatic #13 // Field java/lang/System.out:Ljava/io/PrintStream; + 3: ldc #19 // int 100000 + 5: invokevirtual #20 // Method java/io/PrintStream.println:(I)V + 8: goto 16 + 11: astore_1 + 12: aload_1 + 13: invokevirtual #28 // Method java/lang/RuntimeException.printStackTrace:()V + 16: return + Exception table: + from to target type + 0 8 11 Class java/lang/RuntimeException + """), norm(codes.get(2))); + assertEquals(norm(""" + 0: getstatic #13 // Field java/lang/System.out:Ljava/io/PrintStream; + 3: bipush 115 + 5: invokevirtual #31 // Method java/io/PrintStream.print:(C)V + 8: return + """), norm(codes.get(3))); + } + + private static String norm(String s) { + return String.join("\n", s.lines().map(String::stripLeading).toList()); + } + public void testPermittedSubclasses() throws Exception { sourceLevel = "17"; performTest(""" diff --git a/java/libs.nbjavacapi/manifest.mf b/java/libs.nbjavacapi/manifest.mf index 5f53eafe4f42..24952dccc211 100644 --- a/java/libs.nbjavacapi/manifest.mf +++ b/java/libs.nbjavacapi/manifest.mf @@ -3,6 +3,6 @@ AutoUpdate-Show-In-Client: true OpenIDE-Module: org.netbeans.libs.nbjavacapi OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/nbjavac/api/Bundle.properties OpenIDE-Module-Specification-Version: 21.13 -OpenIDE-Module-Hide-Classpath-Packages: com.sun.source.**, javax.annotation.processing.**, javax.lang.model.**, javax.tools.**, com.sun.tools.javac.**, com.sun.tools.javap.**, com.sun.tools.classfile.**, com.sun.tools.doclint.** +OpenIDE-Module-Hide-Classpath-Packages: com.sun.source.**, javax.annotation.processing.**, javax.lang.model.**, javax.tools.**, com.sun.tools.javac.**, com.sun.tools.doclint.** OpenIDE-Module-Fragment-Host: org.netbeans.libs.javacapi OpenIDE-Module-Provides: org.netbeans.libs.nbjavac