diff --git a/application/build.gradle b/application/build.gradle index 9924efdbb9..28b02e4768 100644 --- a/application/build.gradle +++ b/application/build.gradle @@ -1,3 +1,5 @@ +import java.time.Instant + buildscript { dependencies { classpath 'org.xerial:sqlite-jdbc:3.39.2.0' @@ -28,7 +30,7 @@ jib { } container { mainClass = 'org.togetherjava.tjbot.BootstrapLauncher' - setCreationTime(java.time.Instant.now().toString()) + setCreationTime(Instant.now().toString()) } } @@ -43,6 +45,7 @@ dependencies { implementation 'org.jetbrains:annotations:23.0.0' implementation project(':database') + implementation project(':inmemorycompiler') implementation project(':utils') implementation project(':formatter') @@ -82,4 +85,14 @@ dependencies { application { mainClass = 'org.togetherjava.tjbot.BootstrapLauncher' + + applicationDefaultJvmArgs = [ + '--add-opens=jdk.jdeps/com.sun.tools.javap=ALL-UNNAMED' + ] +} + +run { + jvmArgs = [ + '--add-opens=jdk.jdeps/com.sun.tools.javap=ALL-UNNAMED' + ] } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 76cdd928b7..229e4b2811 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -15,7 +15,6 @@ import org.togetherjava.tjbot.commands.mathcommands.wolframalpha.WolframAlphaCommand; import org.togetherjava.tjbot.commands.mediaonly.MediaOnlyChannelListener; import org.togetherjava.tjbot.commands.moderation.*; -import org.togetherjava.tjbot.commands.moderation.ReportCommand; import org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener; import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.commands.moderation.scam.ScamBlocker; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/BytecodeAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/BytecodeAction.java new file mode 100644 index 0000000000..a61b867bad --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/BytecodeAction.java @@ -0,0 +1,78 @@ +package org.togetherjava.tjbot.commands.code; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.MessageEmbed; + +import org.togetherjava.tjbot.commands.utils.CodeFence; +import org.togetherjava.tjbot.imc.CompilationResult; +import org.togetherjava.tjbot.imc.InMemoryCompiler; +import org.togetherjava.tjbot.imc.JavacOption; +import org.togetherjava.tjbot.javap.Javap; +import org.togetherjava.tjbot.javap.JavapOption; + +import javax.annotation.Nullable; + +import java.util.StringJoiner; + +// TODO Javadoc +final class BytecodeAction implements CodeAction { + @Override + public String getLabel() { + return "Bytecode"; + } + + @Override + public MessageEmbed apply(CodeFence codeFence) { + if (!isLanguageSupported(codeFence.language())) { + return createResponse("Sorry, only Java is supported."); + } + + String result = compile(codeFence.code()); + return createResponse(result); + } + + private static boolean isLanguageSupported(@Nullable String language) { + // Assume that absence indicates Java code + return language == null || "java".equals(language); + } + + private static MessageEmbed createResponse(String content) { + // Rust highlighting looks decent for bytecode + CodeFence resultCodeFence = new CodeFence("rust", content); + + return new EmbedBuilder().setTitle("Bytecode") + .setDescription(resultCodeFence.toMarkdown()) + .setColor(CodeMessageHandler.AMBIENT_COLOR) + .build(); + } + + private static String compile(String code) { + // Raw compilation + CompilationResult compilationResult; + try { + compilationResult = InMemoryCompiler.compile(code, JavacOption.DEBUG_ALL); + } catch (RuntimeException e) { + // TODO logging + return "A fatal error has occurred during compilation: " + e.getMessage(); + } + + if (!compilationResult.success()) { + StringJoiner failureMessage = new StringJoiner("\n", "Compilation failed.\n", ""); + compilationResult.compileInfos() + .forEach(info -> failureMessage.add(info.diagnostic().toString())); + return failureMessage.toString(); + } + + // Disassembling + String disassembledResult; + try { + disassembledResult = Javap.disassemble(compilationResult.bytes(), JavapOption.VERBOSE); + } catch (RuntimeException e) { + // TODO logging + return "A fatal error has occurred during disassembly: " + e.getMessage(); + } + + // TODO max length of embeds + return disassembledResult; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java index 341c8ad351..aa3c469bce 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java @@ -70,7 +70,7 @@ public CodeMessageHandler() { componentIdInteractor = new ComponentIdInteractor(getInteractionType(), getName()); - List codeActions = List.of(new FormatCodeCommand()); + List codeActions = List.of(new FormatCodeAction(), new BytecodeAction()); labelToCodeAction = codeActions.stream() .collect(Collectors.toMap(CodeAction::getLabel, Function.identity(), (x, y) -> y, diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeAction.java similarity index 95% rename from application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java rename to application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeAction.java index 2a3b086cc4..a37d795bec 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeAction.java @@ -11,7 +11,7 @@ *

* While it will attempt formatting for any language, best results are achieved for Java code. */ -final class FormatCodeCommand implements CodeAction { +final class FormatCodeAction implements CodeAction { private final Formatter formatter = new Formatter(); @Override diff --git a/build.gradle b/build.gradle index 09d6f785df..d6bc81a0cf 100644 --- a/build.gradle +++ b/build.gradle @@ -56,11 +56,6 @@ subprojects { excludes { // Disables "Track uses of "TO-DO" tags" rule. message 'java:S1135' - - // Disables "Regular expressions should not overflow the stack" rule. - // https://sonarcloud.io/project/issues?id=Together-Java_TJ-Bot&issues=AXvleoajNC7zjjhmSufQ&open=AXvleoajNC7zjjhmSufQ - // https://sonarcloud.io/project/issues?id=Together-Java_TJ-Bot&issues=AXvleoX5NC7zjjhmSufP&open=AXvleoX5NC7zjjhmSufP - message 'java:S5998' } } diff --git a/formatter/build.gradle b/formatter/build.gradle index e05ddb18dd..9479725367 100644 --- a/formatter/build.gradle +++ b/formatter/build.gradle @@ -10,4 +10,3 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0' } - diff --git a/inmemorycompiler/build.gradle b/inmemorycompiler/build.gradle new file mode 100644 index 0000000000..8485f89868 --- /dev/null +++ b/inmemorycompiler/build.gradle @@ -0,0 +1,9 @@ +plugins { + id 'java' +} + +dependencies { + implementation 'com.google.code.findbugs:jsr305:3.0.2' + + implementation project(':utils') +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/ByteJavaFileObjectLoader.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/ByteJavaFileObjectLoader.java new file mode 100644 index 0000000000..f794b3a5c4 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/ByteJavaFileObjectLoader.java @@ -0,0 +1,37 @@ +package org.togetherjava.tjbot.imc; + +import java.util.LinkedHashMap; +import java.util.Map; + +class ByteJavaFileObjectLoader extends ClassLoader { + private final Map nameToClassJFO = new LinkedHashMap<>(); + + public ByteJavaFileObjectLoader(ClassLoader parent) { + super(parent); + } + + public InMemoryByteJavaFileObject registerJFO(InMemoryByteJavaFileObject jfo) { + nameToClassJFO.put(jfo.getName(), jfo); + + return jfo; + } + + /** + * Only meant to be used for registering and getting, not finding. There are no plans to + * implement this, and it is also not needed. + * + * @throws UnsupportedOperationException always + */ + @Override + protected Class findClass(String name) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + public byte[] getLastBytes() { + return last(nameToClassJFO.values().toArray(InMemoryByteJavaFileObject[]::new)).getBytes(); + } + + private E last(E[] col) { + return col[col.length - 1]; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompilationResult.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompilationResult.java new file mode 100644 index 0000000000..26710875fd --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompilationResult.java @@ -0,0 +1,71 @@ +package org.togetherjava.tjbot.imc; + +import java.util.Arrays; +import java.util.Collections; + +/** + * Class representing a compilation result of {@link InMemoryCompiler} + */ +public record CompilationResult(boolean success, byte[] bytes, Iterable compileInfos) { + + private static final CompilationResult EMPTY_RESULT = + new CompilationResult(false, new byte[0], Collections.emptyList()); + + /** + * @return an empty compilation result + */ + public static CompilationResult empty() { + return EMPTY_RESULT; + } + + /** + * Creates an unsuccessful compilation result + * + * @param compileInfos compilation infos + * @return the generated compilation result + */ + public static CompilationResult fail(Iterable compileInfos) { + return new CompilationResult(false, new byte[0], compileInfos); + } + + /** + * Creates a successful compilation result + * + * @param bytes classfile bytecode + * @param compileInfos compilation infos + * @return the generated compilation result + */ + public static CompilationResult success(byte[] bytes, Iterable compileInfos) { + return new CompilationResult(true, bytes, compileInfos); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof CompilationResult that) || success != that.success + || !Arrays.equals(bytes, that.bytes)) { + return false; + } + + return compileInfos.equals(that.compileInfos); + } + + @Override + public int hashCode() { + int result = (success ? 1 : 0); + + result = 31 * result + Arrays.hashCode(bytes); + result = 31 * result + compileInfos.hashCode(); + + return result; + } + + @Override + public String toString() { + return "CompilationResult{" + "success=" + success + ", bytes=" + Arrays.toString(bytes) + + ", compileInfos=" + compileInfos + '}'; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompileInfo.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompileInfo.java new file mode 100644 index 0000000000..f2f5d50e1c --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompileInfo.java @@ -0,0 +1,31 @@ +package org.togetherjava.tjbot.imc; + +import javax.tools.Diagnostic; + +import java.util.Objects; + +/** + * Wrapper class for a {@link Diagnostic} of unknown type + * + * @see javax.tools.Diagnostic + */ +public record CompileInfo(Diagnostic diagnostic) { + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof CompileInfo that)) + return false; + return diagnostic.equals(that.diagnostic); + } + + @Override + public int hashCode() { + return Objects.hash(diagnostic); + } + + @Override + public String toString() { + return "CompileInfo{" + "diagnostic=" + diagnostic + '}'; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryByteJavaFileObject.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryByteJavaFileObject.java new file mode 100644 index 0000000000..2c6817c4a7 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryByteJavaFileObject.java @@ -0,0 +1,29 @@ +package org.togetherjava.tjbot.imc; + +import javax.tools.SimpleJavaFileObject; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.net.URI; + +/** + * Represents a {@link SimpleJavaFileObject} that exists purely in memory. + * + * @see javax.tools.SimpleJavaFileObject + */ +class InMemoryByteJavaFileObject extends SimpleJavaFileObject { + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + public InMemoryByteJavaFileObject(String className) { + super(URI.create(className), Kind.CLASS); + } + + @Override + public OutputStream openOutputStream() { + return baos; + } + + public byte[] getBytes() { + return baos.toByteArray(); + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryCompiler.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryCompiler.java new file mode 100644 index 0000000000..782a527d5a --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryCompiler.java @@ -0,0 +1,86 @@ +package org.togetherjava.tjbot.imc; + +import org.jetbrains.annotations.Nullable; + +import javax.tools.*; + +import java.io.Writer; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Javac interface that keeps everything in memory. + * + * @see javax.tools.JavaCompiler + */ +public final class InMemoryCompiler { + // Hide constructor + private InMemoryCompiler() {} + + private static final String TEMP_CLASS_NAME = "tmp"; + private static final JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); + private static final JavaFileManager standardFileManager = + javac.getStandardFileManager(null, null, null); + private static final ByteJavaFileObjectLoader bcl = + new ByteJavaFileObjectLoader(ClassLoader.getSystemClassLoader()); + + /** + * Compiles a given code snippet with certain javac executable arguments + * + * @param code code to compile + * @param javacOptions javac options to use + * @return the compiled code in form of a {@link CompilationResult} + */ + public static CompilationResult compile(@Nullable String code, JavacOption... javacOptions) { + if (code == null || code.isEmpty()) { + return CompilationResult.empty(); + } + + DiagnosticCollector collector = new DiagnosticCollector<>(); + boolean hasSucceeded = javac + .getTask(null, new InMemoryJavacFileManager(standardFileManager, bcl), collector, + Arrays.stream(javacOptions).map(JavacOption::getOption).toList(), null, + List.of(genCompilationUnitJFO(code))) + .call(); + + List compileInfos = new ArrayList<>(); + + if (!collector.getDiagnostics().isEmpty()) { + for (Diagnostic diagnostic : collector.getDiagnostics()) { + compileInfos.add(new CompileInfo(diagnostic)); + } + } + + if (!hasSucceeded) { + return CompilationResult.fail(compileInfos); + } + + return CompilationResult.success(bcl.getLastBytes(), compileInfos); + } + + /** + * Generates a single compilation unit in form of a {@link SimpleJavaFileObject} for + * {@link JavaCompiler#getTask(Writer, JavaFileManager, DiagnosticListener, Iterable, Iterable, Iterable)} + * + * @param content content of the imfjo + * @return the generated compilation unit + */ + private static SimpleJavaFileObject genCompilationUnitJFO(String content) { + // random protocol, any works + return new SimpleJavaFileObject(URI.create("string:///" + TEMP_CLASS_NAME.replace('.', '/') + + JavaFileObject.Kind.SOURCE.extension), JavaFileObject.Kind.SOURCE) { + /** + * Returns the content given in the generation of this {@code SimpleJavaFileObject} + * + * @param ignoreEncodingErrors does nothing + * @return content + */ + @Override + public String getCharContent(boolean ignoreEncodingErrors) { + return content; + } + }; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryJavacFileManager.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryJavacFileManager.java new file mode 100644 index 0000000000..520b01b89f --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryJavacFileManager.java @@ -0,0 +1,40 @@ +package org.togetherjava.tjbot.imc; + +import org.jetbrains.annotations.Nullable; + +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; + +/** + * File manager that tries to keep every java file output in memory + * + * @see JavaFileManager + * @see ByteJavaFileObjectLoader + */ +class InMemoryJavacFileManager extends ForwardingJavaFileManager { + private final ByteJavaFileObjectLoader classLoader; + + protected InMemoryJavacFileManager(JavaFileManager fileManager, + ByteJavaFileObjectLoader classLoader) { + super(fileManager); + + this.classLoader = classLoader; + } + + @Override + public JavaFileObject getJavaFileForOutput(@Nullable Location location, String className, + @Nullable JavaFileObject.Kind kind, @Nullable FileObject sibling) { + return classLoader.registerJFO(new InMemoryByteJavaFileObject(className)); + } + + public ByteJavaFileObjectLoader getClassLoader() { + return classLoader; + } + + @Override + public ByteJavaFileObjectLoader getClassLoader(@Nullable Location location) { + return getClassLoader(); + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/JavacOption.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/JavacOption.java new file mode 100644 index 0000000000..478feb7169 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/JavacOption.java @@ -0,0 +1,27 @@ +package org.togetherjava.tjbot.imc; + +/** + * Enum that represents every possible javac executable option that does not include an argument. + */ +public enum JavacOption { + DEBUG_ALL("-g"), + DEBUG_NONE("-g:none"), + NOWARN("-nowarn"), + VERBOSE("-verbose"), + DEPRECATION("-deprecation"), + PARAMETERS("-parameters"), + WERROR("-Werror"); + + private final String option; + + JavacOption(String option) { + this.option = option; + } + + /** + * @return textual representation of the option + */ + public String getOption() { + return option; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java new file mode 100644 index 0000000000..270f61760b --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java @@ -0,0 +1,13 @@ +/** + * This package provides utility classes to compile Java code fully in memory. + *

+ * See {@link org.togetherjava.tjbot.imc.InMemoryCompiler} as entry point. (IMC stands for + * In-Memory-Compiler) + */ +@MethodsReturnNonnullByDefault +@ParametersAreNonnullByDefault +package org.togetherjava.tjbot.imc; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/InMemoryJavaFileManager.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/InMemoryJavaFileManager.java new file mode 100644 index 0000000000..18d04f99c1 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/InMemoryJavaFileManager.java @@ -0,0 +1,49 @@ +package org.togetherjava.tjbot.javap; + +import javax.annotation.Nullable; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; + +/** + * File manager that always returns given predefined data for any file request. + * + * @see JavaFileManager + */ +final class InMemoryJavaFileManager extends ForwardingJavaFileManager { + private final byte[] fileData; + private final String fileName; + + InMemoryJavaFileManager(JavaFileManager fileManager, byte[] fileData, String fileName) { + super(fileManager); + + this.fileData = fileData.clone(); + this.fileName = fileName; + } + + @Override + public JavaFileObject getJavaFileForInput(@Nullable Location location, + @Nullable String className, JavaFileObject.Kind kind) { + return new InMemoryJavaFile(kind, fileData, fileName); + } + + private static final class InMemoryJavaFile extends SimpleJavaFileObject { + private final byte[] fileData; + + private InMemoryJavaFile(Kind kind, byte[] fileData, String fileName) { + super(URI.create("file:///" + fileName), kind); + + this.fileData = fileData; + } + + @Override + public InputStream openInputStream() { + return new ByteArrayInputStream(fileData); + } + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java new file mode 100644 index 0000000000..8fd51c2b7e --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java @@ -0,0 +1,147 @@ +package org.togetherjava.tjbot.javap; + +import javax.tools.DiagnosticListener; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * In-memory disassembler of raw Java bytecode (for example, as received by + * {@link org.togetherjava.tjbot.imc.InMemoryCompiler}, or by reading a {@code .class} file). + */ +/* + * Sonar does not like the heavy use of reflection to access locked down internal JDK tools, but the + * class is designed based on this. + */ +@SuppressWarnings("java:S3011") +public final class Javap { + // FIXME Make this a non-static class + private Javap() { + throw new UnsupportedOperationException("Utility class"); + } + + private static final String TEMP_FILE_NAME = "tmp"; + // FIXME Odd name + private static final String ANNOYING_WARNING_MESSAGE = + "Warning: File /%s does not contain class % javapFileManagerType; + private static final Class javapTaskType; + + private static final Method javapFileManagerCreate; + private static final Method javapTaskRun; + private static final Method javapTaskGetDiagnosticListenerForWriter; + + private static final Field javapTaskDefaultFileManager; + private static final Field javapTaskLog; + + static { + try { + javapFileManagerType = Class.forName("com.sun.tools.javap.JavapFileManager"); + javapFileManagerCreate = javapFileManagerType.getDeclaredMethod("create", + DiagnosticListener.class, PrintWriter.class); + + javapTaskType = Class.forName("com.sun.tools.javap.JavapTask"); + javapTaskDefaultFileManager = javapTaskType.getDeclaredField("defaultFileManager"); + javapTaskLog = javapTaskType.getDeclaredField("log"); + javapTaskRun = javapTaskType.getDeclaredMethod("run", String[].class); + javapTaskGetDiagnosticListenerForWriter = + javapTaskType.getDeclaredMethod("getDiagnosticListenerForWriter", Writer.class); + + javapFileManagerCreate.setAccessible(true); + javapTaskDefaultFileManager.setAccessible(true); + javapTaskLog.setAccessible(true); + javapTaskRun.setAccessible(true); + javapTaskGetDiagnosticListenerForWriter.setAccessible(true); + } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException e) { + throw new IllegalStateException( + "Error while attempting to access JDK internal Javap classes for the disassembler.", + e); + } + } + + /** + * Disassembles the given bytecode with given options. + * + * @param rawBytecode the raw bytecode to disassemble + * @param options selectable options + * @return disassembled bytecode + * @throws RuntimeException If the given bytecode could not be disassembled, for example, + * because it was invalid + */ + public static String disassemble(byte[] rawBytecode, JavapOption... options) { + // FIXME Proper exception usage + StringWriter result = new StringWriter(); + PrintWriter resultWriter = new PrintWriter(result); + + try { + Object javapTask = newJavapTask(); + + var fileManager = new InMemoryJavaFileManager( + getDefaultFileManager(javapTask, resultWriter), rawBytecode, TEMP_FILE_NAME); + javapTaskDefaultFileManager.set(javapTask, fileManager); + + javapTaskLog.set(javapTask, resultWriter); + + javapTaskRun.invoke(javapTask, optionsToInvokeArgs(options)); + } catch (InvocationTargetException | NoSuchMethodException | InstantiationException + | IllegalAccessException e) { + throw new IllegalArgumentException("Failed to disassemble the given bytecode.", e); + } + + return result.toString().replace(ANNOYING_WARNING_MESSAGE.formatted(TEMP_FILE_NAME), ""); + } + + /** + * Gets the default file manager instance from a {@code com.sun.tools.javap.JavapTask} and a + * {@link PrintWriter} using + * {@code com.sun.tools.javap.JavapFileManager#create(DiagnosticListener, PrintWriter)} + */ + private static JavaFileManager getDefaultFileManager(Object javapTask, PrintWriter writer) + throws InvocationTargetException, IllegalAccessException { + DiagnosticListener diagnosticListener = + getDiagnosticListenerForWriter(javapTask, writer); + return (JavaFileManager) javapFileManagerCreate.invoke(null, diagnosticListener, writer); + } + + /** + * Generates a {@link DiagnosticListener} instance from a {@code com.sun.tools.javap.JavapTask} + * and a {@link PrintWriter} using + * {@code com.sun.tools.javap.JavapTask#getDiagnosticListenerForWriter(Writer)} + */ + @SuppressWarnings("unchecked") + private static DiagnosticListener getDiagnosticListenerForWriter( + Object javapTask, PrintWriter writer) + throws InvocationTargetException, IllegalAccessException { + return (DiagnosticListener) javapTaskGetDiagnosticListenerForWriter + .invoke(javapTask, writer); + } + + /** + * Creates a new {@code com.sun.tools.javap.JavapTask} instance + */ + private static Object newJavapTask() throws NoSuchMethodException, InvocationTargetException, + InstantiationException, IllegalAccessException { + return javapTaskType.getConstructor().newInstance(); + } + + private static Object[] optionsToInvokeArgs(JavapOption... options) { + List invokeArgs = Arrays.stream(options) + .map(JavapOption::getLabel) + .collect(Collectors.toCollection(ArrayList::new)); + + invokeArgs.add(TEMP_FILE_NAME); + + return invokeArgs.toArray(Object[]::new); + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java new file mode 100644 index 0000000000..bd7a91848a --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java @@ -0,0 +1,65 @@ +package org.togetherjava.tjbot.javap; + +/** + * Selectable options for {@link Javap}. See the official + * documentation + * for details. + */ +public enum JavapOption { + /** + * Shows additional information about the selected class. + */ + VERBOSE("-verbose"), + /** + * Shows line and local variable tables. + */ + LINE("-l"), + /** + * Shows only public classes and members. + */ + PUBLIC("-public"), + /** + * Shows only protected and public classes and members. + */ + PROTECTED("-protected"), + /** + * Shows package/protected/public classes and members (default). + */ + PACKAGE("-package"), + /** + * Shows all classes and members. + */ + PRIVATE("-private"), + /** + * Shows disassembled code, for example, the instructions that comprise the Java bytecodes, for + * each of the methods in the class. + */ + DISASSEMBLE_CODE("-c"), + /** + * Shows internal type signatures. + */ + INTERNAL_TYPE_SIGNATURES("-s"), + /** + * Shows system information (path, size, date, SHA-256 hash) of the class being processed. + */ + SYSTEM_INFO("-sysinfo"), + /** + * Shows static final constants. + */ + CONSTANTS("-constants"); + + private final String label; + + JavapOption(String label) { + this.label = label; + } + + /** + * Gets the label of this option. + * + * @return textual representation of the option + */ + public String getLabel() { + return label; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java new file mode 100644 index 0000000000..4b45453c81 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java @@ -0,0 +1,11 @@ +/** + * Provides a disassembler that can turn raw Java bytecode into a human-readable form. See + * {@link org.togetherjava.tjbot.javap.Javap} as entry point. + */ +@MethodsReturnNonnullByDefault +@ParametersAreNonnullByDefault +package org.togetherjava.tjbot.javap; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/settings.gradle b/settings.gradle index 5c048b9ade..8b2af70409 100644 --- a/settings.gradle +++ b/settings.gradle @@ -3,6 +3,7 @@ rootProject.name = 'TJ-Bot' include 'application' include 'database' include 'formatter' +include 'inmemorycompiler' include 'utils' include 'website' diff --git a/utils/build.gradle b/utils/build.gradle index ae1923fecf..7a75b6ba8c 100644 --- a/utils/build.gradle +++ b/utils/build.gradle @@ -1,7 +1,7 @@ plugins { id 'java' } + dependencies { implementation 'com.google.code.findbugs:jsr305:3.0.2' } -