diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/Constants.java b/src/main/java/the/bytecode/club/bytecodeviewer/Constants.java index fbba77434..98811d10d 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/Constants.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/Constants.java @@ -68,7 +68,7 @@ public class Constants public static final String FS = System.getProperty("file.separator"); public static final String NL = System.getProperty("line.separator"); - public static final String[] SUPPORTED_FILE_EXTENSIONS = ResourceType.supportedBCVExtensionMap.keySet().toArray(new String[0]); + public static final String[] SUPPORTED_FILE_EXTENSIONS = ResourceType.SUPPORTED_BCV_EXTENSION_MAP.keySet().toArray(new String[0]); public static final int ASM_VERSION = Opcodes.ASM9; public static final File BCVDir = resolveBCVRoot(); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/GlobalHotKeys.java b/src/main/java/the/bytecode/club/bytecodeviewer/GlobalHotKeys.java index 7f6971dfa..46011af29 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/GlobalHotKeys.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/GlobalHotKeys.java @@ -106,6 +106,7 @@ else if ((e.getKeyCode() == KeyEvent.VK_S) && ((e.getModifiersEx() & KeyEvent.CT JFileChooser fc = new FileChooser(Configuration.getLastSaveDirectory(), "Select Zip Export", "Zip Archives", "zip"); int returnVal = fc.showSaveDialog(BytecodeViewer.viewer); + if (returnVal == JFileChooser.APPROVE_OPTION) { Configuration.setLastSaveDirectory(fc.getSelectedFile()); @@ -124,6 +125,7 @@ else if ((e.getKeyCode() == KeyEvent.VK_S) && ((e.getModifiersEx() & KeyEvent.CT jarExport.start(); } }, "Resource Export"); + resourceExport.start(); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/Settings.java b/src/main/java/the/bytecode/club/bytecodeviewer/Settings.java index c3eb39c79..943745844 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/Settings.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/Settings.java @@ -127,32 +127,38 @@ protected static void resetRecentFilesMenu() { //build recent files BytecodeViewer.viewer.recentFilesSecondaryMenu.removeAll(); + for (String s : recentFiles) { if (!s.isEmpty()) { JMenuItem m = new JMenuItem(s); + m.addActionListener(e -> { JMenuItem m12 = (JMenuItem) e.getSource(); BytecodeViewer.openFiles(new File[]{new File(m12.getText())}, true); }); + BytecodeViewer.viewer.recentFilesSecondaryMenu.add(m); } } //build recent plugins BytecodeViewer.viewer.recentPluginsSecondaryMenu.removeAll(); + for (String s : recentPlugins) { if (!s.isEmpty()) { JMenuItem m = new JMenuItem(s); + m.addActionListener(e -> { JMenuItem m1 = (JMenuItem) e.getSource(); BytecodeViewer.startPlugin(new File(m1.getText())); }); + BytecodeViewer.viewer.recentPluginsSecondaryMenu.add(m); } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/SettingsSerializer.java b/src/main/java/the/bytecode/club/bytecodeviewer/SettingsSerializer.java index a6fc470fe..dce2b1b62 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/SettingsSerializer.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/SettingsSerializer.java @@ -338,11 +338,13 @@ public static void loadSettings() BytecodeViewer.viewer.refreshOnChange.setSelected(asBoolean(84)); boolean bool = Boolean.parseBoolean(asString(85)); + if (bool) { BytecodeViewer.viewer.setExtendedState(JFrame.MAXIMIZED_BOTH); BytecodeViewer.viewer.isMaximized = true; } + //86 is deprecated //87 is deprecated Configuration.lastOpenDirectory = asString(88); @@ -388,6 +390,7 @@ public static void loadSettings() //line 130 is used for preload if (Configuration.language != Language.ENGLISH) Configuration.language.setLanguageTranslations(); //load language translations + Settings.hasSetLanguageAsSystemLanguage = true; BytecodeViewer.viewer.viewPane1.setPaneEditable(asBoolean(131)); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/JavaCompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/JavaCompiler.java index 54c8483d0..7c45d0656 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/JavaCompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/JavaCompiler.java @@ -43,20 +43,23 @@ public class JavaCompiler extends InternalCompiler @Override public byte[] compile(String contents, String fullyQualifiedName) { - String fileStart = TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(12) + FS; - String fileStart2 = TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(12) + FS; - File java = new File(fileStart + FS + fullyQualifiedName + ".java"); - File clazz = new File(fileStart2 + FS + fullyQualifiedName + ".class"); - File cp = new File(TEMP_DIRECTORY + FS + "cpath_" + MiscUtils.randomString(12) + ".jar"); - File tempD = new File(fileStart + FS + fullyQualifiedName.substring(0, fullyQualifiedName.length() - + final String fileStart = TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(12) + FS; + final String fileStart2 = TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(12) + FS; + + final File javaFile = new File(fileStart + FS + fullyQualifiedName + ".java"); + final File classFile = new File(fileStart2 + FS + fullyQualifiedName + ".class"); + final File classPath = new File(TEMP_DIRECTORY + FS + "cpath_" + MiscUtils.randomString(12) + ".jar"); + final File tempDirectory = new File(fileStart + FS + fullyQualifiedName.substring(0, fullyQualifiedName.length() - fullyQualifiedName.split("/")[fullyQualifiedName.split("/").length - 1].length())); - tempD.mkdirs(); + //create the temp directories + tempDirectory.mkdirs(); new File(fileStart2).mkdirs(); if (Configuration.javac.isEmpty() || !new File(Configuration.javac).exists()) { - BytecodeViewer.showMessage("You need to set your Javac path, this requires the JDK to be downloaded." + NL + "(C:/Program Files/Java/JDK_xx/bin/javac.exe)"); + BytecodeViewer.showMessage("You need to set your Javac path, this requires the JDK to be downloaded." + + NL + "(C:/Program Files/Java/JDK_xx/bin/javac.exe)"); ExternalResources.getSingleton().selectJavac(); } @@ -66,8 +69,11 @@ public byte[] compile(String contents, String fullyQualifiedName) return null; } - DiskWriter.replaceFile(java.getAbsolutePath(), contents, false); - JarUtils.saveAsJar(BytecodeViewer.getLoadedClasses(), cp.getAbsolutePath()); + //write the file we're assembling to disk + DiskWriter.replaceFile(javaFile.getAbsolutePath(), contents, false); + + //write the entire temporary classpath to disk + JarUtils.saveAsJar(BytecodeViewer.getLoadedClasses(), classPath.getAbsolutePath()); boolean cont = true; try @@ -77,10 +83,10 @@ public byte[] compile(String contents, String fullyQualifiedName) if (Configuration.library.isEmpty()) pb = new ProcessBuilder(Configuration.javac, "-d", fileStart2, - "-classpath", cp.getAbsolutePath(), java.getAbsolutePath()); + "-classpath", classPath.getAbsolutePath(), javaFile.getAbsolutePath()); else pb = new ProcessBuilder(Configuration.javac, "-d", fileStart2, - "-classpath", cp.getAbsolutePath() + System.getProperty("path.separator") + Configuration.library, java.getAbsolutePath()); + "-classpath", classPath.getAbsolutePath() + System.getProperty("path.separator") + Configuration.library, javaFile.getAbsolutePath()); Process process = pb.start(); BytecodeViewer.createdProcesses.add(process); @@ -111,6 +117,7 @@ public byte[] compile(String contents, String fullyQualifiedName) } log.append(NL).append(NL).append(TranslatedStrings.ERROR2).append(NL).append(NL); + try (InputStream is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) @@ -123,7 +130,7 @@ public byte[] compile(String contents, String fullyQualifiedName) log.append(NL).append(NL).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue); System.out.println(log); - if (!clazz.exists()) + if (!classFile.exists()) throw new Exception(log.toString()); } catch (Exception e) @@ -132,12 +139,12 @@ public byte[] compile(String contents, String fullyQualifiedName) e.printStackTrace(); } - cp.delete(); + classPath.delete(); if (cont) try { - return org.apache.commons.io.FileUtils.readFileToByteArray(clazz); + return org.apache.commons.io.FileUtils.readFileToByteArray(classFile); } catch (IOException e) { diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/KrakatauAssembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/KrakatauAssembler.java index c745d02e7..9f396ac33 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/KrakatauAssembler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/KrakatauAssembler.java @@ -51,16 +51,19 @@ public byte[] compile(String contents, String fullyQualifiedName) if (!ExternalResources.getSingleton().hasSetPython2Command()) return null; - File tempD = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); - tempD.mkdir(); + final File tempDirectory1 = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); + final File tempDirectory2 = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); + final File javaFile = new File(tempDirectory1.getAbsolutePath() + FS + fullyQualifiedName + ".j"); + final File tempJar = new File(Constants.TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(32) + ".jar"); - File tempJ = new File(tempD.getAbsolutePath() + FS + fullyQualifiedName + ".j"); - DiskWriter.replaceFile(tempJ.getAbsolutePath(), contents, true); + //create the temp directories + tempDirectory1.mkdir(); + tempDirectory2.mkdir(); - final File tempDirectory = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); - tempDirectory.mkdir(); + //write the file we're assembling to disk + DiskWriter.replaceFile(javaFile.getAbsolutePath(), contents, true); - final File tempJar = new File(Constants.TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(32) + ".jar"); + //write the entire temporary classpath to disk JarUtils.saveAsJar(BytecodeViewer.getLoadedClasses(), tempJar.getAbsolutePath()); StringBuilder log = new StringBuilder(); @@ -72,7 +75,7 @@ public byte[] compile(String contents, String fullyQualifiedName) pythonCommands = ArrayUtils.addAll(pythonCommands, "-2"); ProcessBuilder pb = new ProcessBuilder(ArrayUtils.addAll(pythonCommands, "-O", //love you storyyeller <3 - krakatauWorkingDirectory + FS + "assemble.py", "-out", tempDirectory.getAbsolutePath(), tempJ.getAbsolutePath())); + krakatauWorkingDirectory + FS + "assemble.py", "-out", tempDirectory2.getAbsolutePath(), javaFile.getAbsolutePath())); Process process = pb.start(); BytecodeViewer.createdProcesses.add(process); @@ -101,10 +104,15 @@ public byte[] compile(String contents, String fullyQualifiedName) log.append(NL).append(NL).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue); System.err.println(log); - byte[] b = FileUtils.readFileToByteArray(Objects.requireNonNull(ExternalResources.getSingleton().findFile(tempDirectory, ".class"))); - tempDirectory.delete(); + //read the assembled bytes from disk + byte[] assembledBytes = FileUtils.readFileToByteArray(Objects.requireNonNull(ExternalResources.getSingleton().findFile(tempDirectory2, ".class"))); + + //cleanup + tempDirectory2.delete(); tempJar.delete(); - return b; + + //return the assembled file + return assembledBytes; } catch (Exception e) { diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/SmaliAssembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/SmaliAssembler.java index 58e6e7328..fc2d5fef6 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/SmaliAssembler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/impl/SmaliAssembler.java @@ -44,19 +44,21 @@ public class SmaliAssembler extends InternalCompiler @Override public byte[] compile(String contents, String fullyQualifiedName) { - String fileStart = TEMP_DIRECTORY + FS + "temp"; - int fileNumber = MiscUtils.getClassNumber(fileStart, ".dex"); - + final String fileStart = TEMP_DIRECTORY + FS + "temp"; + final int fileNumber = MiscUtils.getClassNumber(fileStart, ".dex"); final File tempSmaliFolder = new File(fileStart + fileNumber + "-smalifolder" + FS); - tempSmaliFolder.mkdir(); - File tempSmali = new File(tempSmaliFolder.getAbsolutePath() + FS + fileNumber + ".smali"); - File tempDex = new File("./out.dex"); - File tempJar = new File(fileStart + fileNumber + ".jar"); - File tempJarFolder = new File(fileStart + fileNumber + "-jar" + FS); + final File tempSmali = new File(tempSmaliFolder.getAbsolutePath() + FS + fileNumber + ".smali"); + final File tempDex = new File("./out.dex"); + final File tempJar = new File(fileStart + fileNumber + ".jar"); + final File tempJarFolder = new File(fileStart + fileNumber + "-jar" + FS); + + //create the temp directory + tempSmaliFolder.mkdir(); try { + //write the file we're assembling to disk DiskWriter.replaceFile(tempSmali.getAbsolutePath(), contents, false); } catch (Exception e) @@ -107,6 +109,7 @@ else if (BytecodeViewer.viewer.apkConversionGroup.isSelected(BytecodeViewer.view System.out.println("Saved as: " + outputClass.getAbsolutePath()); + //return the assembled file return FileUtils.readFileToByteArray(outputClass); } catch (java.lang.NullPointerException ignored) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/InternalDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/InternalDecompiler.java index 9aa144349..5cba6872a 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/InternalDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/InternalDecompiler.java @@ -27,7 +27,7 @@ */ public abstract class InternalDecompiler { - public abstract String decompileClassNode(ClassNode cn, byte[] b); + public abstract String decompileClassNode(ClassNode cn, byte[] bytes); public abstract void decompileToZip(String sourceJar, String zipName); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java index 1c9a0b683..1c08d5407 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java @@ -37,11 +37,14 @@ public static PrefixedStringBuilder decompile(PrefixedStringBuilder sb, FieldNod { String s = getAccessString(f.access); sb.append(s); + if (s.length() > 0) sb.append(" "); + sb.append(Type.getType(f.desc).getClassName()); sb.append(" "); sb.append(f.name); + if (f.value != null) { sb.append(" = "); @@ -59,13 +62,16 @@ public static PrefixedStringBuilder decompile(PrefixedStringBuilder sb, FieldNod sb.append(")"); } } + sb.append(";"); + return sb; } private static String getAccessString(int access) { List tokens = new ArrayList<>(); + if ((access & Opcodes.ACC_PUBLIC) != 0) tokens.add("public"); if ((access & Opcodes.ACC_PRIVATE) != 0) @@ -84,6 +90,7 @@ private static String getAccessString(int access) tokens.add("volatile"); if (tokens.size() == 0) return ""; + // hackery delimeters StringBuilder sb = new StringBuilder(tokens.get(0)); for (int i = 1; i < tokens.size(); i++) @@ -91,6 +98,7 @@ private static String getAccessString(int access) sb.append(" "); sb.append(tokens.get(i)); } + return sb.toString(); } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java index 7d05456ce..a96e1929d 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java @@ -61,8 +61,6 @@ public InstructionPrinter(MethodNode m, TypeAndName[] args) mNode = m; labels = new HashMap<>(); precalculateLabelIndexes(m); - // matchedInsns = new ArrayList(); // ingnored because - // match = false match = false; } @@ -125,97 +123,39 @@ public String printInstruction(AbstractInsnNode ain) { String line = ""; if (ain instanceof VarInsnNode) - { line = printVarInsnNode((VarInsnNode) ain); - } else if (ain instanceof IntInsnNode) - { line = printIntInsnNode((IntInsnNode) ain); - } else if (ain instanceof FieldInsnNode) - { line = printFieldInsnNode((FieldInsnNode) ain); - } else if (ain instanceof MethodInsnNode) - { line = printMethodInsnNode((MethodInsnNode) ain); - } else if (ain instanceof LdcInsnNode) - { line = printLdcInsnNode((LdcInsnNode) ain); - } else if (ain instanceof InsnNode) - { line = printInsnNode((InsnNode) ain); - } else if (ain instanceof JumpInsnNode) - { line = printJumpInsnNode((JumpInsnNode) ain); - } else if (ain instanceof LineNumberNode) - { line = printLineNumberNode((LineNumberNode) ain); - } else if (ain instanceof LabelNode) - { - if (firstLabel && BytecodeViewer.viewer.appendBracketsToLabels.isSelected()) - info.add("}"); - - LabelNode label = (LabelNode) ain; - if (mNode.tryCatchBlocks != null) - { - List tcbs = mNode.tryCatchBlocks; - String starting = tcbs.stream().filter(tcb -> tcb.start == label).map(tcb -> "start TCB" + tcbs.indexOf(tcb)).collect(Collectors.joining(", ")); - String ending = tcbs.stream().filter(tcb -> tcb.end == label).map(tcb -> "end TCB" + tcbs.indexOf(tcb)).collect(Collectors.joining(", ")); - String handlers = tcbs.stream().filter(tcb -> tcb.handler == label).map(tcb -> "handle TCB" + tcbs.indexOf(tcb)).collect(Collectors.joining(", ")); - if (!ending.isEmpty()) - info.add("// " + ending); - if (!starting.isEmpty()) - info.add("// " + starting); - if (!handlers.isEmpty()) - info.add("// " + handlers); - } line = printLabelNode((LabelNode) ain); - - if (BytecodeViewer.viewer.appendBracketsToLabels.isSelected()) - { - if (!firstLabel) - firstLabel = true; - line += " {"; - } - } else if (ain instanceof TypeInsnNode) - { line = printTypeInsnNode((TypeInsnNode) ain); - } else if (ain instanceof FrameNode) - { line = printFrameNode((FrameNode) ain); - } else if (ain instanceof IincInsnNode) - { line = printIincInsnNode((IincInsnNode) ain); - } else if (ain instanceof TableSwitchInsnNode) - { line = printTableSwitchInsnNode((TableSwitchInsnNode) ain); - } else if (ain instanceof LookupSwitchInsnNode) - { line = printLookupSwitchInsnNode((LookupSwitchInsnNode) ain); - } else if (ain instanceof InvokeDynamicInsnNode) - { line = printInvokeDynamicInsNode((InvokeDynamicInsnNode) ain); - } else if (ain instanceof MultiANewArrayInsnNode) - { line = printMultiANewArrayInsNode((MultiANewArrayInsnNode) ain); - } else - { line += "UNADDED OPCODE: " + nameOpcode(ain.getOpcode()) + " " + ain; - } return line; } @@ -312,11 +252,44 @@ protected String printLineNumberNode(LineNumberNode lnn) return ""; } - protected String printLabelNode(LabelNode label) + protected String printOnlyLabelNode(LabelNode label) { return "L" + resolveLabel(label); } + protected String printLabelNode(LabelNode label) + { + if (firstLabel && BytecodeViewer.viewer.appendBracketsToLabels.isSelected()) + info.add("}"); + + String line = ""; + + if (mNode.tryCatchBlocks != null) + { + List tcbs = mNode.tryCatchBlocks; + String starting = tcbs.stream().filter(tcb -> tcb.start == label).map(tcb -> "start TCB" + tcbs.indexOf(tcb)).collect(Collectors.joining(", ")); + String ending = tcbs.stream().filter(tcb -> tcb.end == label).map(tcb -> "end TCB" + tcbs.indexOf(tcb)).collect(Collectors.joining(", ")); + String handlers = tcbs.stream().filter(tcb -> tcb.handler == label).map(tcb -> "handle TCB" + tcbs.indexOf(tcb)).collect(Collectors.joining(", ")); + if (!ending.isEmpty()) + info.add("// " + ending); + if (!starting.isEmpty()) + info.add("// " + starting); + if (!handlers.isEmpty()) + info.add("// " + handlers); + } + + line = printOnlyLabelNode(label); + + if (BytecodeViewer.viewer.appendBracketsToLabels.isSelected()) + { + if (!firstLabel) + firstLabel = true; + line += " {"; + } + + return line; + } + protected String printTypeInsnNode(TypeInsnNode tin) { try @@ -403,6 +376,7 @@ private String printFrameNode(FrameNode frame) { StringBuilder sb = new StringBuilder(); sb.append(nameFrameType(frame.type)).append(" "); + sb.append("(Locals"); if (frame.local != null && !frame.local.isEmpty()) { @@ -490,15 +464,13 @@ protected String nameOpcode(int opcode) protected int resolveLabel(LabelNode label) { if (labels.containsKey(label)) - { return labels.get(label); - } else { - /*int newLabelIndex = labels.size() + 1; + //NOTE: Should NEVER enter this state, but if it ever does, here's the fall-back solution + int newLabelIndex = labels.size() + 1; labels.put(label, newLabelIndex); - return newLabelIndex;*/ - throw new IllegalStateException("LabelNode index not found. (Label not in InsnList?)"); + return newLabelIndex; } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java index c04500ddf..390786917 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java @@ -36,7 +36,6 @@ public class InstructionSearcher implements Opcodes protected InsnList insns; protected InstructionPattern pattern; - protected List matches; public InstructionSearcher(InsnList insns, int[] opcodes) @@ -62,6 +61,7 @@ public boolean search() { if (ain instanceof LineNumberNode || ain instanceof FrameNode) continue; + if (pattern.accept(ain)) { matches.add(pattern.getLastMatch()); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java index bb6cd09b4..ed7b255df 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java @@ -40,14 +40,17 @@ public class MethodNodeDecompiler public static PrefixedStringBuilder decompile(PrefixedStringBuilder sb, MethodNode m, ClassNode cn) { String className; + if (cn.name.contains("/")) className = cn.name.substring(cn.name.lastIndexOf("/") + 1); else className = cn.name; String s = getAccessString(m.access); + sb.append(" "); sb.append(s); + if (s.length() > 0) sb.append(" "); @@ -73,7 +76,6 @@ else if (!m.name.equals("")) for (int i = 0; i < argTypes.length; i++) { final Type type = argTypes[i]; - final TypeAndName tan = new TypeAndName(); final String argName = "arg" + i; @@ -89,10 +91,12 @@ else if (!m.name.equals("")) } int amountOfThrows = m.exceptions.size(); + if (amountOfThrows > 0) { sb.append(" throws "); sb.append(m.exceptions.get(0));// exceptions is list + for (int i = 1; i < amountOfThrows; i++) { sb.append(", "); @@ -109,7 +113,6 @@ else if (!m.name.equals("")) } else { - sb.append(" {"); if (BytecodeViewer.viewer.debugHelpers.isSelected()) @@ -161,10 +164,12 @@ else if (m.name.equals("")) sb.append(" handled by L"); sb.append(insnPrinter.resolveLabel(o.handler)); sb.append(": "); + if (o.type != null) sb.append(o.type); else sb.append("Type is null."); + sb.append(NL); } @@ -174,8 +179,10 @@ else if (m.name.equals("")) sb.append(insn); sb.append(NL); } + sb.append(" }" + NL); } + return sb; } @@ -194,6 +201,7 @@ private static void addAttrList(List list, String name, PrefixedStringBuilder sb.append(">"); sb.append(NL); } + sb.append(NL); } } @@ -203,7 +211,8 @@ private static String printAttr(Object o, InstructionPrinter insnPrinter) if (o instanceof LocalVariableNode) { LocalVariableNode lvn = (LocalVariableNode) o; - return "index=" + lvn.index + " , name=" + lvn.name + " , desc=" + lvn.desc + ", sig=" + lvn.signature + ", start=L" + insnPrinter.resolveLabel(lvn.start) + ", end=L" + insnPrinter.resolveLabel(lvn.end); + return "index=" + lvn.index + " , name=" + lvn.name + " , desc=" + lvn.desc + ", sig=" + lvn.signature + + ", start=L" + insnPrinter.resolveLabel(lvn.start) + ", end=L" + insnPrinter.resolveLabel(lvn.end); } else if (o instanceof AnnotationNode) { @@ -212,6 +221,7 @@ else if (o instanceof AnnotationNode) sb.append("desc = "); sb.append(an.desc); sb.append(" , values = "); + if (an.values != null) { sb.append(Arrays.toString(an.values.toArray())); @@ -220,10 +230,13 @@ else if (o instanceof AnnotationNode) { sb.append("[]"); } + return sb.toString(); } + if (o == null) return ""; + return o.toString(); } @@ -258,6 +271,7 @@ private static String getAccessString(int access) tokens.add("varargs"); if (tokens.isEmpty()) return ""; + // hackery delimeters StringBuilder sb = new StringBuilder(tokens.get(0)); for (int i = 1; i < tokens.size(); i++) @@ -265,6 +279,7 @@ private static String getAccessString(int access) sb.append(" "); sb.append(tokens.get(i)); } + return sb.toString(); } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java index 3f8c62a30..5c8d4c9b9 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java @@ -36,15 +36,11 @@ public PrefixedStringBuilder() public PrefixedStringBuilder append(String s) { sb.append(s); - if (s.contains("\n") && (prefix != null) && (prefix.length() > 0))// insert - // the - // prefix - // at - // every - // new - // line, - // overridable + + // insert the prefix at every new line, overridable + if (s.contains("\n") && (prefix != null) && (prefix.length() > 0)) sb.append(prefix); + return this; } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMTextifierDisassembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMTextifierDisassembler.java index 963efbefc..d52fc3d3a 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMTextifierDisassembler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMTextifierDisassembler.java @@ -34,7 +34,7 @@ public class ASMTextifierDisassembler extends InternalDecompiler { @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { StringWriter writer = new StringWriter(); cn.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter(writer))); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMifierGenerator.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMifierGenerator.java index d58604e93..578d85250 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMifierGenerator.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ASMifierGenerator.java @@ -34,7 +34,7 @@ public class ASMifierGenerator extends InternalDecompiler { @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { StringWriter writer = new StringWriter(); cn.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter(writer))); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/BytecodeDisassembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/BytecodeDisassembler.java index ebcc8b60f..53ed17ca4 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/BytecodeDisassembler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/BytecodeDisassembler.java @@ -32,7 +32,7 @@ public class BytecodeDisassembler extends InternalDecompiler { @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { return ClassNodeDecompiler.decompile(new PrefixedStringBuilder(), new ArrayList<>(), cn).toString(); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/CFRDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/CFRDecompiler.java index 112ec4e6c..0c85d98ad 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/CFRDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/CFRDecompiler.java @@ -59,9 +59,9 @@ public class CFRDecompiler extends InternalDecompiler private static final String CLASS_SUFFIX = ".class"; @Override - public String decompileClassNode(ClassNode cn, byte[] content) + public String decompileClassNode(ClassNode cn, byte[] bytes) { - return decompile(cn, cn.name, content); + return decompile(cn, cn.name, bytes); } private String decompile(ClassNode cn, String name, byte[] content) @@ -93,7 +93,10 @@ private String decompile(ClassNode cn, String name, byte[] content) @Override public void decompileToZip(String sourceJar, String outJar) { - try (JarFile jfile = new JarFile(new File(sourceJar)); FileOutputStream dest = new FileOutputStream(outJar); BufferedOutputStream buffDest = new BufferedOutputStream(dest); ZipOutputStream out = new ZipOutputStream(buffDest)) + try (JarFile jfile = new JarFile(new File(sourceJar)); + FileOutputStream dest = new FileOutputStream(outJar); + BufferedOutputStream buffDest = new BufferedOutputStream(dest); + ZipOutputStream out = new ZipOutputStream(buffDest)) { byte[] data = new byte[1024]; @@ -105,6 +108,7 @@ public void decompileToZip(String sourceJar, String outJar) if (entry.getName().endsWith(CLASS_SUFFIX)) { JarEntry etn = new JarEntry(entry.getName().replace(CLASS_SUFFIX, ".java")); + if (history.add(etn)) { out.putNextEntry(etn); @@ -203,6 +207,7 @@ public Options generateOptions() options.put("recovertypehints", String.valueOf(BytecodeViewer.viewer.recoveryTypehInts.isSelected())); options.put("forcereturningifs", String.valueOf(BytecodeViewer.viewer.forceTurningIFs.isSelected())); options.put("forloopaggcapture", String.valueOf(BytecodeViewer.viewer.forLoopAGGCapture.isSelected())); + return new OptionsImpl(options); } @@ -226,11 +231,15 @@ public Pair getClassFileContent(String classFilePath) throws IOE { if (classFilePath.equals(this.classFilePath) && content != null) return Pair.make(content, classFilePath); + if (container == null) return super.getClassFileContent(classFilePath); + byte[] data = container.resourceClassBytes.get(classFilePath); + if (data == null) return super.getClassFileContent(classFilePath); + return Pair.make(data, classFilePath); } @@ -259,6 +268,7 @@ public Sink getSink(SinkType sinkType, SinkClass sinkClass) { return x -> dumpDecompiled.accept((SinkReturns.Decompiled) x); } + return ignore -> { }; diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/FernFlowerDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/FernFlowerDecompiler.java index 6ae2f8f09..2187e2e22 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/FernFlowerDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/FernFlowerDecompiler.java @@ -65,7 +65,7 @@ public void decompileToZip(String sourceJar, String zipName) } @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { String start = TEMP_DIRECTORY + FS + MiscUtils.getUniqueName("", ".class"); @@ -74,7 +74,7 @@ public String decompileClassNode(ClassNode cn, byte[] b) String exception = ""; try (FileOutputStream fos = new FileOutputStream(tempClass)) { - fos.write(b); + fos.write(bytes); } catch (IOException e) { @@ -154,7 +154,26 @@ public String decompileClassNode(ClassNode cn, byte[] b) private String[] generateMainMethod(String className, String folder) { - return new String[]{"-rbr=" + r(BytecodeViewer.viewer.rbr.isSelected()), "-rsy=" + r(BytecodeViewer.viewer.rsy.isSelected()), "-din=" + r(BytecodeViewer.viewer.din.isSelected()), "-dc4=" + r(BytecodeViewer.viewer.dc4.isSelected()), "-das=" + r(BytecodeViewer.viewer.das.isSelected()), "-hes=" + r(BytecodeViewer.viewer.hes.isSelected()), "-hdc=" + r(BytecodeViewer.viewer.hdc.isSelected()), "-dgs=" + r(BytecodeViewer.viewer.dgs.isSelected()), "-ner=" + r(BytecodeViewer.viewer.ner.isSelected()), "-den=" + r(BytecodeViewer.viewer.den.isSelected()), "-rgn=" + r(BytecodeViewer.viewer.rgn.isSelected()), "-bto=" + r(BytecodeViewer.viewer.bto.isSelected()), "-nns=" + r(BytecodeViewer.viewer.nns.isSelected()), "-uto=" + r(BytecodeViewer.viewer.uto.isSelected()), "-udv=" + r(BytecodeViewer.viewer.udv.isSelected()), "-rer=" + r(BytecodeViewer.viewer.rer.isSelected()), "-fdi=" + r(BytecodeViewer.viewer.fdi.isSelected()), "-asc=" + r(BytecodeViewer.viewer.asc.isSelected()), "-ren=" + r(BytecodeViewer.viewer.ren.isSelected()), className, folder}; + return new String[]{"-rbr=" + r(BytecodeViewer.viewer.rbr.isSelected()), + "-rsy=" + r(BytecodeViewer.viewer.rsy.isSelected()), + "-din=" + r(BytecodeViewer.viewer.din.isSelected()), + "-dc4=" + r(BytecodeViewer.viewer.dc4.isSelected()), + "-das=" + r(BytecodeViewer.viewer.das.isSelected()), + "-hes=" + r(BytecodeViewer.viewer.hes.isSelected()), + "-hdc=" + r(BytecodeViewer.viewer.hdc.isSelected()), + "-dgs=" + r(BytecodeViewer.viewer.dgs.isSelected()), + "-ner=" + r(BytecodeViewer.viewer.ner.isSelected()), + "-den=" + r(BytecodeViewer.viewer.den.isSelected()), + "-rgn=" + r(BytecodeViewer.viewer.rgn.isSelected()), + "-bto=" + r(BytecodeViewer.viewer.bto.isSelected()), + "-nns=" + r(BytecodeViewer.viewer.nns.isSelected()), + "-uto=" + r(BytecodeViewer.viewer.uto.isSelected()), + "-udv=" + r(BytecodeViewer.viewer.udv.isSelected()), + "-rer=" + r(BytecodeViewer.viewer.rer.isSelected()), + "-fdi=" + r(BytecodeViewer.viewer.fdi.isSelected()), + "-asc=" + r(BytecodeViewer.viewer.asc.isSelected()), + "-ren=" + r(BytecodeViewer.viewer.ren.isSelected()), + className, folder}; } private String r(boolean b) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JADXDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JADXDecompiler.java index c55e8ecc1..c69a35354 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JADXDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JADXDecompiler.java @@ -42,10 +42,8 @@ */ public class JADXDecompiler extends InternalDecompiler { - private final Random r = new Random(); - @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { String fileStart = TEMP_DIRECTORY + FS; @@ -54,23 +52,23 @@ public String decompileClassNode(ClassNode cn, byte[] b) try (FileOutputStream fos = new FileOutputStream(tempClass)) { - fos.write(b); + fos.write(bytes); } catch (IOException e) { BytecodeViewer.handleException(e); } - File fuckery = new File(fuckery(fileStart)); - fuckery.mkdirs(); + File freeDirectory = new File(findUnusedFile(fileStart)); + freeDirectory.mkdirs(); try { JadxArgs args = new JadxArgs(); args.setInputFile(tempClass); - args.setOutDir(fuckery); - args.setOutDirSrc(fuckery); - args.setOutDirRes(fuckery); + args.setOutDir(freeDirectory); + args.setOutDirSrc(freeDirectory); + args.setOutDirRes(freeDirectory); JadxDecompiler jadx = new JadxDecompiler(args); jadx.load(); @@ -86,8 +84,8 @@ public String decompileClassNode(ClassNode cn, byte[] b) tempClass.delete(); - if (fuckery.exists()) - return findFile(MiscUtils.listFiles(fuckery)); + if (freeDirectory.exists()) + return findFile(MiscUtils.listFiles(freeDirectory)); if (exception.isEmpty()) exception = "Decompiled source file not found!"; @@ -95,29 +93,29 @@ public String decompileClassNode(ClassNode cn, byte[] b) return JADX + " " + ERROR + "! " + ExceptionUI.SEND_STACKTRACE_TO + NL + NL + TranslatedStrings.SUGGESTED_FIX_DECOMPILER_ERROR + NL + NL + exception; } - //TODO remove - public String fuckery(String start) + public String findUnusedFile(String start) { - int failSafe = 0; - while (failSafe++ <= 42069) + long index = 0; + + while (true) { - File f = new File(start + r.nextInt(Integer.MAX_VALUE)); + File f = new File(start + index); + if (!f.exists()) return f.toString(); } - - return null; } - public String findFile(File[] fA) + public String findFile(File[] fileArray) { - for (File f : fA) + for (File f : fileArray) { if (f.isDirectory()) return findFile(MiscUtils.listFiles(f)); else { String s; + try { s = DiskReader.loadAsString(f.getAbsolutePath()); @@ -131,6 +129,7 @@ public String findFile(File[] fA) return JADX + " " + ERROR + "! " + ExceptionUI.SEND_STACKTRACE_TO + NL + NL + TranslatedStrings.SUGGESTED_FIX_DECOMPILER_ERROR + NL + NL + exception; } + return s; } } @@ -141,5 +140,6 @@ public String findFile(File[] fA) @Override public void decompileToZip(String sourceJar, String zipName) { + //TODO } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JDGUIDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JDGUIDecompiler.java index 177356335..13af2a4fb 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JDGUIDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JDGUIDecompiler.java @@ -50,9 +50,10 @@ public class JDGUIDecompiler extends InternalDecompiler { @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { String exception; + try { final File tempDirectory = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); @@ -75,14 +76,13 @@ public String decompileClassNode(ClassNode cn, byte[] b) try (FileOutputStream fos = new FileOutputStream(tempClass)) { - fos.write(b); + fos.write(bytes); } catch (IOException e) { BytecodeViewer.handleException(e); } - String pathToClass = tempClass.getAbsolutePath().replace('/', File.separatorChar).replace('\\', File.separatorChar); String directoryPath = JDGUIClassFileUtil.ExtractDirectoryPath(pathToClass); String internalPath = JDGUIClassFileUtil.ExtractInternalPath(directoryPath, pathToClass); @@ -104,8 +104,6 @@ public boolean isMergeEmptyLines() DirectoryLoader loader = new DirectoryLoader(new File(directoryPath)); - //PrintStream ps = new PrintStream("test.html"); - //HtmlPrinter printer = new HtmlPrinter(ps); org.jd.core.v1.api.Decompiler decompiler = new ClassFileToJavaSourceDecompiler(); try (PrintStream ps = new PrintStream(tempJava.getAbsolutePath()); PlainTextPrinter printer = new PlainTextPrinter(preferences, ps)) @@ -130,5 +128,6 @@ public boolean isMergeEmptyLines() @Override public void decompileToZip(String sourceJar, String zipName) { + //TODO } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JavapDisassembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JavapDisassembler.java index 853cacda2..90c300b43 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JavapDisassembler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/JavapDisassembler.java @@ -49,20 +49,21 @@ public class JavapDisassembler extends InternalDecompiler { @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { if (!ExternalResources.getSingleton().hasJavaToolsSet()) return "Set Java Tools Path!"; - return synchronizedDecompilation(cn, b); + return synchronizedDecompilation(cn, bytes); } private synchronized String synchronizedDecompilation(ClassNode cn, byte[] b) { final File tempDirectory = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); - tempDirectory.mkdir(); final File tempClass = new File(Constants.TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(32) + ".class"); + tempDirectory.mkdir(); + DiskWriter.replaceFileBytes(tempClass.getAbsolutePath(), b, false); JFrameConsolePrintStream sysOutBuffer = null; diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDecompiler.java index cd004f194..902c4c88a 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDecompiler.java @@ -64,12 +64,14 @@ public String buildCLIArguments() return ";" + Arrays.stream(files).filter(File::isFile).map(File::getAbsolutePath).collect(Collectors.joining(";")); } - public String decompileClassNode(File krakatauTempJar, File krakatauTempDir, ClassNode cn) + @Override + public String decompileClassNode(ClassNode cn, byte[] bytes) { if (!ExternalResources.getSingleton().hasSetPython2Command()) return TranslatedStrings.YOU_NEED_TO_SET_YOUR_PYTHON_2_PATH.toString(); ExternalResources.getSingleton().rtCheck(); + if (Configuration.rt.isEmpty()) { BytecodeViewer.showMessage(TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_A + "\r\n" + TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_B); @@ -82,74 +84,23 @@ public String decompileClassNode(File krakatauTempJar, File krakatauTempDir, Cla return TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_A + " " + TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_B; } - String s = ExceptionUI.SEND_STACKTRACE_TO_NL; - - try - { - String[] pythonCommands = new String[]{Configuration.python2}; - if (Configuration.python2Extra) - pythonCommands = ArrayUtils.addAll(pythonCommands, "-2"); - - ProcessBuilder pb = new ProcessBuilder(ArrayUtils.addAll(pythonCommands, "-O", //love you storyyeller <3 - krakatauWorkingDirectory + FS + "decompile.py", "-skip", //love you storyyeller <3 - "-nauto", "-path", Configuration.rt + ";" + krakatauTempJar.getAbsolutePath() + buildCLIArguments(), "-out", krakatauTempDir.getAbsolutePath(), cn.name + ".class")); - - Process process = pb.start(); - BytecodeViewer.createdProcesses.add(process); - - StringBuilder log = new StringBuilder(TranslatedStrings.PROCESS2 + NL + NL); - - //Read out dir output - try (InputStream is = process.getInputStream(); - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr)) - { - String line; - while ((line = br.readLine()) != null) - { - log.append(NL).append(line); - } - } - - log.append(NL).append(NL).append(TranslatedStrings.ERROR2).append(NL).append(NL); - - try (InputStream is = process.getErrorStream(); - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr)) - { - String line; - while ((line = br.readLine()) != null) - { - log.append(NL).append(line); - } - } + final File tempDirectory = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); + final File tempJar = new File(Constants.TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(32) + ".jar"); - int exitValue = process.waitFor(); - log.append(NL).append(NL).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue); - s = log.toString(); + tempDirectory.mkdir(); - //if the motherfucker failed this'll fail, aka wont set. - s = DiskReader.loadAsString(krakatauTempDir.getAbsolutePath() + FS + cn.name + ".java"); - } - catch (Exception e) - { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - e.printStackTrace(); - s += NL + ExceptionUI.SEND_STACKTRACE_TO_NL + sw; - } + JarUtils.saveAsJarClassesOnly(BytecodeViewer.getLoadedClasses(), tempJar.getAbsolutePath()); - return s; + return decompileClassNode(tempJar, tempDirectory, cn); } - @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(File tempJar, File tempDir, ClassNode cn) { - //TODO look into transforming through krakatau as a zip rather than direct classfile - if (!ExternalResources.getSingleton().hasSetPython2Command()) return TranslatedStrings.YOU_NEED_TO_SET_YOUR_PYTHON_2_PATH.toString(); + ExternalResources.getSingleton().rtCheck(); + if (Configuration.rt.isEmpty()) { BytecodeViewer.showMessage(TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_A + "\r\n" + TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_B); @@ -158,17 +109,11 @@ public String decompileClassNode(ClassNode cn, byte[] b) if (Configuration.rt.isEmpty()) { - BytecodeViewer.showMessage("You need to set RT.jar!"); - return "Set your paths"; + BytecodeViewer.showMessage(TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_A + "\r\n" + TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_B); + return TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_A + " " + TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_B; } - String s = ExceptionUI.SEND_STACKTRACE_TO_NL; - - final File tempDirectory = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); - tempDirectory.mkdir(); - final File tempJar = new File(Constants.TEMP_DIRECTORY + FS + "temp" + MiscUtils.randomString(32) + ".jar"); - - JarUtils.saveAsJarClassesOnly(BytecodeViewer.getLoadedClasses(), tempJar.getAbsolutePath()); + String returnString = ExceptionUI.SEND_STACKTRACE_TO_NL; try { @@ -178,7 +123,8 @@ public String decompileClassNode(ClassNode cn, byte[] b) ProcessBuilder pb = new ProcessBuilder(ArrayUtils.addAll(pythonCommands, "-O", //love you storyyeller <3 krakatauWorkingDirectory + FS + "decompile.py", "-skip", //love you storyyeller <3 - "-nauto", "-path", Configuration.rt + ";" + tempJar.getAbsolutePath() + buildCLIArguments(), "-out", tempDirectory.getAbsolutePath(), cn.name + ".class")); + "-nauto", "-path", Configuration.rt + ";" + tempJar.getAbsolutePath() + buildCLIArguments(), + "-out", tempDir.getAbsolutePath(), cn.name + ".class")); Process process = pb.start(); BytecodeViewer.createdProcesses.add(process); @@ -212,22 +158,20 @@ public String decompileClassNode(ClassNode cn, byte[] b) int exitValue = process.waitFor(); log.append(NL).append(NL).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue); - s = log.toString(); + returnString = log.toString(); - //if the motherfucker failed this'll fail, aka wont set. - s = DiskReader.loadAsString(tempDirectory.getAbsolutePath() + FS + cn.name + ".java"); - tempDirectory.delete(); - tempJar.delete(); + // update the string on a successful disassemble + returnString = DiskReader.loadAsString(tempDir.getAbsolutePath() + FS + cn.name + ".java"); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); e.printStackTrace(); - s += NL + ExceptionUI.SEND_STACKTRACE_TO_NL + sw; + returnString += NL + ExceptionUI.SEND_STACKTRACE_TO_NL + sw; } - return s; + return returnString; } @Override @@ -237,18 +181,19 @@ public void decompileToZip(String sourceJar, String zipName) return; ExternalResources.getSingleton().rtCheck(); + if (Configuration.rt.isEmpty()) { BytecodeViewer.showMessage(TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_A + "\r\n" + TranslatedStrings.YOU_NEED_TO_SET_YOUR_JAVA_RT_PATH_B); ExternalResources.getSingleton().selectJRERTLibrary(); } - String ran = MiscUtils.randomString(32); + final String ran = MiscUtils.randomString(32); final File tempDirectory = new File(Constants.TEMP_DIRECTORY + FS + ran + FS); - tempDirectory.mkdir(); - final File tempJar = new File(sourceJar); + tempDirectory.mkdir(); + try { String[] pythonCommands = new String[]{Configuration.python2}; diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDisassembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDisassembler.java index f67a255f9..da42c6908 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDisassembler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/KrakatauDisassembler.java @@ -45,12 +45,12 @@ public class KrakatauDisassembler extends InternalDecompiler { @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { if (!ExternalResources.getSingleton().hasSetPython2Command()) return TranslatedStrings.YOU_NEED_TO_SET_YOUR_PYTHON_2_PATH.toString(); - String s = ExceptionUI.SEND_STACKTRACE_TO_NL; + String returnString = ExceptionUI.SEND_STACKTRACE_TO_NL; final File tempDirectory = new File(Constants.TEMP_DIRECTORY + FS + MiscUtils.randomString(32) + FS); tempDirectory.mkdir(); @@ -98,19 +98,20 @@ public String decompileClassNode(ClassNode cn, byte[] b) int exitValue = process.waitFor(); log.append(NL).append(NL).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue); - s = log.toString(); + returnString = log.toString(); - // if the motherfucker failed this'll fail, aka won't set. - s = DiskReader.loadAsString(tempDirectory.getAbsolutePath() + FS + cn.name + ".j"); + // update the string on a successful disassemble + returnString = DiskReader.loadAsString(tempDirectory.getAbsolutePath() + FS + cn.name + ".j"); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); e.printStackTrace(); - s += NL + ExceptionUI.SEND_STACKTRACE_TO_NL + sw; + returnString += NL + ExceptionUI.SEND_STACKTRACE_TO_NL + sw; } - return s; + + return returnString; } @Override @@ -132,7 +133,8 @@ public void decompileToZip(String sourceJar, String zipName) pythonCommands = ArrayUtils.addAll(pythonCommands, "-2"); ProcessBuilder pb = new ProcessBuilder(ArrayUtils.addAll(pythonCommands, "-O", //love you storyyeller <3 - krakatauWorkingDirectory + FS + "disassemble.py", "-path", Configuration.rt + ";" + tempJar.getAbsolutePath(), "-out", tempDirectory.getAbsolutePath(), tempJar.getAbsolutePath())); + krakatauWorkingDirectory + FS + "disassemble.py", "-path", Configuration.rt + ";" + tempJar.getAbsolutePath(), + "-out", tempDirectory.getAbsolutePath(), tempJar.getAbsolutePath())); Process process = pb.start(); BytecodeViewer.createdProcesses.add(process); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ProcyonDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ProcyonDecompiler.java index 8aab8ab08..a125fd463 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ProcyonDecompiler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/ProcyonDecompiler.java @@ -75,18 +75,17 @@ public DecompilerSettings getDecompilerSettings() } @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { String exception; try { - String fileStart = TEMP_DIRECTORY + FS + "temp"; - + final String fileStart = TEMP_DIRECTORY + FS + "temp"; final File tempClass = new File(MiscUtils.getUniqueName(fileStart, ".class") + ".class"); try (FileOutputStream fos = new FileOutputStream(tempClass)) { - fos.write(b); + fos.write(bytes); } catch (IOException e) { @@ -104,6 +103,7 @@ public String decompileClassNode(ClassNode cn, byte[] b) decompilationOptions.setFullDecompilation(true); TypeDefinition resolvedType; + if (type == null || ((resolvedType = type.resolve()) == null)) throw new Exception("Unable to resolve type."); @@ -142,7 +142,10 @@ public void decompileToZip(String sourceJar, String zipName) */ private void doSaveJarDecompiled(File inFile, File outFile) throws Exception { - try (JarFile jfile = new JarFile(inFile); FileOutputStream dest = new FileOutputStream(outFile); BufferedOutputStream buffDest = new BufferedOutputStream(dest); ZipOutputStream out = new ZipOutputStream(buffDest)) + try (JarFile jfile = new JarFile(inFile); + FileOutputStream dest = new FileOutputStream(outFile); + BufferedOutputStream buffDest = new BufferedOutputStream(dest); + ZipOutputStream out = new ZipOutputStream(buffDest)) { byte[] data = new byte[1024]; DecompilerSettings settings = getDecompilerSettings(); @@ -157,24 +160,30 @@ private void doSaveJarDecompiled(File inFile, File outFile) throws Exception Enumeration ent = jfile.entries(); Set history = new HashSet<>(); + while (ent.hasMoreElements()) { JarEntry entry = ent.nextElement(); + if (entry.getName().endsWith(".class")) { JarEntry etn = new JarEntry(entry.getName().replace(".class", ".java")); + if (history.add(etn)) { out.putNextEntry(etn); + try { String internalName = StringUtilities.removeRight(entry.getName(), ".class"); TypeReference type = metadataSystem.lookupType(internalName); TypeDefinition resolvedType; + if ((type == null) || ((resolvedType = type.resolve()) == null)) { throw new Exception("Unable to resolve type."); } + Writer writer = new OutputStreamWriter(out); settings.getLanguage().decompileType(resolvedType, new PlainTextOutput(writer), decompilationOptions); writer.flush(); @@ -190,10 +199,13 @@ private void doSaveJarDecompiled(File inFile, File outFile) throws Exception try { JarEntry etn = new JarEntry(entry.getName()); + if (history.add(etn)) continue; + history.add(etn); out.putNextEntry(etn); + try (InputStream in = jfile.getInputStream(entry)) { if (in != null) @@ -214,9 +226,7 @@ private void doSaveJarDecompiled(File inFile, File outFile) throws Exception { // some jars contain duplicate pom.xml entries: ignore it if (!ze.getMessage().contains("duplicate")) - { throw ze; - } } } } @@ -229,28 +239,26 @@ private void doSaveJarDecompiled(File inFile, File outFile) throws Exception public static final class LuytenTypeLoader implements ITypeLoader { - private final List _typeLoaders; + private final List typeLoaders; public LuytenTypeLoader() { - _typeLoaders = new ArrayList<>(); - _typeLoaders.add(new InputTypeLoader()); + typeLoaders = new ArrayList<>(); + typeLoaders.add(new InputTypeLoader()); } public List getTypeLoaders() { - return _typeLoaders; + return typeLoaders; } @Override public boolean tryLoadType(String internalName, Buffer buffer) { - for (ITypeLoader typeLoader : _typeLoaders) + for (ITypeLoader typeLoader : typeLoaders) { if (typeLoader.tryLoadType(internalName, buffer)) - { return true; - } buffer.reset(); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/SmaliDisassembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/SmaliDisassembler.java index 5bd45b56d..66c8c12a7 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/SmaliDisassembler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/impl/SmaliDisassembler.java @@ -44,21 +44,20 @@ public class SmaliDisassembler extends InternalDecompiler { @Override - public String decompileClassNode(ClassNode cn, byte[] b) + public String decompileClassNode(ClassNode cn, byte[] bytes) { - String exception = ""; - String fileStart = TEMP_DIRECTORY + FS + "temp"; - - String start = MiscUtils.getUniqueName(fileStart, ".class"); - + final String fileStart = TEMP_DIRECTORY + FS + "temp"; + final String start = MiscUtils.getUniqueName(fileStart, ".class"); final File tempClass = new File(start + ".class"); final File tempDex = new File(start + ".dex"); final File tempDexOut = new File(start + "-out"); final File tempSmali = new File(start + "-smali"); //output directory + String exception = ""; + try (FileOutputStream fos = new FileOutputStream(tempClass)) { - fos.write(b); + fos.write(bytes); } catch (IOException e) { diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/jdgui/JDGUIClassFileUtil.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/jdgui/JDGUIClassFileUtil.java index 2b418dd41..b841e1980 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/jdgui/JDGUIClassFileUtil.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/jdgui/JDGUIClassFileUtil.java @@ -40,7 +40,9 @@ public static String ExtractDirectoryPath(String pathToClass) { String directoryPath; - try (FileInputStream fis = new FileInputStream(pathToClass); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis)) + try (FileInputStream fis = new FileInputStream(pathToClass); + BufferedInputStream bis = new BufferedInputStream(fis); + DataInputStream dis = new DataInputStream(bis)) { int magic = dis.readInt(); if (magic != ClassFileReader.JAVA_MAGIC_NUMBER) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/DecompilerViewComponent.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/DecompilerViewComponent.java index 7a4c77eb9..bf01013e9 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/DecompilerViewComponent.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/DecompilerViewComponent.java @@ -59,6 +59,7 @@ private void createMenu() { if (type == JAVA || type == JAVA_NON_EDITABLE || type == JAVA_AND_BYTECODE) menu.add(java); + if (type == BYTECODE || type == JAVA_AND_BYTECODE || type == BYTECODE_NON_EDITABLE) menu.add(bytecode); @@ -75,6 +76,7 @@ public void addToGroup(ButtonGroup group) { if (type == JAVA || type == JAVA_NON_EDITABLE || type == JAVA_AND_BYTECODE) group.add(java); + if (type == BYTECODE || type == JAVA_AND_BYTECODE || type == BYTECODE_NON_EDITABLE) group.add(bytecode); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExportJar.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExportJar.java index 8f2f55460..5dfe1877d 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExportJar.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExportJar.java @@ -57,11 +57,13 @@ public ExportJar(String jarPath) btnNewButton.addActionListener(arg0 -> { BytecodeViewer.updateBusyStatus(true); + Thread t = new Thread(() -> { JarUtils.saveAsJar(BytecodeViewer.getLoadedClasses(), jarPath, manifest.getText()); BytecodeViewer.updateBusyStatus(false); }, "Jar Export"); + t.start(); dispose(); }); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExtendedJOptionPane.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExtendedJOptionPane.java index ae4a9fc01..fa7811947 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExtendedJOptionPane.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/ExtendedJOptionPane.java @@ -151,6 +151,7 @@ public static void showJPanelDialog(Component parentComponent, JScrollPane panel private static JDialog createNewJDialog(Component parentComponent, JOptionPane pane, String title, int style, OnCreate onCreate) { JDialog dialog = pane.createDialog(parentComponent, title); + if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/FileChooser.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/FileChooser.java index 3796a7451..f6e9d5303 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/FileChooser.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/FileChooser.java @@ -45,6 +45,7 @@ public FileChooser(boolean skipFileFilter, File file, String title, String descr Set extensionSet = new HashSet<>(Arrays.asList(extensions)); setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); + try { setSelectedFile(file); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/JFrameConsole.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/JFrameConsole.java index 349b96d3d..91d60fe58 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/JFrameConsole.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/JFrameConsole.java @@ -144,7 +144,8 @@ public String trimConsoleText(String s) String trimmed = s.substring(0, max); if (!trimmed.startsWith("WARNING: Skipping")) - trimmed = ("WARNING: Skipping " + skipped + " chars, allowing " + max + "\n\r") + "Full log saved to: " + tempFile.getAbsolutePath() + "\n\r\n\r" + trimmed; + trimmed = ("WARNING: Skipping " + skipped + " chars, allowing " + max + "\n\r") + + "Full log saved to: " + tempFile.getAbsolutePath() + "\n\r\n\r" + trimmed; return trimmed; } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MethodsRenderer.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MethodsRenderer.java index 42c5881c4..95667673a 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MethodsRenderer.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MethodsRenderer.java @@ -48,6 +48,7 @@ public Component getListCellRendererComponent(JList list, Object value, int i MethodParser methods; List methodParsers = bytecodeViewPanelUpdater.viewer.methods; BytecodeViewPanel bytecodeViewPanel = bytecodeViewPanelUpdater.bytecodeViewPanel; + try { methods = methodParsers.get(bytecodeViewPanel.decompiler.ordinal()); @@ -56,8 +57,10 @@ public Component getListCellRendererComponent(JList list, Object value, int i { methods = methodParsers.get(bytecodeViewPanel.panelIndex); } + MethodParser.Method method = methods.getMethod(methodIndex); setText(method.toString()); + return this; } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MultipleChoiceDialog.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MultipleChoiceDialog.java index 9d21e8ccb..4b3ebd23d 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MultipleChoiceDialog.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MultipleChoiceDialog.java @@ -47,6 +47,7 @@ public int promptChoice() dialog.setVisible(true); Object obj = pane.getValue(); int result = -1; + for (int k = 0; k < options.length; k++) if (options[k].equals(obj)) result = k; diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MyErrorStripe.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MyErrorStripe.java index 60ec11392..5f9deff71 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MyErrorStripe.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/MyErrorStripe.java @@ -71,6 +71,7 @@ private int lineToY(int line, Rectangle r) float lineCount = textArea.getLineCount(); int lineHeight = textArea.getLineHeight(); int linesPerVisibleRect = h / lineHeight; + return Math.round((h - 1) * line / Math.max(lineCount, linesPerVisibleRect)); } @@ -81,6 +82,7 @@ private int yToLine(int y) int lineHeight = textArea.getLineHeight(); int linesPerVisibleRect = h / lineHeight; int lineCount = textArea.getLineCount(); + if (y < h) { float at = y / (float) h; @@ -119,6 +121,7 @@ private void addMarkersForRanges(List occurrences, Map occurrences, Map -1) { try @@ -353,6 +359,7 @@ private void addNotice(ParserNotice notice) protected void paintComponent(Graphics g) { final ParserNotice notice = getHighestPriorityNotice(); + if (notice != null) paintParserNoticeMarker((Graphics2D) g, notice, getWidth(), getHeight()); } @@ -362,6 +369,7 @@ protected void mouseClicked(MouseEvent e) ParserNotice pn = notices.get(0); int offs = pn.getOffset(); int len = pn.getLength(); + if (offs > -1 && len > -1) // These values are optional { DocumentRange range = new DocumentRange(offs, offs + len); @@ -370,6 +378,7 @@ protected void mouseClicked(MouseEvent e) else { int line = pn.getLine(); + try { offs = textArea.getLineStartOffset(line); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RSyntaxTextAreaHighlighterEx.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RSyntaxTextAreaHighlighterEx.java index ef0507fe4..ca334a5b2 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RSyntaxTextAreaHighlighterEx.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RSyntaxTextAreaHighlighterEx.java @@ -72,6 +72,7 @@ public List getMarkedOccurrences() { int start = info.getStartOffset(); int end = info.getEndOffset() + 1; // HACK + if (start <= end) { // Occasionally a Marked Occurrence can have a lost end offset @@ -116,6 +117,7 @@ public Color getColor() if (notice != null) { color = notice.getColor(); + if (color == null) color = DEFAULT_PARSER_NOTICE_COLOR; } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RunOptions.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RunOptions.java index b5dc8bb0f..4d0f92555 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RunOptions.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/RunOptions.java @@ -111,6 +111,7 @@ public RunOptions() printToCommandLine.setBounds(6, 315, 232, 23); getContentPane().add(printToCommandLine); this.setLocationRelativeTo(null); + btnNewButton.addActionListener(arg0 -> { PluginManager.runPlugin(new EZInjection(accessModifiers.isSelected(), injectHooks.isSelected(), debugMethodCalls.isSelected(), invokeMethod.isSelected(), mainMethodFQN.getText(), false, false, debugClasses.getText(), this.socksProxy.getText(), forceProxy.isSelected(), launchReflectionKit.isSelected(), console.isSelected(), printToCommandLine.isSelected())); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/SettingsDialog.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/SettingsDialog.java index 9c241546a..fc5828d15 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/SettingsDialog.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/SettingsDialog.java @@ -49,6 +49,7 @@ public SettingsDialog(JMenu menu, JPanel display) return; List options = new ArrayList<>(); + for (Component child : menu.getMenuComponents()) { if (!(child instanceof JMenuItem)) @@ -83,6 +84,7 @@ public void showDialog() private void buildPanel() { display.setLayout(new BoxLayout(display, BoxLayout.Y_AXIS)); + for (JMenuItem menuItem : options) display.add(menuItem); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/TextAreaSearchPanel.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/TextAreaSearchPanel.java index 15250bff9..b3b9bf647 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/TextAreaSearchPanel.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/TextAreaSearchPanel.java @@ -42,7 +42,9 @@ public class TextAreaSearchPanel extends JPanel public TextAreaSearchPanel(JTextArea textArea) { super(new BorderLayout()); + this.textArea = textArea; + setup(); setVisible(true); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/WaitBusyIcon.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/WaitBusyIcon.java index 0e14afe15..693ae0e01 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/WaitBusyIcon.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/WaitBusyIcon.java @@ -35,7 +35,9 @@ public class WaitBusyIcon extends JMenuItemIcon public WaitBusyIcon() { super(new RotatableIcon(IconResources.busyIcon)); + animator = new RotatableIconAnimator(8, (RotatableIcon) getIcon(), this); + addHierarchyListener(e -> { if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/actions/GoToAction.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/actions/GoToAction.java index a71f90931..327478cd4 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/actions/GoToAction.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/components/actions/GoToAction.java @@ -90,6 +90,7 @@ public void actionPerformed(ActionEvent e) if (localMember.line == line && localMember.columnStart - 1 <= column && localMember.columnEnd >= column) { Element root = textArea.getDocument().getDefaultRootElement(); + if (localMember.decRef.equals("declaration")) { int startOffset = root.getElement(localMember.line - 1).getStartOffset() + (localMember.columnStart - 1); @@ -115,6 +116,7 @@ public void actionPerformed(ActionEvent e) if (method.line == line && method.columnStart - 1 <= column && method.columnEnd >= column) { Element root = textArea.getDocument().getDefaultRootElement(); + if (method.decRef.equalsIgnoreCase("declaration")) { int startOffset = root.getElement(method.line - 1).getStartOffset() + (method.columnStart - 1); @@ -131,7 +133,6 @@ public void actionPerformed(ActionEvent e) } }); - open(textArea, false, false, true); } } @@ -144,6 +145,7 @@ public void actionPerformed(ActionEvent e) { name = clazz.owner; Element root = textArea.getDocument().getDefaultRootElement(); + if (clazz.type.equals("declaration")) { int startOffset = root.getElement(clazz.line - 1).getStartOffset() + (clazz.columnStart - 1); @@ -173,6 +175,7 @@ private ClassFileContainer openClass(String lexeme, boolean field, boolean metho return null; ResourceContainer resourceContainer = BytecodeViewer.getFileContainer(container.getParentContainer()); + if (resourceContainer == null) return null; @@ -188,6 +191,7 @@ else if (method) { ClassMethodLocation classMethodLocation = container.getMethodLocationsFor(lexeme).get(0); ClassReferenceLocation classReferenceLocation = null; + try { classReferenceLocation = container.getClassReferenceLocationsFor(classMethodLocation.owner).get(0); @@ -200,10 +204,12 @@ else if (method) return null; String packagePath = classReferenceLocation.packagePath; + if (packagePath.startsWith("java") || packagePath.startsWith("javax") || packagePath.startsWith("com.sun")) return null; String resourceName = packagePath + "/" + classMethodLocation.owner; + if (resourceContainer.resourceClasses.containsKey(resourceName)) { BytecodeViewer.viewer.workPane.addClassResource(resourceContainer, resourceName + ".class"); @@ -216,10 +222,12 @@ else if (method) { ClassReferenceLocation classReferenceLocation = container.getClassReferenceLocationsFor(lexeme).get(0); String packagePath = classReferenceLocation.packagePath; + if (packagePath.startsWith("java") || packagePath.startsWith("javax") || packagePath.startsWith("com.sun")) return null; String resourceName = packagePath + "/" + lexeme; + if (resourceContainer.resourceClasses.containsKey(resourceName)) { BytecodeViewer.viewer.workPane.addClassResource(resourceContainer, resourceName + ".class"); @@ -240,9 +248,11 @@ private void open(RSyntaxTextArea textArea, boolean isClass, boolean isField, bo token = TokenUtil.getToken(textArea, token); String lexeme = token.getLexeme(); ClassFileContainer classFileContainer; + if (isClass) { classFileContainer = openClass(lexeme, false, false); + if (classFileContainer == null) return; @@ -253,9 +263,7 @@ private void open(RSyntaxTextArea textArea, boolean isClass, boolean isField, bo classReference.forEach(classReferenceLocation -> { if (classReferenceLocation.type.equals("declaration")) - { moveCursor(classReferenceLocation.line, classReferenceLocation.columnStart); - } }); } }); @@ -273,9 +281,7 @@ else if (isField) fields.forEach(classFieldLocation -> { if (classFieldLocation.type.equals("declaration")) - { moveCursor(classFieldLocation.line, classFieldLocation.columnStart); - } }); } }); @@ -283,6 +289,7 @@ else if (isField) else if (isMethod) { classFileContainer = openClass(lexeme, false, true); + if (classFileContainer == null) return; @@ -293,14 +300,13 @@ else if (isMethod) methods.forEach(method -> { if (method.decRef.equalsIgnoreCase("declaration")) - { moveCursor(method.line, method.columnStart); - } }); } }); } }, "Open Class"); + thread.start(); } @@ -352,6 +358,7 @@ private void moveCursor(int line, int columnStart) if (caretListener instanceof BytecodeViewPanelUpdater.MarkerCaretListener) { BytecodeViewPanelUpdater.MarkerCaretListener markerCaretListener = (BytecodeViewPanelUpdater.MarkerCaretListener) caretListener; + markerCaretListener.caretUpdate(new CaretEvent(panel.textArea) { @Override diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcelist/ResourceListIconRenderer.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcelist/ResourceListIconRenderer.java index a0dcf922b..3e361dd3d 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcelist/ResourceListIconRenderer.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcelist/ResourceListIconRenderer.java @@ -63,7 +63,7 @@ public Component getTreeCellRendererComponent(JTree tree, Object value, boolean boolean iconSet = false; //guess file type based on extension - ResourceType knownResourceType = onlyName.contains(":") ? null : ResourceType.extensionMap.get(FilenameUtils.getExtension(onlyName).toLowerCase()); + ResourceType knownResourceType = onlyName.contains(":") ? null : ResourceType.EXTENSION_MAP.get(FilenameUtils.getExtension(onlyName).toLowerCase()); //set the icon to a known file type if (knownResourceType != null diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchRadius.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchRadius.java index 26f7df5c2..e5c53e679 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchRadius.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchRadius.java @@ -24,5 +24,6 @@ */ public enum SearchRadius { - All_Classes, Current_Class + All_Classes, + Current_Class } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchType.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchType.java index 131fafcd8..b3f7a72e9 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchType.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourcesearch/SearchType.java @@ -27,7 +27,11 @@ */ public enum SearchType { - Strings(new LDCSearch()), Regex(new RegexSearch()), MethodCall(new MethodCallSearch()), FieldCall(new FieldCallSearch()), MemberWithAnnotation(new MemberWithAnnotationSearch()); + Strings(new LDCSearch()), + Regex(new RegexSearch()), + MethodCall(new MethodCallSearch()), + FieldCall(new FieldCallSearch()), + MemberWithAnnotation(new MemberWithAnnotationSearch()); public final SearchPanel panel; diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/DecompilerSelectionPane.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/DecompilerSelectionPane.java index d6a1be7ff..70a8e2537 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/DecompilerSelectionPane.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/DecompilerSelectionPane.java @@ -107,6 +107,7 @@ public void buildMenu() //build the action commands none.setActionCommand(Decompiler.NONE.name()); hexcode.setActionCommand(Decompiler.HEXCODE_VIEWER.name()); + for (DecompilerViewComponent component : components) { for (Decompiler decompiler : component.getDecompilers()) @@ -123,6 +124,7 @@ public void buildMenu() //auto-save on decompiler change Enumeration it = group.getElements(); + while (it.hasMoreElements()) { AbstractButton button = it.nextElement(); @@ -140,14 +142,18 @@ public void buildMenu() menu.add(new JSeparator()); menu.add(procyon.getMenu()); menu.add(CFR.getMenu()); + if (!Configuration.jadxGroupedWithSmali) menu.add(JADX.getMenu()); + menu.add(JD.getMenu()); menu.add(fern.getMenu()); menu.add(krakatau.getMenu()); menu.add(new JSeparator()); + if (Configuration.jadxGroupedWithSmali) menu.add(JADX.getMenu()); + menu.add(smali.getMenu()); menu.add(new JSeparator()); menu.add(bytecode.getMenu()); @@ -166,6 +172,7 @@ public Decompiler getSelectedDecompiler() public void setSelectedDecompiler(Decompiler decompiler) { Enumeration it = group.getElements(); + while (it.hasMoreElements()) { AbstractButton button = it.nextElement(); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/TabComponent.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/TabComponent.java index 42d58f7d1..74985a2d2 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/TabComponent.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/TabComponent.java @@ -36,10 +36,9 @@ public class TabComponent extends JPanel public TabComponent(JTabbedPane pane) { super(new FlowLayout(FlowLayout.LEFT, 0, 0)); + if (pane == null) - { throw new NullPointerException("TabbedPane is null"); - } this.pane = pane; @@ -50,9 +49,7 @@ public String getText() { int i = pane.indexOfTabComponent(TabComponent.this); if (i != -1) - { return pane.getTitleAt(i); - } return null; } @@ -102,13 +99,9 @@ public String getText() return; if (pane.indexOfTabComponent(TabComponent.this) != 0) - { removeTab(0); - } else - { removeTab(1); - } } }); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/viewer/FileViewer.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/viewer/FileViewer.java index 4fe3fdff8..366b8031f 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/viewer/FileViewer.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/resourceviewer/viewer/FileViewer.java @@ -82,7 +82,7 @@ public void setContents() // (If none selected, try Pane2, Pane3, default to Procyon) //check by file extension to display image - if (!onlyName.contains(":") && ResourceType.imageExtensionMap.containsKey(FilenameUtils.getExtension(onlyName)) && !hexViewerOnly) + if (!onlyName.contains(":") && ResourceType.IMAGE_EXTENSION_MAP.containsKey(FilenameUtils.getExtension(onlyName)) && !hexViewerOnly) { canRefresh = true; diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/AbstractJTabbedPanePopupMenuHandler.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/AbstractJTabbedPanePopupMenuHandler.java index f5340b353..057340220 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/AbstractJTabbedPanePopupMenuHandler.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/AbstractJTabbedPanePopupMenuHandler.java @@ -32,6 +32,7 @@ public abstract class AbstractJTabbedPanePopupMenuHandler extends JTabbedPanePop public AbstractJTabbedPanePopupMenuHandler(JTabbedPane tabbedPane) { super(tabbedPane); + registerPopupEventListener(this); } @@ -39,6 +40,7 @@ public AbstractJTabbedPanePopupMenuHandler(JTabbedPane tabbedPane) public void onTabPopupEvent(JTabbedPane tabbedPane, int index, TabPopupEvent e) { JPopupMenu popupMenu = toBuildTabPopupMenu(tabbedPane, e.getPopupOnTab()); + popupTabMenuWithEvent(popupMenu, e); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPaneCloser.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPaneCloser.java index 595d06992..77debc564 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPaneCloser.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPaneCloser.java @@ -84,14 +84,11 @@ public void removeLeftComponents(Component component) do { Component c = this.tabbedPane.getComponentAt(i); + if (c != component) - { removeTabs.add(c); - } else - { break; - } } while (i++ < count); for (Component c : removeTabs) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPanePopupMenuTabsCloser.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPanePopupMenuTabsCloser.java index 0e9a1990e..386d1bfbc 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPanePopupMenuTabsCloser.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/tabpopup/closer/JTabbedPanePopupMenuTabsCloser.java @@ -54,6 +54,7 @@ public PopupMenuTabsCloseConfiguration getCloseConfiguration() public JPopupMenu toBuildTabPopupMenu(JTabbedPane tabbedPane, Component popupOnTab) { JPopupMenu popUpMenu = new JPopupMenu(); + if (closeConfiguration.isClose()) addItemCloseTab(popUpMenu, popupOnTab); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/MalwareScanModule.java b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/MalwareScanModule.java index 4bd20eafa..64dfe683d 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/MalwareScanModule.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/MalwareScanModule.java @@ -23,15 +23,20 @@ import the.bytecode.club.bytecodeviewer.malwarescanner.impl.*; /** - * All of the installed malware scan modules + * All the installed malware scan modules * * @author Konloch * @since 6/27/2021 */ public enum MalwareScanModule { - URL_SCANNER("Scan String URLs", new URLScanner(), true), REFLECTION_SCANNER("Scan Java Reflection", new ReflectionScanner(), false), JAVA_RUNTIME_SCANNER("Scan Java Runtime", new JavaRuntimeScanner(), true), JAVA_NET_SCANNER("Scan Java Net", new JavaNetScanner(), false), JAVA_IO_SCANNER("Scan Java IO", new JavaIOScanner(), false), AWT_ROBOT_SCANNER("Scan AWT Robot", new AWTRobotScanner(), true), NULL_SECURITY_MANAGER("Scan Null SecurityManager", new NullSecurityManagerScanner(), true), - ; + URL_SCANNER("Scan String URLs", new URLScanner(), true), + REFLECTION_SCANNER("Scan Java Reflection", new ReflectionScanner(), false), + JAVA_RUNTIME_SCANNER("Scan Java Runtime", new JavaRuntimeScanner(), true), + JAVA_NET_SCANNER("Scan Java Net", new JavaNetScanner(), false), + JAVA_IO_SCANNER("Scan Java IO", new JavaIOScanner(), false), + AWT_ROBOT_SCANNER("Scan AWT Robot", new AWTRobotScanner(), true), + NULL_SECURITY_MANAGER("Scan Null SecurityManager", new NullSecurityManagerScanner(), true); static { diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/AWTRobotScanner.java b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/AWTRobotScanner.java index 1a0f32da4..7e29c982a 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/AWTRobotScanner.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/AWTRobotScanner.java @@ -53,6 +53,7 @@ public void scanMethodInstruction(MalwareScan scan, ClassNode cn, MethodNode met if (instruction instanceof MethodInsnNode) { final MethodInsnNode min = (MethodInsnNode) instruction; + if (min.owner.startsWith("java/awt/Robot")) foundMethod(scan, instructionToString(instruction) + " at " + methodToString(cn, method) + NL); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaIOScanner.java b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaIOScanner.java index 1b8564c31..88aff7684 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaIOScanner.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaIOScanner.java @@ -47,6 +47,7 @@ public void scanMethodInstruction(MalwareScan scan, ClassNode cn, MethodNode met if (instruction instanceof MethodInsnNode) { final MethodInsnNode min = (MethodInsnNode) instruction; + if (min.owner.startsWith("java/io")) foundMethod(scan, instructionToString(instruction) + " at " + methodToString(cn, method) + NL); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaNetScanner.java b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaNetScanner.java index 90ceb0563..bf7954fed 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaNetScanner.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaNetScanner.java @@ -48,6 +48,7 @@ public void scanMethodInstruction(MalwareScan scan, ClassNode cn, MethodNode met if (instruction instanceof MethodInsnNode) { final MethodInsnNode min = (MethodInsnNode) instruction; + if (min.owner.startsWith("java/net")) foundMethod(scan, instructionToString(instruction) + " at " + methodToString(cn, method) + NL); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaRuntimeScanner.java b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaRuntimeScanner.java index aa2bef5d6..f96005f10 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaRuntimeScanner.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/JavaRuntimeScanner.java @@ -53,6 +53,7 @@ public void scanMethodInstruction(MalwareScan scan, ClassNode cn, MethodNode met if (instruction instanceof MethodInsnNode) { final MethodInsnNode min = (MethodInsnNode) instruction; + if (min.owner.startsWith("java/lang/Runtime")) foundMethod(scan, instructionToString(instruction) + " at " + methodToString(cn, method) + NL); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/NullSecurityManagerScanner.java b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/NullSecurityManagerScanner.java index 931909726..dce482b43 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/NullSecurityManagerScanner.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/NullSecurityManagerScanner.java @@ -57,10 +57,10 @@ public void scanMethodInstruction(MalwareScan scan, ClassNode cn, MethodNode met final String owner = min.owner; final String name = min.name; - if (lastInstruction == OpCode.ACONST_NULL.getCode() && owner.equals("java/lang/System") && name.equals("setSecurityManager")) - { + if (lastInstruction == OpCode.ACONST_NULL.getCode() + && owner.equals("java/lang/System") + && name.equals("setSecurityManager")) found(scan, "Security Manager set to null at method " + methodToString(cn, method) + NL); - } } lastInstruction = instruction.getOpcode(); @@ -70,6 +70,7 @@ public void scanMethodInstruction(MalwareScan scan, ClassNode cn, MethodNode met public void scanningClass(MalwareScan scan, ClassNode cn) { lastInstruction = 0; + super.scanningClass(scan, cn); } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/ReflectionScanner.java b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/ReflectionScanner.java index 6a84c9caa..abe7d5b11 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/ReflectionScanner.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/malwarescanner/impl/ReflectionScanner.java @@ -50,6 +50,7 @@ public void scanMethodInstruction(MalwareScan scan, ClassNode cn, MethodNode met if (instruction instanceof MethodInsnNode) { final MethodInsnNode min = (MethodInsnNode) instruction; + if (min.owner.startsWith("java/lang/reflect")) foundMethod(scan, instructionToString(instruction) + " at " + methodToString(cn, method) + NL); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java index 40239d6ab..f11844ebb 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java @@ -34,12 +34,18 @@ public abstract class JavaObfuscator extends Thread { + public static int MAX_STRING_LENGTH = 25; + public static int MIN_STRING_LENGTH = 5; + private final List names = new ArrayList<>(); + @Override public void run() { BytecodeViewer.updateBusyStatus(true); Configuration.runningObfuscation = true; + obfuscate(); + BytecodeViewer.refactorer.run(); Configuration.runningObfuscation = false; BytecodeViewer.updateBusyStatus(false); @@ -48,24 +54,16 @@ public void run() public int getStringLength() { if (BytecodeViewer.viewer.obfuscatorGroup.isSelected(BytecodeViewer.viewer.strongObf.getModel())) - { return MAX_STRING_LENGTH; - } - else - { // if(BytecodeViewer.viewer.obfuscatorGroup.isSelected(BytecodeViewer.viewer.lightObf.getModel())) - // { + else // if(BytecodeViewer.viewer.obfuscatorGroup.isSelected(BytecodeViewer.viewer.lightObf.getModel())) return MIN_STRING_LENGTH; - } } - public static int MAX_STRING_LENGTH = 25; - public static int MIN_STRING_LENGTH = 5; - private final List names = new ArrayList<>(); - protected String generateUniqueName(int length) { boolean found = false; String name = ""; + while (!found) { String nameTry = MiscUtils.randomString(1) + MiscUtils.randomStringNum(length - 1); @@ -79,6 +77,7 @@ protected String generateUniqueName(int length) found = true; } } + return name; } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java index 56a923e4b..e5e42228a 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java @@ -37,6 +37,7 @@ public void obfuscate() int stringLength = getStringLength(); System.out.println("Obfuscating class names..."); + for (ClassNode c : BytecodeViewer.getLoadedClasses()) { String newName = generateUniqueName(stringLength); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java index be8e982a2..148839fe0 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java @@ -38,6 +38,7 @@ public void obfuscate() int stringLength = getStringLength(); System.out.println("Obfuscating fields names..."); + for (ClassNode c : BytecodeViewer.getLoadedClasses()) { for (Object o : c.fields.toArray()) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java index b01574e9d..e3c62936e 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java @@ -39,6 +39,7 @@ public void obfuscate() int stringLength = getStringLength(); System.out.println("Obfuscating method names..."); + for (ClassNode c : BytecodeViewer.getLoadedClasses()) { for (Object o : c.methods.toArray()) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java index 8ed71ddce..a6feb712f 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java @@ -47,6 +47,7 @@ public RefactorMapper(HookMap hookMap) sortedFields = new HashMap<>(); mappingList = new ArrayList<>(); builder = new StringBuilder(); + for (MappingData hook : hookMap.getClasses()) { if (hook.getObfuscatedName().contains("$")) @@ -56,6 +57,7 @@ public RefactorMapper(HookMap hookMap) sortedClasses.put(obfuscatedName, hook); sortedClasses.put(refactoredName, hook); } + for (MethodMappingData hook : hookMap.getMethods()) { String obfuscatedName = hook.getMethodName().getObfuscatedName(); @@ -63,6 +65,7 @@ public RefactorMapper(HookMap hookMap) String obfuscatedCname = hook.getMethodOwner(); sortedMethods.put(obfuscatedCname + "$$$$" + obfuscatedName + "$$$$" + obfuscatedDesc, hook); } + for (FieldMappingData hook : hookMap.getFields()) { String obfuscatedName = hook.getName().getObfuscatedName(); @@ -83,6 +86,7 @@ public String map(String type) return sortedClasses.get(type).getRefactoredName(); } + return type; } @@ -90,6 +94,7 @@ public String map(String type) public String mapFieldName(String owner, String name, String desc) { String obfKey = owner + "$$$$" + name + "$$$$" + desc; + if (sortedFields.containsKey(obfKey)) { String map = owner + "." + name + " --> " + owner + sortedFields.get(obfKey).getName().getRefactoredName() + "\n"; @@ -97,6 +102,7 @@ public String mapFieldName(String owner, String name, String desc) mappingList.add(map); name = sortedFields.get(obfKey).getName().getRefactoredName(); } + return name; } @@ -104,6 +110,7 @@ public String mapFieldName(String owner, String name, String desc) public String mapMethodName(String owner, String name, String desc) { String obfKey = owner + "$$$$" + name + "$$$$" + desc; + if (sortedMethods.containsKey(obfKey)) { String map = owner + "." + name + " --> " + owner + sortedMethods.get(obfKey).getMethodName().getRefactoredName() + "\n"; @@ -111,6 +118,7 @@ public String mapMethodName(String owner, String name, String desc) mappingList.add(map); name = sortedMethods.get(obfKey).getMethodName().getRefactoredName(); } + return name; } @@ -120,6 +128,7 @@ public void printMap() { builder.append(map); } + System.out.println(builder.toString()); } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java index 7c8935644..3a4d9b91b 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java @@ -60,9 +60,11 @@ public void run() cr.accept(cn, 0); //refactored.put(oldName, cn); } + /*for (Map.Entry factor : refactored.entrySet()) { BytecodeViewer.relocate(factor.getKey(), factor.getValue()); }*/ + mapper.printMap(); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java index 510bb0d90..cf01e028c 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java @@ -56,22 +56,26 @@ public abstract class Remapper extends org.objectweb.asm.commons.Remapper public String mapDesc(String desc) { Type t = Type.getType(desc); + switch (t.getSort()) { case Type.ARRAY: StringBuilder s = new StringBuilder(mapDesc(t.getElementType().getDescriptor())); + for (int i = 0; i < t.getDimensions(); ++i) { s.insert(0, '['); } + return s.toString(); + case Type.OBJECT: String newType = map(t.getInternalName()); + if (newType != null) - { return 'L' + newType + ';'; - } } + return desc; } @@ -81,17 +85,22 @@ private Type mapType(Type t) { case Type.ARRAY: StringBuilder s = new StringBuilder(mapDesc(t.getElementType().getDescriptor())); + for (int i = 0; i < t.getDimensions(); ++i) { s.insert(0, '['); } + return Type.getType(s.toString()); + case Type.OBJECT: s = new StringBuilder(map(t.getInternalName())); return Type.getObjectType(s.toString()); + case Type.METHOD: return Type.getMethodType(mapMethodDesc(t.getDescriptor())); } + return t; } @@ -99,9 +108,8 @@ private Type mapType(Type t) public String mapType(String type) { if (type == null) - { return null; - } + return mapType(Type.getObjectType(type)).getInternalName(); } @@ -110,24 +118,26 @@ public String[] mapTypes(String[] types) { String[] newTypes = null; boolean needMapping = false; + for (int i = 0; i < types.length; i++) { String type = types[i]; String newType = map(type); + if (newType != null && newTypes == null) { newTypes = new String[types.length]; + if (i > 0) - { System.arraycopy(types, 0, newTypes, 0, i); - } + needMapping = true; } + if (needMapping) - { newTypes[i] = newType == null ? type : newType; - } } + return needMapping ? newTypes : types; } @@ -135,22 +145,24 @@ public String[] mapTypes(String[] types) public String mapMethodDesc(String desc) { if ("()V".equals(desc)) - { return desc; - } Type[] args = Type.getArgumentTypes(desc); StringBuilder sb = new StringBuilder("("); + for (Type arg : args) { sb.append(mapDesc(arg.getDescriptor())); } + Type returnType = Type.getReturnType(desc); + if (returnType == Type.VOID_TYPE) { sb.append(")V"); return sb.toString(); } + sb.append(')').append(mapDesc(returnType.getDescriptor())); return sb.toString(); } @@ -159,14 +171,14 @@ public String mapMethodDesc(String desc) public Object mapValue(Object value) { if (value instanceof Type) - { return mapType((Type) value); - } + if (value instanceof Handle) { Handle h = (Handle) value; return new Handle(h.getTag(), mapType(h.getOwner()), mapMethodName(h.getOwner(), h.getName(), h.getDesc()), mapMethodDesc(h.getDesc()), h.getTag() == Opcodes.H_INVOKEINTERFACE); } + return value; } @@ -179,20 +191,17 @@ public Object mapValue(Object value) public String mapSignature(String signature, boolean typeSignature) { if (signature == null) - { return null; - } + SignatureReader r = new SignatureReader(signature); SignatureWriter w = new SignatureWriter(); SignatureVisitor a = createSignatureRemapper(w); + if (typeSignature) - { r.acceptType(a); - } else - { r.accept(a); - } + return w.toString(); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java index 8a20dde5f..f08ea1231 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java @@ -106,9 +106,11 @@ private Object[] remapEntries(int n, Object[] entries) Object t = entries[i]; newEntries[i++] = t instanceof String ? remapper.mapType((String) t) : t; } while (i < n); + return newEntries; } } + return entries; } @@ -127,6 +129,7 @@ public void visitMethodInsn(int opcode, String owner, String name, String desc) super.visitMethodInsn(opcode, owner, name, desc); return; } + doVisitMethodInsn(opcode, owner, name, desc, opcode == Opcodes.INVOKEINTERFACE); } @@ -138,6 +141,7 @@ public void visitMethodInsn(int opcode, String owner, String name, String desc, super.visitMethodInsn(opcode, owner, name, desc, itf); return; } + doVisitMethodInsn(opcode, owner, name, desc, itf); } @@ -150,9 +154,7 @@ private void doVisitMethodInsn(int opcode, String owner, String name, String des // IMPORTANT: THIS ASSUMES THAT visitMethodInsn IS NOT OVERRIDDEN IN // LocalVariableSorter. if (mv != null) - { mv.visitMethodInsn(opcode, remapper.mapType(owner), remapper.mapMethodName(owner, name, desc), remapper.mapMethodDesc(desc), itf); - } } @Override @@ -162,6 +164,7 @@ public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object. { bsmArgs[i] = remapper.mapValue(bsmArgs[i]); } + super.visitInvokeDynamicInsn(remapper.mapInvokeDynamicMethodName(name, desc), remapper.mapMethodDesc(desc), (Handle) remapper.mapValue(bsm), bsmArgs); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java index ffec29399..717218684 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java @@ -90,7 +90,9 @@ public boolean equals(Object obj) return false; if (getClass() != obj.getClass()) return false; + FieldMappingData other = (FieldMappingData) obj; + if (desc == null) { if (other.desc != null) @@ -98,6 +100,7 @@ public boolean equals(Object obj) } else if (!desc.equals(other.desc)) return false; + if (fieldOwner == null) { if (other.fieldOwner != null) @@ -105,10 +108,9 @@ else if (!desc.equals(other.desc)) } else if (!fieldOwner.equals(other.fieldOwner)) return false; + if (name == null) - { return other.name == null; - } else return name.equals(other.name); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java index e0db408f2..cd3487012 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java @@ -76,7 +76,9 @@ public boolean equals(Object obj) return false; if (getClass() != obj.getClass()) return false; + MappingData other = (MappingData) obj; + if (obfuscatedName == null) { if (other.obfuscatedName != null) @@ -84,10 +86,9 @@ public boolean equals(Object obj) } else if (!obfuscatedName.equals(other.obfuscatedName)) return false; + if (refactoredName == null) - { return other.refactoredName == null; - } else return refactoredName.equals(other.refactoredName); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java index 2833f6d3e..1e3cb37b5 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java @@ -90,7 +90,9 @@ public boolean equals(Object obj) return false; if (getClass() != obj.getClass()) return false; + MethodMappingData other = (MethodMappingData) obj; + if (methodDesc == null) { if (other.methodDesc != null) @@ -98,6 +100,7 @@ public boolean equals(Object obj) } else if (!methodDesc.equals(other.methodDesc)) return false; + if (methodName == null) { if (other.methodName != null) @@ -105,10 +108,9 @@ else if (!methodDesc.equals(other.methodDesc)) } else if (!methodName.equals(other.methodName)) return false; + if (methodOwner == null) - { return other.methodOwner == null; - } else return methodOwner.equals(other.methodOwner); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java index 4e32c42ee..ef538d62a 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java @@ -42,7 +42,9 @@ public static void open() BytecodeViewer.showMessage("You're currently running an obfuscation task, wait for this to finish" + "."); return; } + new RenameClasses().start(); + BytecodeViewer.viewer.workPane.refreshClass.doClick(); BytecodeViewer.viewer.resourcePane.tree.updateUI(); } @@ -61,7 +63,8 @@ public void obfuscate() for (MethodNode o : c.methods) { /* As we dont want to rename any main-classes */ - if (o.name.equals("main") && o.desc.equals("([Ljava/lang/String;)V") || o.name.equals("init") && c.superName.equals("java/applet/Applet")) + if (o.name.equals("main") && o.desc.equals("([Ljava/lang/String;)V") + || o.name.equals("init") && c.superName.equals("java/applet/Applet")) continue classLoop; /* As we dont want to rename native dll methods */ diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java index bc85f8758..a374d16d1 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java @@ -42,7 +42,9 @@ public static void open() BytecodeViewer.showMessage("You're currently running an obfuscation task, wait for this to finish."); return; } + new RenameFields().start(); + BytecodeViewer.viewer.workPane.refreshClass.doClick(); BytecodeViewer.viewer.resourcePane.tree.updateUI(); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java index d290e986f..c08643c9f 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java @@ -43,7 +43,9 @@ public static void open() BytecodeViewer.showMessage("You're currently running an obfuscation task, wait for this to finish" + "."); return; } + new RenameMethods().start(); + BytecodeViewer.viewer.workPane.refreshClass.doClick(); BytecodeViewer.viewer.resourcePane.tree.updateUI(); } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java index c5ebadd8d..935255441 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java @@ -219,14 +219,13 @@ private boolean scanDecrypter(MethodNode decryptermethodnode, int newHashCode) if (i instanceof MethodInsnNode) { MethodInsnNode methodi = ((MethodInsnNode) i); + if ("currentThread".equals(methodi.name)) // find code form this instruction { insn = i; break; } - } - } if (insn == null) @@ -241,6 +240,7 @@ private boolean scanDecrypter(MethodNode decryptermethodnode, int newHashCode) if ("hashCode".equals(methodi.name)) // to this instruction break; } + removeInsn = insn; insn = insn.getNext(); iList.remove(removeInsn); // and remove it diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java index 44629fb9f..29634f919 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java @@ -75,6 +75,7 @@ public void scanClassNode(ClassNode classNode) if (v instanceof String) { String s = (String) v; + if (contains) { if (s.contains(originalLDC)) @@ -92,6 +93,7 @@ public void scanClassNode(ClassNode classNode) for (int i = 0; i < ((String[]) v).length; i++) { String s = ((String[]) v)[i]; + if (contains) { if (s.contains(originalLDC)) @@ -118,6 +120,7 @@ public void scanClassNode(ClassNode classNode) { MethodNode m = (MethodNode) o; InsnList iList = m.instructions; + for (AbstractInsnNode a : iList.toArray()) { if (a instanceof LdcInsnNode) @@ -125,6 +128,7 @@ public void scanClassNode(ClassNode classNode) if (((LdcInsnNode) a).cst instanceof String) { final String s = (String) ((LdcInsnNode) a).cst; + if (contains) { if (s.contains(originalLDC)) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewAPKAndroidPermissions.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewAPKAndroidPermissions.java index 96dbe6f6b..726e5a5ef 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewAPKAndroidPermissions.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewAPKAndroidPermissions.java @@ -38,6 +38,7 @@ public void execute(List classNodeList) frame.setVisible(true); byte[] encodedAndroidManifest = activeContainer.getFileContents("AndroidManifest.xml"); + if (encodedAndroidManifest == null) { frame.appendText("This plugin only works on valid Android APKs"); @@ -45,6 +46,7 @@ public void execute(List classNodeList) } byte[] decodedAndroidManifest = activeContainer.getFileContents("Decoded Resources/AndroidManifest.xml"); + if (decodedAndroidManifest != null) { String manifest = new String(decodedAndroidManifest, StandardCharsets.UTF_8); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewManifest.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewManifest.java index b323a856c..b0c751895 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewManifest.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ViewManifest.java @@ -39,6 +39,7 @@ public void execute(List classNodeList) //TODO android APKs may have AndroidManifests that can be viewed normally, this should be checked byte[] encodedAndroidManifest = activeContainer.getFileContents("AndroidManifest.xml"); + if (encodedAndroidManifest != null) { frame.appendText("Android APK Manifest:\r"); @@ -50,6 +51,7 @@ public void execute(List classNodeList) } byte[] jarManifest = activeContainer.getFileContents("META-INF/MANIFEST.MF"); + if (jarManifest != null) { if (!frame.getTextArea().getText().isEmpty()) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java index a91e94c7d..4094b0552 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java @@ -52,11 +52,13 @@ public void execute(List classNodeList) if (dialog.promptChoice() == 0) { boolean needsWarning = false; + for (Class cn : Objects.requireNonNull(BCV.loadClassesIntoClassLoader())) { try { Field[] fields = cn.getDeclaredFields(); + for (Field field : fields) { if (field.getName().equals("z")) @@ -81,9 +83,8 @@ public void execute(List classNodeList) } if (needsWarning) - { - BytecodeViewer.showMessage("Some classes failed to decrypt, if you'd like to decrypt all of them" + NL + "makes sure you include ALL the libraries it requires."); - } + BytecodeViewer.showMessage("Some classes failed to decrypt, if you'd like to decrypt all of them" + + NL + "makes sure you include ALL the libraries it requires."); gui.setText(out.toString()); gui.setVisible(true); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java index 35ce7a001..397c4b427 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java @@ -56,13 +56,9 @@ public Plugin run(File file) throws Throwable if (Objects.equals(cn.superName, PLUGIN_CLASS_NAME)) { if (pdata == null) - { pdata = d; - } else - { throw new RuntimeException("Multiple plugin subclasses."); - } } } @@ -92,9 +88,11 @@ private static Set loadData(File jarFile) throws Throwable try { String name = entry.getName(); + if (name.endsWith(".class")) { byte[] bytes = MiscUtils.getBytes(jis); + if (FileHeaderUtils.doesFileHeaderMatch(bytes, FileHeaderUtils.JAVA_CLASS_FILE_HEADER)) { try @@ -174,20 +172,20 @@ public Plugin getPlugin() public static class LoadingClassLoader extends ClassLoader { private final LoadedNodeData data; - private final Map cache; - private final Map> ccache; + private final Map nodeCache; + private final Map> classCache; private final Class pluginKlass; public LoadingClassLoader(LoadedNodeData data, Set set) throws Throwable { this.data = data; - cache = new HashMap<>(); - ccache = new HashMap<>(); + nodeCache = new HashMap<>(); + classCache = new HashMap<>(); for (LoadedNodeData d : set) { - cache.put(d.node.name, d); + nodeCache.put(d.node.name, d); } @SuppressWarnings("unchecked") Class pluginKlass = (Class) loadClass(data.node.name.replace("/", ".")); @@ -205,15 +203,16 @@ public Class findClass(String name) throws ClassNotFoundException System.out.println("finding " + name); - if (ccache.containsKey(name)) - return ccache.get(name); + if (classCache.containsKey(name)) + return classCache.get(name); + + LoadedNodeData data = nodeCache.get(name); - LoadedNodeData data = cache.get(name); if (data != null) { byte[] bytes = data.bytes; Class klass = defineClass(data.node.name.replace("/", "."), bytes, 0, bytes.length); - ccache.put(name, klass); + classCache.put(name, klass); return klass; } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceDecompiling.java b/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceDecompiling.java index f44cdc2af..e10044ad1 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceDecompiling.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceDecompiling.java @@ -70,7 +70,8 @@ public static void decompileSaveAll() if (!BytecodeViewer.autoCompileSuccessful()) return; - final JFileChooser fc = new FileChooser(Configuration.getLastSaveDirectory(), "Select Zip Export", "Zip Archives", "zip"); + final JFileChooser fc = new FileChooser(Configuration.getLastSaveDirectory(), + "Select Zip Export", "Zip Archives", "zip"); //if the user doesn't select a file then we should stop while we're ahead if (fc.showSaveDialog(BytecodeViewer.viewer) != JFileChooser.APPROVE_OPTION) @@ -87,7 +88,8 @@ public static void decompileSaveAll() return; //this temporary jar file will be used to store the classes while BCV performs decompilation - File temporaryTargetJar = MiscUtils.deleteExistingFile(new File(TEMP_DIRECTORY + FS + "temp_" + MiscUtils.getRandomizedName() + ".jar")); + File temporaryTargetJar = MiscUtils.deleteExistingFile(new File(TEMP_DIRECTORY + FS + + "temp_" + MiscUtils.getRandomizedName() + ".jar")); //extract all the loaded classes imported into BCV to the temporary target jar JarUtils.saveAsJarClassesOnly(BytecodeViewer.getLoadedClasses(), temporaryTargetJar.getAbsolutePath()); @@ -254,7 +256,8 @@ public static void decompileSaveAll(Decompiler decompiler, File targetJar, File BytecodeViewer.updateBusyStatus(true); //decompile all opened classes to zip - decompiler.getDecompiler().decompileToZip(targetJar.getAbsolutePath(), saveAll ? MiscUtils.append(outputZip, "-" + decompiler.getDecompilerNameProgrammic() + ".zip") : outputZip.getAbsolutePath()); + decompiler.getDecompiler().decompileToZip(targetJar.getAbsolutePath(), saveAll ? MiscUtils.append(outputZip, + "-" + decompiler.getDecompilerNameProgrammic() + ".zip") : outputZip.getAbsolutePath()); //signal to the user that BCV is finished performing that action BytecodeViewer.updateBusyStatus(false); @@ -266,7 +269,8 @@ public static void decompileCurrentlyOpenedResource(Decompiler decompiler, File BytecodeViewer.updateBusyStatus(true); //decompile the currently opened resource and save it to the specified file - DiskWriter.replaceFile(saveAll ? MiscUtils.append(outputFile, "-" + decompiler.getDecompilerNameProgrammic() + ".java") : outputFile.getAbsolutePath(), BCV.decompileCurrentlyOpenedClassNode(decompiler), false); + DiskWriter.replaceFile(saveAll ? MiscUtils.append(outputFile, + "-" + decompiler.getDecompilerNameProgrammic() + ".java") : outputFile.getAbsolutePath(), BCV.decompileCurrentlyOpenedClassNode(decompiler), false); //signal to the user that BCV is finished performing that action BytecodeViewer.updateBusyStatus(false); diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceType.java b/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceType.java index 89918667c..441484c50 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceType.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/resources/ResourceType.java @@ -38,18 +38,18 @@ public enum ResourceType ZIP_ARCHIVE(IconResources.zipIcon, "zip"), ANDROID_ARCHIVE(IconResources.androidIcon, "apk", "wapk", "dex", "xapk"), IMAGE_FILE(IconResources.imageIcon, "png", "jpg", "jpeg", "bmp", "wbmp", "gif", "tif", "webp"), - CONFIG_TEXT_FILE(IconResources.configIcon, "properties", "xml", "jsp", "mf", "config", "csv", "yml", "yaml", "ini", "json", "sql", "gradle", "dockerfile", "htaccess", "plugin", "attachprovider", "transportservice", "connector"), + CONFIG_TEXT_FILE(IconResources.configIcon, "properties", "xml", "jsp", "mf", "config", "csv", "yml", "yaml", "ini", + "json", "sql", "gradle", "dockerfile", "htaccess", "plugin", "attachprovider", "transportservice", "connector"), JAVA_FILE(IconResources.javaIcon, "java"), TEXT_FILE(IconResources.textIcon, "txt", "md", "log", "html", "css"), CPP_FILE(IconResources.cplusplusIcon, "c", "cpp", "h"), CSHARP_FILE(IconResources.csharpIcon, "cs"), BAT_FILE(IconResources.batIcon, "bat", "batch"), - SH_FILE(IconResources.shIcon, "sh", "bash"), - ; + SH_FILE(IconResources.shIcon, "sh", "bash"); - public static final Map extensionMap = new HashMap<>(); - public static final Map imageExtensionMap = new HashMap<>(); - public static final Map supportedBCVExtensionMap = new HashMap<>(); + public static final Map EXTENSION_MAP = new HashMap<>(); + public static final Map IMAGE_EXTENSION_MAP = new HashMap<>(); + public static final Map SUPPORTED_BCV_EXTENSION_MAP = new HashMap<>(); private final Icon icon; private final String[] extensions; @@ -60,21 +60,21 @@ public enum ResourceType //add all extensions for (ResourceType t : values()) for (String extension : t.extensions) - extensionMap.put(extension, t); + EXTENSION_MAP.put(extension, t); //add image extensions for (String extension : IMAGE_FILE.extensions) - imageExtensionMap.put(extension, IMAGE_FILE); + IMAGE_EXTENSION_MAP.put(extension, IMAGE_FILE); //add extensions BCV can be opened with for (String extension : CLASS_FILE.extensions) - supportedBCVExtensionMap.put(extension, CLASS_FILE); + SUPPORTED_BCV_EXTENSION_MAP.put(extension, CLASS_FILE); for (String extension : JAVA_ARCHIVE.extensions) - supportedBCVExtensionMap.put(extension, JAVA_ARCHIVE); + SUPPORTED_BCV_EXTENSION_MAP.put(extension, JAVA_ARCHIVE); for (String extension : ZIP_ARCHIVE.extensions) - supportedBCVExtensionMap.put(extension, ZIP_ARCHIVE); + SUPPORTED_BCV_EXTENSION_MAP.put(extension, ZIP_ARCHIVE); for (String extension : ANDROID_ARCHIVE.extensions) - supportedBCVExtensionMap.put(extension, ANDROID_ARCHIVE); + SUPPORTED_BCV_EXTENSION_MAP.put(extension, ANDROID_ARCHIVE); } ResourceType(Icon icon, String... extensions) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/util/JarUtils.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/JarUtils.java index 5f9e64fed..5f9c7c9cf 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/util/JarUtils.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/JarUtils.java @@ -64,7 +64,8 @@ public static void importArchiveA(File jarFile) throws IOException ResourceContainer container = new ResourceContainer(jarFile); Map files = new LinkedHashMap<>(); - try (FileInputStream fis = new FileInputStream(jarFile); ZipInputStream jis = new ZipInputStream(fis)) + try (FileInputStream fis = new FileInputStream(jarFile); + ZipInputStream jis = new ZipInputStream(fis)) { ZipEntry entry; while ((entry = jis.getNextEntry()) != null) @@ -184,7 +185,8 @@ public static void importArchiveB(File jarFile) throws IOException public static List loadClasses(File jarFile) throws IOException { List classes = new ArrayList<>(); - try (FileInputStream fis = new FileInputStream(jarFile); ZipInputStream jis = new ZipInputStream(fis)) + try (FileInputStream fis = new FileInputStream(jarFile); + ZipInputStream jis = new ZipInputStream(fis)) { ZipEntry entry; while ((entry = jis.getNextEntry()) != null) @@ -405,7 +407,8 @@ public static void saveAsJarClassesOnlyToDir(List nodeList, String di */ public static void saveAsJar(List nodeList, String path) { - try (FileOutputStream fos = new FileOutputStream(path); JarOutputStream out = new JarOutputStream(fos)) + try (FileOutputStream fos = new FileOutputStream(path); + JarOutputStream out = new JarOutputStream(fos)) { List noDupe = new ArrayList<>(); for (ClassNode cn : nodeList) diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/util/MiscUtils.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/MiscUtils.java index 992482dc1..d171785f7 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/util/MiscUtils.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/MiscUtils.java @@ -56,8 +56,10 @@ public class MiscUtils public static String randomString(int len) { StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) sb.append(AB.charAt(RND.nextInt(AB.length()))); + return sb.toString(); } @@ -70,9 +72,11 @@ public static String getRandomizedName() { boolean generated = false; String name = ""; + while (!generated) { String randomizedName = MiscUtils.randomString(25); + if (!CREATED_RANDOMIZED_NAMES.contains(randomizedName)) { CREATED_RANDOMIZED_NAMES.add(randomizedName); @@ -80,6 +84,7 @@ public static String getRandomizedName() generated = true; } } + return name; } @@ -87,7 +92,8 @@ public static void printProcess(Process process) throws Exception { //Read out dir output try (InputStream is = process.getInputStream(); - InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) @@ -117,8 +123,10 @@ public static void printProcess(Process process) throws Exception public static String randomStringNum(int len) { StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) sb.append(AN.charAt(RND.nextInt(AN.length()))); + return sb.toString(); } @@ -135,10 +143,12 @@ public static String getUniqueName(String start, String ext) boolean b = true; File f; String m; + while (b) { m = MiscUtils.randomString(32); f = new File(start + m + ext); + if (!f.exists()) { s = start + m; @@ -159,14 +169,17 @@ public static int getClassNumber(String start, String ext) { boolean b = true; int i = 0; + while (b) { File tempF = new File(start + i + ext); + if (!tempF.exists()) b = false; else i++; } + return i; } @@ -186,14 +199,17 @@ public static String extension(String name) public static String append(File file, String extension) { String path = file.getAbsolutePath(); + if (!path.endsWith(extension)) path += extension; + return path; } public static int fileContainersHash(List resourceContainers) { StringBuilder block = new StringBuilder(); + for (ResourceContainer container : resourceContainers) { block.append(container.name); @@ -246,6 +262,7 @@ public static BufferedImage loadImage(BufferedImage defaultImage, byte[] content public static void deduplicateAndTrim(List list, int maxLength) { List temporaryList = new ArrayList<>(); + for (String s : list) if (!s.isEmpty() && !temporaryList.contains(s)) temporaryList.add(s); @@ -265,6 +282,7 @@ public static boolean guessIfBinary(byte[] data) { double ascii = 0; double other = 0; + for (byte b : data) { if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D || (b >= 0x20 && b <= 0x7E)) @@ -272,6 +290,7 @@ public static boolean guessIfBinary(byte[] data) else other++; } + return other != 0 && other / (ascii + other) > 0.25; } @@ -345,9 +364,9 @@ public static byte[] getBytes(InputStream is) throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - byte[] buffer = new byte[1024]; int a; + while ((a = is.read(buffer)) != -1) baos.write(buffer, 0, a); @@ -359,9 +378,11 @@ public static File[] listFiles(File file) { if (file == null) return new File[0]; + File[] list = file.listFiles(); if (list != null) return list; + return new File[0]; } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java index 54c865561..30e688b08 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java @@ -41,11 +41,14 @@ public class NewlineOutputStream extends FilterOutputStream public NewlineOutputStream(OutputStream os) { super(os); + if (newline == null) { String s = Constants.NL; + if (s == null || s.length() <= 0) s = "\n"; + newline = s.getBytes(StandardCharsets.ISO_8859_1); // really us-ascii } } @@ -66,6 +69,7 @@ else if (b == '\n') { out.write(b); } + lastByte = b; } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/util/SyntaxLanguage.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/SyntaxLanguage.java index f962c705b..71c9f46f3 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/util/SyntaxLanguage.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/SyntaxLanguage.java @@ -33,7 +33,37 @@ public enum SyntaxLanguage XML(SyntaxConstants.SYNTAX_STYLE_XML, (n, c) -> n.endsWith(".xml") || c.startsWith(" n.endsWith(".py") || n.endsWith(".python")), RUBY(SyntaxConstants.SYNTAX_STYLE_RUBY, (n, c) -> n.endsWith(".rb") || n.endsWith(".ruby")), - JAVA(SyntaxConstants.SYNTAX_STYLE_JAVA, (n, c) -> n.endsWith(".java")), HTML(SyntaxConstants.SYNTAX_STYLE_HTML, (n, c) -> n.endsWith(".html")), CSS(SyntaxConstants.SYNTAX_STYLE_CSS, (n, c) -> n.endsWith(".css")), PROPERTIES(SyntaxConstants.SYNTAX_STYLE_PROPERTIES_FILE, (n, c) -> n.endsWith(".properties") || n.endsWith(".mf") || n.endsWith(".sf") || n.endsWith(".plugin") || n.endsWith(".attachprovider") || n.endsWith(".transportservice") || n.endsWith(".connector")), PHP(SyntaxConstants.SYNTAX_STYLE_PHP, (n, c) -> n.endsWith(".php") || c.startsWith(" n.endsWith(".js")), BATCH(SyntaxConstants.SYNTAX_STYLE_WINDOWS_BATCH, (n, c) -> n.endsWith(".bat")), SHELL(SyntaxConstants.SYNTAX_STYLE_UNIX_SHELL, (n, c) -> n.endsWith(".sh")), C(SyntaxConstants.SYNTAX_STYLE_C, (n, c) -> n.endsWith(".c") || n.endsWith(".h")), CPP(SyntaxConstants.SYNTAX_STYLE_CPLUSPLUS, (n, c) -> n.endsWith(".cpp") || n.endsWith(".hpp")), SCALA(SyntaxConstants.SYNTAX_STYLE_SCALA, (n, c) -> n.endsWith(".scala")), CLOJURE(SyntaxConstants.SYNTAX_STYLE_CLOJURE, (n, c) -> n.endsWith(".clojure")), GROOVY(SyntaxConstants.SYNTAX_STYLE_GROOVY, (n, c) -> n.endsWith(".groovy") || n.endsWith(".gradle")), LUA(SyntaxConstants.SYNTAX_STYLE_LUA, (n, c) -> n.endsWith(".lua")), SQL(SyntaxConstants.SYNTAX_STYLE_SQL, (n, c) -> n.endsWith(".sql")), JSON(SyntaxConstants.SYNTAX_STYLE_JSON, (n, c) -> n.endsWith(".json")), JSP(SyntaxConstants.SYNTAX_STYLE_JSP, (n, c) -> n.endsWith(".jsp")), YAML(SyntaxConstants.SYNTAX_STYLE_YAML, (n, c) -> n.endsWith(".yml") || n.endsWith(".yaml")), CS(SyntaxConstants.SYNTAX_STYLE_CSHARP, (n, c) -> n.endsWith(".cs")), CSV(SyntaxConstants.SYNTAX_STYLE_CSV, (n, c) -> n.endsWith(".csv")), DOCKER(SyntaxConstants.SYNTAX_STYLE_DOCKERFILE, (n, c) -> n.endsWith(".dockerfile")), DART(SyntaxConstants.SYNTAX_STYLE_DART, (n, c) -> n.endsWith(".dart")), GO(SyntaxConstants.SYNTAX_STYLE_GO, (n, c) -> n.endsWith(".go")), HTACCESS(SyntaxConstants.SYNTAX_STYLE_HTACCESS, (n, c) -> n.endsWith(".htaccess")), INI(SyntaxConstants.SYNTAX_STYLE_INI, (n, c) -> n.endsWith(".ini")), KOTLIN(SyntaxConstants.SYNTAX_STYLE_KOTLIN, (n, c) -> n.endsWith(".kt") || n.endsWith(".kts")), LATEX(SyntaxConstants.SYNTAX_STYLE_LATEX, (n, c) -> n.endsWith(".tex")), MARKDOWN(SyntaxConstants.SYNTAX_STYLE_MARKDOWN, (n, c) -> n.endsWith(".md")), PERL(SyntaxConstants.SYNTAX_STYLE_PERL, (n, c) -> n.endsWith(".pl")), TYPESCRIPT(SyntaxConstants.SYNTAX_STYLE_TYPESCRIPT, (n, c) -> n.endsWith(".ts")), NONE(SyntaxConstants.SYNTAX_STYLE_NONE, (n, c) -> false); + JAVA(SyntaxConstants.SYNTAX_STYLE_JAVA, (n, c) -> n.endsWith(".java")), + HTML(SyntaxConstants.SYNTAX_STYLE_HTML, (n, c) -> n.endsWith(".html")), + CSS(SyntaxConstants.SYNTAX_STYLE_CSS, (n, c) -> n.endsWith(".css")), + PROPERTIES(SyntaxConstants.SYNTAX_STYLE_PROPERTIES_FILE, (n, c) -> n.endsWith(".properties") || n.endsWith(".mf") || n.endsWith(".sf") || n.endsWith(".plugin") || n.endsWith(".attachprovider") || n.endsWith(".transportservice") || n.endsWith(".connector")), + PHP(SyntaxConstants.SYNTAX_STYLE_PHP, (n, c) -> n.endsWith(".php") || c.startsWith(" n.endsWith(".js")), + BATCH(SyntaxConstants.SYNTAX_STYLE_WINDOWS_BATCH, (n, c) -> n.endsWith(".bat")), + SHELL(SyntaxConstants.SYNTAX_STYLE_UNIX_SHELL, (n, c) -> n.endsWith(".sh")), + C(SyntaxConstants.SYNTAX_STYLE_C, (n, c) -> n.endsWith(".c") || n.endsWith(".h")), + CPP(SyntaxConstants.SYNTAX_STYLE_CPLUSPLUS, (n, c) -> n.endsWith(".cpp") || n.endsWith(".hpp")), + SCALA(SyntaxConstants.SYNTAX_STYLE_SCALA, (n, c) -> n.endsWith(".scala")), + CLOJURE(SyntaxConstants.SYNTAX_STYLE_CLOJURE, (n, c) -> n.endsWith(".clojure")), + GROOVY(SyntaxConstants.SYNTAX_STYLE_GROOVY, (n, c) -> n.endsWith(".groovy") || n.endsWith(".gradle")), + LUA(SyntaxConstants.SYNTAX_STYLE_LUA, (n, c) -> n.endsWith(".lua")), + SQL(SyntaxConstants.SYNTAX_STYLE_SQL, (n, c) -> n.endsWith(".sql")), + JSON(SyntaxConstants.SYNTAX_STYLE_JSON, (n, c) -> n.endsWith(".json")), + JSP(SyntaxConstants.SYNTAX_STYLE_JSP, (n, c) -> n.endsWith(".jsp")), + YAML(SyntaxConstants.SYNTAX_STYLE_YAML, (n, c) -> n.endsWith(".yml") || n.endsWith(".yaml")), + CS(SyntaxConstants.SYNTAX_STYLE_CSHARP, (n, c) -> n.endsWith(".cs")), + CSV(SyntaxConstants.SYNTAX_STYLE_CSV, (n, c) -> n.endsWith(".csv")), + DOCKER(SyntaxConstants.SYNTAX_STYLE_DOCKERFILE, (n, c) -> n.endsWith(".dockerfile")), + DART(SyntaxConstants.SYNTAX_STYLE_DART, (n, c) -> n.endsWith(".dart")), + GO(SyntaxConstants.SYNTAX_STYLE_GO, (n, c) -> n.endsWith(".go")), + HTACCESS(SyntaxConstants.SYNTAX_STYLE_HTACCESS, (n, c) -> n.endsWith(".htaccess")), + INI(SyntaxConstants.SYNTAX_STYLE_INI, (n, c) -> n.endsWith(".ini")), + KOTLIN(SyntaxConstants.SYNTAX_STYLE_KOTLIN, (n, c) -> n.endsWith(".kt") || n.endsWith(".kts")), + LATEX(SyntaxConstants.SYNTAX_STYLE_LATEX, (n, c) -> n.endsWith(".tex")), + MARKDOWN(SyntaxConstants.SYNTAX_STYLE_MARKDOWN, (n, c) -> n.endsWith(".md")), + PERL(SyntaxConstants.SYNTAX_STYLE_PERL, (n, c) -> n.endsWith(".pl")), + TYPESCRIPT(SyntaxConstants.SYNTAX_STYLE_TYPESCRIPT, (n, c) -> n.endsWith(".ts")), + NONE(SyntaxConstants.SYNTAX_STYLE_NONE, (n, c) -> false); public static final SyntaxLanguage[] VALUES = values(); @@ -68,20 +98,19 @@ public static SyntaxLanguage detectLanguage(String fileName, String content) for (SyntaxLanguage lang : VALUES) { if (lang.isLanguage(fileName, content)) - { return lang; - } } + return NONE; } public static void setLanguage(RSyntaxTextArea area, String fileName) { String type = FILE_TYPE_UTIL.guessContentType(new File(fileName)); + if (type == null || type.equals(SyntaxConstants.SYNTAX_STYLE_NONE)) - { type = FILE_TYPE_UTIL.guessContentType(area); - } + area.setSyntaxEditingStyle(type); } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/util/WindowStateChangeAdapter.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/WindowStateChangeAdapter.java index 1e380d221..34b80f202 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/util/WindowStateChangeAdapter.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/WindowStateChangeAdapter.java @@ -50,12 +50,8 @@ public void windowStateChanged(WindowEvent evt) }*/ if ((oldState & Frame.MAXIMIZED_BOTH) == 0 && (newState & Frame.MAXIMIZED_BOTH) != 0) - { mainViewerGUI.isMaximized = true; - } else if ((oldState & Frame.MAXIMIZED_BOTH) != 0 && (newState & Frame.MAXIMIZED_BOTH) == 0) - { mainViewerGUI.isMaximized = false; - } } } diff --git a/src/main/java/the/bytecode/club/bytecodeviewer/util/ZipUtils.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/ZipUtils.java index 8f2f767e9..fbc74dc1f 100644 --- a/src/main/java/the/bytecode/club/bytecodeviewer/util/ZipUtils.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/ZipUtils.java @@ -44,12 +44,14 @@ public final class ZipUtils public static void unzipFilesToPath(String jarPath, String destinationDir) throws IOException { String canonicalDestDir = new File(destinationDir).getCanonicalPath(); + if (!canonicalDestDir.endsWith(File.separator)) { canonicalDestDir += File.separator; } File file = new File(jarPath); + try (JarFile jar = new JarFile(file)) { @@ -82,6 +84,7 @@ public static void unzipFilesToPath(String jarPath, String destinationDir) throw } File parent = f.getParentFile(); + if (!parent.exists()) { parent.mkdirs(); @@ -110,6 +113,7 @@ public static void zipFile(File inputFile, File outputZip) { ZipEntry ze = new ZipEntry(inputFile.getName()); zos.putNextEntry(ze); + try (FileInputStream in = new FileInputStream(inputFile)) { int len; @@ -156,14 +160,18 @@ public static void addFileToZip(String path, String srcFile, ZipOutputStream zip { byte[] buf = new byte[1024]; int len; + try (FileInputStream in = new FileInputStream(srcFile)) { ZipEntry entry; + if (ignore == null) entry = new ZipEntry(path + "/" + folder.getName()); else entry = new ZipEntry(path.replace(ignore, "BCV_Krakatau") + "/" + folder.getName()); + zip.putNextEntry(entry); + while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); @@ -194,6 +202,7 @@ public static void addFileToZipAPKTool(String path, String srcFile, ZipOutputStr { byte[] buf = new byte[1024]; int len; + try (FileInputStream in = new FileInputStream(srcFile)) { ZipEntry entry; @@ -216,13 +225,9 @@ public static void addFolderToZip(String path, String srcFolder, ZipOutputStream for (String fileName : Objects.requireNonNull(folder.list())) { if (path.isEmpty()) - { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, ignore); - } else - { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, ignore); - } } } @@ -233,13 +238,9 @@ public static void addFolderToZipAPKTool(String path, String srcFolder, ZipOutpu for (String fileName : Objects.requireNonNull(folder.list())) { if (path.isEmpty()) - { addFileToZipAPKTool(folder.getName(), srcFolder + "/" + fileName, zip); - } else - { addFileToZipAPKTool(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip); - } } } }