+
\ No newline at end of file
diff --git a/license.APL2.txt b/license.APL2.txt
new file mode 100644
index 00000000..a453e432
--- /dev/null
+++ b/license.APL2.txt
@@ -0,0 +1,55 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+
+You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+
+You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+
+If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
\ No newline at end of file
diff --git a/license.LGPL3.txt b/license.LGPL3.txt
new file mode 100644
index 00000000..65c5ca88
--- /dev/null
+++ b/license.LGPL3.txt
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/proguard-build.conf b/proguard-build.conf
new file mode 100644
index 00000000..195b84db
--- /dev/null
+++ b/proguard-build.conf
@@ -0,0 +1,8 @@
+-libraryjars /lib/rt.jar
+-dontoptimize
+-dontobfuscate
+-dontwarn
+-keep class cuchaz.enigma.Main { static void main(java.lang.String[]); }
+-keep class cuchaz.enigma.CommandMain { static void main(java.lang.String[]); }
+-keep class cuchaz.enigma.ConvertMain { static void main(java.lang.String[]); }
+-keep class de.sciss.syntaxpane.** { *; }
\ No newline at end of file
diff --git a/proguard-test.conf b/proguard-test.conf
new file mode 100644
index 00000000..0d3d60e9
--- /dev/null
+++ b/proguard-test.conf
@@ -0,0 +1,9 @@
+-libraryjars /lib/rt.jar
+-overloadaggressively
+-repackageclasses
+-allowaccessmodification
+-dontoptimize
+-dontshrink
+-keepparameternames
+-keepattributes
+-keep class cuchaz.enigma.inputs.Keep
\ No newline at end of file
diff --git a/readme.txt b/readme.txt
new file mode 100644
index 00000000..47277d91
--- /dev/null
+++ b/readme.txt
@@ -0,0 +1,33 @@
+
+Enigma v0.10.4 beta
+A tool for deobfuscation of Java bytecode
+
+Copyright Jeff Martin, 2015
+
+
+LICENSE
+
+Enigma is distributed under the GNU Lesser General Public license version 3
+
+Enigma includes a modified version of Procyon which is distributed under the Apache license version 2. Procyon is copyrighted by Mike Strobel, 2013
+
+Enigma includes unmodified versions of the following libraries which are also released under the Apache license version 2.
+ Guava
+ Javassist
+ JSyntaxPane
+
+Copies of the GNU Lesser General Public license verion 3 and the Apache license v2 have been included in this distribution.
+
+
+USING ENIGMA
+
+Launch the GUI:
+ java -jar enigma.jar
+
+Use Enigma on the command line:
+ java -cp enigma.jar cuchaz.enigma.CommandMain
+
+
+OPEN SOURCE
+
+https://bitbucket.org/cuchaz/enigma
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 00000000..8fa1712a
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'enigma'
\ No newline at end of file
diff --git a/src/cuchaz/enigma/CommandMain.java b/src/cuchaz/enigma/CommandMain.java
new file mode 100644
index 00000000..540cfb95
--- /dev/null
+++ b/src/cuchaz/enigma/CommandMain.java
@@ -0,0 +1,186 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+import java.io.File;
+import java.io.FileReader;
+import java.util.jar.JarFile;
+
+import cuchaz.enigma.Deobfuscator.ProgressListener;
+import cuchaz.enigma.mapping.Mappings;
+import cuchaz.enigma.mapping.MappingsReader;
+
+public class CommandMain {
+
+ public static class ConsoleProgressListener implements ProgressListener {
+
+ private static final int ReportTime = 5000; // 5s
+
+ private int m_totalWork;
+ private long m_startTime;
+ private long m_lastReportTime;
+
+ @Override
+ public void init(int totalWork, String title) {
+ m_totalWork = totalWork;
+ m_startTime = System.currentTimeMillis();
+ m_lastReportTime = m_startTime;
+ System.out.println(title);
+ }
+
+ @Override
+ public void onProgress(int numDone, String message) {
+
+ long now = System.currentTimeMillis();
+ boolean isLastUpdate = numDone == m_totalWork;
+ boolean shouldReport = isLastUpdate || now - m_lastReportTime > ReportTime;
+
+ if (shouldReport) {
+ int percent = numDone*100/m_totalWork;
+ System.out.println(String.format("\tProgress: %3d%%", percent));
+ m_lastReportTime = now;
+ }
+ if (isLastUpdate) {
+ double elapsedSeconds = (now - m_startTime)/1000;
+ System.out.println(String.format("Finished in %.1f seconds", elapsedSeconds));
+ }
+ }
+ }
+
+ public static void main(String[] args)
+ throws Exception {
+
+ try {
+
+ // process the command
+ String command = getArg(args, 0, "command", true);
+ if (command.equalsIgnoreCase("deobfuscate")) {
+ deobfuscate(args);
+ } else if (command.equalsIgnoreCase("decompile")) {
+ decompile(args);
+ } else if (command.equalsIgnoreCase("protectify")) {
+ protectify(args);
+ } else if (command.equalsIgnoreCase("publify")) {
+ publify(args);
+ } else {
+ throw new IllegalArgumentException("Command not recognized: " + command);
+ }
+ } catch (IllegalArgumentException ex) {
+ System.out.println(ex.getMessage());
+ printHelp();
+ }
+ }
+
+ private static void printHelp() {
+ System.out.println(String.format("%s - %s", Constants.Name, Constants.Version));
+ System.out.println("Usage:");
+ System.out.println("\tjava -cp enigma.jar cuchaz.enigma.CommandMain ");
+ System.out.println("\twhere is one of:");
+ System.out.println("\t\tdeobfuscate []");
+ System.out.println("\t\tdecompile []");
+ System.out.println("\t\tprotectify ");
+ }
+
+ private static void decompile(String[] args)
+ throws Exception {
+ File fileJarIn = getReadableFile(getArg(args, 1, "in jar", true));
+ File fileJarOut = getWritableFolder(getArg(args, 2, "out folder", true));
+ File fileMappings = getReadableFile(getArg(args, 3, "mappings file", false));
+ Deobfuscator deobfuscator = getDeobfuscator(fileMappings, new JarFile(fileJarIn));
+ deobfuscator.writeSources(fileJarOut, new ConsoleProgressListener());
+ }
+
+ private static void deobfuscate(String[] args)
+ throws Exception {
+ File fileJarIn = getReadableFile(getArg(args, 1, "in jar", true));
+ File fileJarOut = getWritableFile(getArg(args, 2, "out jar", true));
+ File fileMappings = getReadableFile(getArg(args, 3, "mappings file", false));
+ Deobfuscator deobfuscator = getDeobfuscator(fileMappings, new JarFile(fileJarIn));
+ deobfuscator.writeJar(fileJarOut, new ConsoleProgressListener());
+ }
+
+ private static void protectify(String[] args)
+ throws Exception {
+ File fileJarIn = getReadableFile(getArg(args, 1, "in jar", true));
+ File fileJarOut = getWritableFile(getArg(args, 2, "out jar", true));
+ Deobfuscator deobfuscator = getDeobfuscator(null, new JarFile(fileJarIn));
+ deobfuscator.protectifyJar(fileJarOut, new ConsoleProgressListener());
+ }
+
+ private static void publify(String[] args)
+ throws Exception {
+ File fileJarIn = getReadableFile(getArg(args, 1, "in jar", true));
+ File fileJarOut = getWritableFile(getArg(args, 2, "out jar", true));
+ Deobfuscator deobfuscator = getDeobfuscator(null, new JarFile(fileJarIn));
+ deobfuscator.publifyJar(fileJarOut, new ConsoleProgressListener());
+ }
+
+ private static Deobfuscator getDeobfuscator(File fileMappings, JarFile jar)
+ throws Exception {
+ System.out.println("Reading jar...");
+ Deobfuscator deobfuscator = new Deobfuscator(jar);
+ if (fileMappings != null) {
+ System.out.println("Reading mappings...");
+ Mappings mappings = new MappingsReader().read(new FileReader(fileMappings));
+ deobfuscator.setMappings(mappings);
+ }
+ return deobfuscator;
+ }
+
+ private static String getArg(String[] args, int i, String name, boolean required) {
+ if (i >= args.length) {
+ if (required) {
+ throw new IllegalArgumentException(name + " is required");
+ } else {
+ return null;
+ }
+ }
+ return args[i];
+ }
+
+ private static File getWritableFile(String path) {
+ if (path == null) {
+ return null;
+ }
+ File file = new File(path).getAbsoluteFile();
+ File dir = file.getParentFile();
+ if (dir == null) {
+ throw new IllegalArgumentException("Cannot write to folder: " + dir);
+ }
+ // quick fix to avoid stupid stuff in Gradle code
+ if (!dir.isDirectory()) {
+ dir.mkdirs();
+ }
+ return file;
+ }
+
+ private static File getWritableFolder(String path) {
+ if (path == null) {
+ return null;
+ }
+ File dir = new File(path).getAbsoluteFile();
+ if (!dir.exists()) {
+ throw new IllegalArgumentException("Cannot write to folder: " + dir);
+ }
+ return dir;
+ }
+
+ private static File getReadableFile(String path) {
+ if (path == null) {
+ return null;
+ }
+ File file = new File(path).getAbsoluteFile();
+ if (!file.exists()) {
+ throw new IllegalArgumentException("Cannot find file: " + file.getAbsolutePath());
+ }
+ return file;
+ }
+}
diff --git a/src/cuchaz/enigma/Constants.java b/src/cuchaz/enigma/Constants.java
new file mode 100644
index 00000000..951fa8f3
--- /dev/null
+++ b/src/cuchaz/enigma/Constants.java
@@ -0,0 +1,20 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+public class Constants {
+ public static final String Name = "Enigma";
+ public static final String Version = "0.10.4 beta";
+ public static final String Url = "http://www.cuchazinteractive.com/enigma";
+ public static final int MiB = 1024 * 1024; // 1 mebibyte
+ public static final int KiB = 1024; // 1 kebibyte
+ public static final String NonePackage = "none";
+}
diff --git a/src/cuchaz/enigma/ConvertMain.java b/src/cuchaz/enigma/ConvertMain.java
new file mode 100644
index 00000000..17bd2f80
--- /dev/null
+++ b/src/cuchaz/enigma/ConvertMain.java
@@ -0,0 +1,322 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.jar.JarFile;
+
+import cuchaz.enigma.convert.ClassMatches;
+import cuchaz.enigma.convert.MappingsConverter;
+import cuchaz.enigma.convert.MatchesReader;
+import cuchaz.enigma.convert.MatchesWriter;
+import cuchaz.enigma.convert.MemberMatches;
+import cuchaz.enigma.gui.ClassMatchingGui;
+import cuchaz.enigma.gui.MemberMatchingGui;
+import cuchaz.enigma.mapping.BehaviorEntry;
+import cuchaz.enigma.mapping.ClassEntry;
+import cuchaz.enigma.mapping.ClassMapping;
+import cuchaz.enigma.mapping.FieldEntry;
+import cuchaz.enigma.mapping.FieldMapping;
+import cuchaz.enigma.mapping.MappingParseException;
+import cuchaz.enigma.mapping.Mappings;
+import cuchaz.enigma.mapping.MappingsChecker;
+import cuchaz.enigma.mapping.MappingsReader;
+import cuchaz.enigma.mapping.MappingsWriter;
+import cuchaz.enigma.mapping.MethodMapping;
+
+
+public class ConvertMain {
+
+ public static void main(String[] args)
+ throws IOException, MappingParseException {
+
+ // init files
+ File home = new File(System.getProperty("user.home"));
+ JarFile sourceJar = new JarFile(new File(home, ".minecraft/versions/1.8/1.8.jar"));
+ JarFile destJar = new JarFile(new File(home, ".minecraft/versions/1.8.3/1.8.3.jar"));
+ File inMappingsFile = new File("../Enigma Mappings/1.8.mappings");
+ File outMappingsFile = new File("../Enigma Mappings/1.8.3.mappings");
+ Mappings mappings = new MappingsReader().read(new FileReader(inMappingsFile));
+ File classMatchesFile = new File(inMappingsFile.getName() + ".class.matches");
+ File fieldMatchesFile = new File(inMappingsFile.getName() + ".field.matches");
+ File methodMatchesFile = new File(inMappingsFile.getName() + ".method.matches");
+
+ // match classes
+ //computeClassMatches(classMatchesFile, sourceJar, destJar, mappings);
+ //editClasssMatches(classMatchesFile, sourceJar, destJar, mappings);
+ //convertMappings(outMappingsFile, sourceJar, destJar, mappings, classMatchesFile);
+
+ // match fields
+ //computeFieldMatches(fieldMatchesFile, destJar, outMappingsFile, classMatchesFile);
+ //editFieldMatches(sourceJar, destJar, outMappingsFile, mappings, classMatchesFile, fieldMatchesFile);
+ //convertMappings(outMappingsFile, sourceJar, destJar, mappings, classMatchesFile, fieldMatchesFile);
+
+ // match methods/constructors
+ //computeMethodMatches(methodMatchesFile, destJar, outMappingsFile, classMatchesFile);
+ //editMethodMatches(sourceJar, destJar, outMappingsFile, mappings, classMatchesFile, methodMatchesFile);
+ convertMappings(outMappingsFile, sourceJar, destJar, mappings, classMatchesFile, fieldMatchesFile, methodMatchesFile);
+ }
+
+ private static void computeClassMatches(File classMatchesFile, JarFile sourceJar, JarFile destJar, Mappings mappings)
+ throws IOException {
+ ClassMatches classMatches = MappingsConverter.computeClassMatches(sourceJar, destJar, mappings);
+ MatchesWriter.writeClasses(classMatches, classMatchesFile);
+ System.out.println("Wrote:\n\t" + classMatchesFile.getAbsolutePath());
+ }
+
+ private static void editClasssMatches(final File classMatchesFile, JarFile sourceJar, JarFile destJar, Mappings mappings)
+ throws IOException {
+ System.out.println("Reading class matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ Deobfuscators deobfuscators = new Deobfuscators(sourceJar, destJar);
+ deobfuscators.source.setMappings(mappings);
+ System.out.println("Starting GUI...");
+ new ClassMatchingGui(classMatches, deobfuscators.source, deobfuscators.dest).setSaveListener(new ClassMatchingGui.SaveListener() {
+ @Override
+ public void save(ClassMatches matches) {
+ try {
+ MatchesWriter.writeClasses(matches, classMatchesFile);
+ } catch (IOException ex) {
+ throw new Error(ex);
+ }
+ }
+ });
+ }
+
+ private static void convertMappings(File outMappingsFile, JarFile sourceJar, JarFile destJar, Mappings mappings, File classMatchesFile)
+ throws IOException {
+ System.out.println("Reading class matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ Deobfuscators deobfuscators = new Deobfuscators(sourceJar, destJar);
+ deobfuscators.source.setMappings(mappings);
+
+ Mappings newMappings = MappingsConverter.newMappings(classMatches, mappings, deobfuscators.source, deobfuscators.dest);
+
+ try (FileWriter out = new FileWriter(outMappingsFile)) {
+ new MappingsWriter().write(out, newMappings);
+ }
+ System.out.println("Write converted mappings to: " + outMappingsFile.getAbsolutePath());
+ }
+
+ private static void computeFieldMatches(File memberMatchesFile, JarFile destJar, File destMappingsFile, File classMatchesFile)
+ throws IOException, MappingParseException {
+
+ System.out.println("Reading class matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ System.out.println("Reading mappings...");
+ Mappings destMappings = new MappingsReader().read(new FileReader(destMappingsFile));
+ System.out.println("Indexing dest jar...");
+ Deobfuscator destDeobfuscator = new Deobfuscator(destJar);
+
+ System.out.println("Writing matches...");
+
+ // get the matched and unmatched mappings
+ MemberMatches fieldMatches = MappingsConverter.computeMemberMatches(
+ destDeobfuscator,
+ destMappings,
+ classMatches,
+ MappingsConverter.getFieldDoer()
+ );
+
+ MatchesWriter.writeMembers(fieldMatches, memberMatchesFile);
+ System.out.println("Wrote:\n\t" + memberMatchesFile.getAbsolutePath());
+ }
+
+ private static void editFieldMatches(JarFile sourceJar, JarFile destJar, File destMappingsFile, Mappings sourceMappings, File classMatchesFile, final File fieldMatchesFile)
+ throws IOException, MappingParseException {
+
+ System.out.println("Reading matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ MemberMatches fieldMatches = MatchesReader.readMembers(fieldMatchesFile);
+
+ // prep deobfuscators
+ Deobfuscators deobfuscators = new Deobfuscators(sourceJar, destJar);
+ deobfuscators.source.setMappings(sourceMappings);
+ Mappings destMappings = new MappingsReader().read(new FileReader(destMappingsFile));
+ MappingsChecker checker = new MappingsChecker(deobfuscators.dest.getJarIndex());
+ checker.dropBrokenMappings(destMappings);
+ deobfuscators.dest.setMappings(destMappings);
+
+ new MemberMatchingGui(classMatches, fieldMatches, deobfuscators.source, deobfuscators.dest).setSaveListener(new MemberMatchingGui.SaveListener() {
+ @Override
+ public void save(MemberMatches matches) {
+ try {
+ MatchesWriter.writeMembers(matches, fieldMatchesFile);
+ } catch (IOException ex) {
+ throw new Error(ex);
+ }
+ }
+ });
+ }
+
+ private static void convertMappings(File outMappingsFile, JarFile sourceJar, JarFile destJar, Mappings mappings, File classMatchesFile, File fieldMatchesFile)
+ throws IOException {
+
+ System.out.println("Reading matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ MemberMatches fieldMatches = MatchesReader.readMembers(fieldMatchesFile);
+
+ Deobfuscators deobfuscators = new Deobfuscators(sourceJar, destJar);
+ deobfuscators.source.setMappings(mappings);
+
+ // apply matches
+ Mappings newMappings = MappingsConverter.newMappings(classMatches, mappings, deobfuscators.source, deobfuscators.dest);
+ MappingsConverter.applyMemberMatches(newMappings, classMatches, fieldMatches, MappingsConverter.getFieldDoer());
+
+ // write out the converted mappings
+ try (FileWriter out = new FileWriter(outMappingsFile)) {
+ new MappingsWriter().write(out, newMappings);
+ }
+ System.out.println("Wrote converted mappings to:\n\t" + outMappingsFile.getAbsolutePath());
+ }
+
+
+ private static void computeMethodMatches(File methodMatchesFile, JarFile destJar, File destMappingsFile, File classMatchesFile)
+ throws IOException, MappingParseException {
+
+ System.out.println("Reading class matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ System.out.println("Reading mappings...");
+ Mappings destMappings = new MappingsReader().read(new FileReader(destMappingsFile));
+ System.out.println("Indexing dest jar...");
+ Deobfuscator destDeobfuscator = new Deobfuscator(destJar);
+
+ System.out.println("Writing method matches...");
+
+ // get the matched and unmatched mappings
+ MemberMatches methodMatches = MappingsConverter.computeMemberMatches(
+ destDeobfuscator,
+ destMappings,
+ classMatches,
+ MappingsConverter.getMethodDoer()
+ );
+
+ MatchesWriter.writeMembers(methodMatches, methodMatchesFile);
+ System.out.println("Wrote:\n\t" + methodMatchesFile.getAbsolutePath());
+ }
+
+ private static void editMethodMatches(JarFile sourceJar, JarFile destJar, File destMappingsFile, Mappings sourceMappings, File classMatchesFile, final File methodMatchesFile)
+ throws IOException, MappingParseException {
+
+ System.out.println("Reading matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ MemberMatches methodMatches = MatchesReader.readMembers(methodMatchesFile);
+
+ // prep deobfuscators
+ Deobfuscators deobfuscators = new Deobfuscators(sourceJar, destJar);
+ deobfuscators.source.setMappings(sourceMappings);
+ Mappings destMappings = new MappingsReader().read(new FileReader(destMappingsFile));
+ MappingsChecker checker = new MappingsChecker(deobfuscators.dest.getJarIndex());
+ checker.dropBrokenMappings(destMappings);
+ deobfuscators.dest.setMappings(destMappings);
+
+ new MemberMatchingGui(classMatches, methodMatches, deobfuscators.source, deobfuscators.dest).setSaveListener(new MemberMatchingGui.SaveListener() {
+ @Override
+ public void save(MemberMatches matches) {
+ try {
+ MatchesWriter.writeMembers(matches, methodMatchesFile);
+ } catch (IOException ex) {
+ throw new Error(ex);
+ }
+ }
+ });
+ }
+
+ private static void convertMappings(File outMappingsFile, JarFile sourceJar, JarFile destJar, Mappings mappings, File classMatchesFile, File fieldMatchesFile, File methodMatchesFile)
+ throws IOException {
+
+ System.out.println("Reading matches...");
+ ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile);
+ MemberMatches fieldMatches = MatchesReader.readMembers(fieldMatchesFile);
+ MemberMatches methodMatches = MatchesReader.readMembers(methodMatchesFile);
+
+ Deobfuscators deobfuscators = new Deobfuscators(sourceJar, destJar);
+ deobfuscators.source.setMappings(mappings);
+
+ // apply matches
+ Mappings newMappings = MappingsConverter.newMappings(classMatches, mappings, deobfuscators.source, deobfuscators.dest);
+ MappingsConverter.applyMemberMatches(newMappings, classMatches, fieldMatches, MappingsConverter.getFieldDoer());
+ MappingsConverter.applyMemberMatches(newMappings, classMatches, methodMatches, MappingsConverter.getMethodDoer());
+
+ // check the final mappings
+ MappingsChecker checker = new MappingsChecker(deobfuscators.dest.getJarIndex());
+ checker.dropBrokenMappings(newMappings);
+
+ for (java.util.Map.Entry mapping : checker.getDroppedClassMappings().entrySet()) {
+ System.out.println("WARNING: Broken class entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ")");
+ }
+ for (java.util.Map.Entry mapping : checker.getDroppedInnerClassMappings().entrySet()) {
+ System.out.println("WARNING: Broken inner class entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ")");
+ }
+ for (java.util.Map.Entry mapping : checker.getDroppedFieldMappings().entrySet()) {
+ System.out.println("WARNING: Broken field entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ")");
+ }
+ for (java.util.Map.Entry mapping : checker.getDroppedMethodMappings().entrySet()) {
+ System.out.println("WARNING: Broken behavior entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ")");
+ }
+
+ // write out the converted mappings
+ try (FileWriter out = new FileWriter(outMappingsFile)) {
+ new MappingsWriter().write(out, newMappings);
+ }
+ System.out.println("Wrote converted mappings to:\n\t" + outMappingsFile.getAbsolutePath());
+ }
+
+ private static class Deobfuscators {
+
+ public Deobfuscator source;
+ public Deobfuscator dest;
+
+ public Deobfuscators(JarFile sourceJar, JarFile destJar) {
+ System.out.println("Indexing source jar...");
+ IndexerThread sourceIndexer = new IndexerThread(sourceJar);
+ sourceIndexer.start();
+ System.out.println("Indexing dest jar...");
+ IndexerThread destIndexer = new IndexerThread(destJar);
+ destIndexer.start();
+ sourceIndexer.joinOrBail();
+ destIndexer.joinOrBail();
+ source = sourceIndexer.deobfuscator;
+ dest = destIndexer.deobfuscator;
+ }
+ }
+
+ private static class IndexerThread extends Thread {
+
+ private JarFile m_jarFile;
+ public Deobfuscator deobfuscator;
+
+ public IndexerThread(JarFile jarFile) {
+ m_jarFile = jarFile;
+ deobfuscator = null;
+ }
+
+ public void joinOrBail() {
+ try {
+ join();
+ } catch (InterruptedException ex) {
+ throw new Error(ex);
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ deobfuscator = new Deobfuscator(m_jarFile);
+ } catch (IOException ex) {
+ throw new Error(ex);
+ }
+ }
+ }
+}
diff --git a/src/cuchaz/enigma/Deobfuscator.java b/src/cuchaz/enigma/Deobfuscator.java
new file mode 100644
index 00000000..08a974aa
--- /dev/null
+++ b/src/cuchaz/enigma/Deobfuscator.java
@@ -0,0 +1,548 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.JarOutputStream;
+
+import javassist.CtClass;
+import javassist.bytecode.Descriptor;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.strobel.assembler.metadata.MetadataSystem;
+import com.strobel.assembler.metadata.TypeDefinition;
+import com.strobel.assembler.metadata.TypeReference;
+import com.strobel.decompiler.DecompilerContext;
+import com.strobel.decompiler.DecompilerSettings;
+import com.strobel.decompiler.PlainTextOutput;
+import com.strobel.decompiler.languages.java.JavaOutputVisitor;
+import com.strobel.decompiler.languages.java.ast.AstBuilder;
+import com.strobel.decompiler.languages.java.ast.CompilationUnit;
+import com.strobel.decompiler.languages.java.ast.InsertParenthesesVisitor;
+
+import cuchaz.enigma.analysis.EntryReference;
+import cuchaz.enigma.analysis.JarClassIterator;
+import cuchaz.enigma.analysis.JarIndex;
+import cuchaz.enigma.analysis.SourceIndex;
+import cuchaz.enigma.analysis.SourceIndexVisitor;
+import cuchaz.enigma.analysis.Token;
+import cuchaz.enigma.bytecode.ClassProtectifier;
+import cuchaz.enigma.bytecode.ClassPublifier;
+import cuchaz.enigma.mapping.ArgumentEntry;
+import cuchaz.enigma.mapping.BehaviorEntry;
+import cuchaz.enigma.mapping.ClassEntry;
+import cuchaz.enigma.mapping.ClassMapping;
+import cuchaz.enigma.mapping.ConstructorEntry;
+import cuchaz.enigma.mapping.Entry;
+import cuchaz.enigma.mapping.FieldEntry;
+import cuchaz.enigma.mapping.FieldMapping;
+import cuchaz.enigma.mapping.Mappings;
+import cuchaz.enigma.mapping.MappingsChecker;
+import cuchaz.enigma.mapping.MappingsRenamer;
+import cuchaz.enigma.mapping.MethodEntry;
+import cuchaz.enigma.mapping.MethodMapping;
+import cuchaz.enigma.mapping.TranslationDirection;
+import cuchaz.enigma.mapping.Translator;
+
+public class Deobfuscator {
+
+ public interface ProgressListener {
+ void init(int totalWork, String title);
+ void onProgress(int numDone, String message);
+ }
+
+ private JarFile m_jar;
+ private DecompilerSettings m_settings;
+ private JarIndex m_jarIndex;
+ private Mappings m_mappings;
+ private MappingsRenamer m_renamer;
+ private Map m_translatorCache;
+
+ public Deobfuscator(JarFile jar) throws IOException {
+ m_jar = jar;
+
+ // build the jar index
+ m_jarIndex = new JarIndex();
+ m_jarIndex.indexJar(m_jar, true);
+
+ // config the decompiler
+ m_settings = DecompilerSettings.javaDefaults();
+ m_settings.setMergeVariables(true);
+ m_settings.setForceExplicitImports(true);
+ m_settings.setForceExplicitTypeArguments(true);
+ m_settings.setShowDebugLineNumbers(true);
+ // DEBUG
+ //m_settings.setShowSyntheticMembers(true);
+
+ // init defaults
+ m_translatorCache = Maps.newTreeMap();
+
+ // init mappings
+ setMappings(new Mappings());
+ }
+
+ public JarFile getJar() {
+ return m_jar;
+ }
+
+ public String getJarName() {
+ return m_jar.getName();
+ }
+
+ public JarIndex getJarIndex() {
+ return m_jarIndex;
+ }
+
+ public Mappings getMappings() {
+ return m_mappings;
+ }
+
+ public void setMappings(Mappings val) {
+ setMappings(val, true);
+ }
+
+ public void setMappings(Mappings val, boolean warnAboutDrops) {
+ if (val == null) {
+ val = new Mappings();
+ }
+
+ // drop mappings that don't match the jar
+ MappingsChecker checker = new MappingsChecker(m_jarIndex);
+ checker.dropBrokenMappings(val);
+ if (warnAboutDrops) {
+ for (java.util.Map.Entry mapping : checker.getDroppedClassMappings().entrySet()) {
+ System.out.println("WARNING: Couldn't find class entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ") in jar. Mapping was dropped.");
+ }
+ for (java.util.Map.Entry mapping : checker.getDroppedInnerClassMappings().entrySet()) {
+ System.out.println("WARNING: Couldn't find inner class entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ") in jar. Mapping was dropped.");
+ }
+ for (java.util.Map.Entry mapping : checker.getDroppedFieldMappings().entrySet()) {
+ System.out.println("WARNING: Couldn't find field entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ") in jar. Mapping was dropped.");
+ }
+ for (java.util.Map.Entry mapping : checker.getDroppedMethodMappings().entrySet()) {
+ System.out.println("WARNING: Couldn't find behavior entry " + mapping.getKey() + " (" + mapping.getValue().getDeobfName() + ") in jar. Mapping was dropped.");
+ }
+ }
+
+ // check for related method inconsistencies
+ if (checker.getRelatedMethodChecker().hasProblems()) {
+ throw new Error("Related methods are inconsistent! Need to fix the mappings manually.\n" + checker.getRelatedMethodChecker().getReport());
+ }
+
+ m_mappings = val;
+ m_renamer = new MappingsRenamer(m_jarIndex, val);
+ m_translatorCache.clear();
+ }
+
+ public Translator getTranslator(TranslationDirection direction) {
+ Translator translator = m_translatorCache.get(direction);
+ if (translator == null) {
+ translator = m_mappings.getTranslator(direction, m_jarIndex.getTranslationIndex());
+ m_translatorCache.put(direction, translator);
+ }
+ return translator;
+ }
+
+ public void getSeparatedClasses(List obfClasses, List deobfClasses) {
+ for (ClassEntry obfClassEntry : m_jarIndex.getObfClassEntries()) {
+ // skip inner classes
+ if (obfClassEntry.isInnerClass()) {
+ continue;
+ }
+
+ // separate the classes
+ ClassEntry deobfClassEntry = deobfuscateEntry(obfClassEntry);
+ if (!deobfClassEntry.equals(obfClassEntry)) {
+ // if the class has a mapping, clearly it's deobfuscated
+ deobfClasses.add(deobfClassEntry);
+ } else if (!obfClassEntry.getPackageName().equals(Constants.NonePackage)) {
+ // also call it deobufscated if it's not in the none package
+ deobfClasses.add(obfClassEntry);
+ } else {
+ // otherwise, assume it's still obfuscated
+ obfClasses.add(obfClassEntry);
+ }
+ }
+ }
+
+ public CompilationUnit getSourceTree(String className) {
+
+ // we don't know if this class name is obfuscated or deobfuscated
+ // we need to tell the decompiler the deobfuscated name so it doesn't get freaked out
+ // the decompiler only sees classes after deobfuscation, so we need to load it by the deobfuscated name if there is one
+
+ // first, assume class name is deobf
+ String deobfClassName = className;
+
+ // if it wasn't actually deobf, then we can find a mapping for it and get the deobf name
+ ClassMapping classMapping = m_mappings.getClassByObf(className);
+ if (classMapping != null && classMapping.getDeobfName() != null) {
+ deobfClassName = classMapping.getDeobfName();
+ }
+
+ // set the type loader
+ TranslatingTypeLoader loader = new TranslatingTypeLoader(
+ m_jar,
+ m_jarIndex,
+ getTranslator(TranslationDirection.Obfuscating),
+ getTranslator(TranslationDirection.Deobfuscating)
+ );
+ m_settings.setTypeLoader(loader);
+
+ // see if procyon can find the type
+ TypeReference type = new MetadataSystem(loader).lookupType(deobfClassName);
+ if (type == null) {
+ throw new Error(String.format("Unable to find type: %s (deobf: %s)\nTried class names: %s",
+ className, deobfClassName, loader.getClassNamesToTry(deobfClassName)
+ ));
+ }
+ TypeDefinition resolvedType = type.resolve();
+
+ // decompile it!
+ DecompilerContext context = new DecompilerContext();
+ context.setCurrentType(resolvedType);
+ context.setSettings(m_settings);
+ AstBuilder builder = new AstBuilder(context);
+ builder.addType(resolvedType);
+ builder.runTransformations(null);
+ return builder.getCompilationUnit();
+ }
+
+ public SourceIndex getSourceIndex(CompilationUnit sourceTree, String source) {
+ return getSourceIndex(sourceTree, source, null);
+ }
+
+ public SourceIndex getSourceIndex(CompilationUnit sourceTree, String source, Boolean ignoreBadTokens) {
+
+ // build the source index
+ SourceIndex index;
+ if (ignoreBadTokens != null) {
+ index = new SourceIndex(source, ignoreBadTokens);
+ } else {
+ index = new SourceIndex(source);
+ }
+ sourceTree.acceptVisitor(new SourceIndexVisitor(), index);
+
+ // DEBUG
+ // sourceTree.acceptVisitor( new TreeDumpVisitor( new File( "tree.txt" ) ), null );
+
+ // resolve all the classes in the source references
+ for (Token token : index.referenceTokens()) {
+ EntryReference deobfReference = index.getDeobfReference(token);
+
+ // get the obfuscated entry
+ Entry obfEntry = obfuscateEntry(deobfReference.entry);
+
+ // try to resolve the class
+ ClassEntry resolvedObfClassEntry = m_jarIndex.getTranslationIndex().resolveEntryClass(obfEntry);
+ if (resolvedObfClassEntry != null && !resolvedObfClassEntry.equals(obfEntry.getClassEntry())) {
+ // change the class of the entry
+ obfEntry = obfEntry.cloneToNewClass(resolvedObfClassEntry);
+
+ // save the new deobfuscated reference
+ deobfReference.entry = deobfuscateEntry(obfEntry);
+ index.replaceDeobfReference(token, deobfReference);
+ }
+
+ // DEBUG
+ // System.out.println( token + " -> " + reference + " -> " + index.getReferenceToken( reference ) );
+ }
+
+ return index;
+ }
+
+ public String getSource(CompilationUnit sourceTree) {
+ // render the AST into source
+ StringWriter buf = new StringWriter();
+ sourceTree.acceptVisitor(new InsertParenthesesVisitor(), null);
+ sourceTree.acceptVisitor(new JavaOutputVisitor(new PlainTextOutput(buf), m_settings), null);
+ return buf.toString();
+ }
+
+ public void writeSources(File dirOut, ProgressListener progress) throws IOException {
+ // get the classes to decompile
+ Set classEntries = Sets.newHashSet();
+ for (ClassEntry obfClassEntry : m_jarIndex.getObfClassEntries()) {
+ // skip inner classes
+ if (obfClassEntry.isInnerClass()) {
+ continue;
+ }
+
+ classEntries.add(obfClassEntry);
+ }
+
+ if (progress != null) {
+ progress.init(classEntries.size(), "Decompiling classes...");
+ }
+
+ // DEOBFUSCATE ALL THE THINGS!! @_@
+ int i = 0;
+ for (ClassEntry obfClassEntry : classEntries) {
+ ClassEntry deobfClassEntry = deobfuscateEntry(new ClassEntry(obfClassEntry));
+ if (progress != null) {
+ progress.onProgress(i++, deobfClassEntry.toString());
+ }
+
+ try {
+ // get the source
+ String source = getSource(getSourceTree(obfClassEntry.getName()));
+
+ // write the file
+ File file = new File(dirOut, deobfClassEntry.getName().replace('.', '/') + ".java");
+ file.getParentFile().mkdirs();
+ try (FileWriter out = new FileWriter(file)) {
+ out.write(source);
+ }
+ } catch (Throwable t) {
+ throw new Error("Unable to deobfuscate class " + deobfClassEntry.toString() + " (" + obfClassEntry.toString() + ")", t);
+ }
+ }
+ if (progress != null) {
+ progress.onProgress(i, "Done!");
+ }
+ }
+
+ public void writeJar(File out, ProgressListener progress) {
+ final TranslatingTypeLoader loader = new TranslatingTypeLoader(
+ m_jar,
+ m_jarIndex,
+ getTranslator(TranslationDirection.Obfuscating),
+ getTranslator(TranslationDirection.Deobfuscating)
+ );
+ transformJar(out, progress, new ClassTransformer() {
+
+ @Override
+ public CtClass transform(CtClass c) throws Exception {
+ return loader.transformClass(c);
+ }
+ });
+ }
+
+ public void protectifyJar(File out, ProgressListener progress) {
+ transformJar(out, progress, new ClassTransformer() {
+
+ @Override
+ public CtClass transform(CtClass c) throws Exception {
+ return ClassProtectifier.protectify(c);
+ }
+ });
+ }
+
+ public void publifyJar(File out, ProgressListener progress) {
+ transformJar(out, progress, new ClassTransformer() {
+
+ @Override
+ public CtClass transform(CtClass c) throws Exception {
+ return ClassPublifier.publify(c);
+ }
+ });
+ }
+
+ private interface ClassTransformer {
+ public CtClass transform(CtClass c) throws Exception;
+ }
+ private void transformJar(File out, ProgressListener progress, ClassTransformer transformer) {
+ try (JarOutputStream outJar = new JarOutputStream(new FileOutputStream(out))) {
+ if (progress != null) {
+ progress.init(JarClassIterator.getClassEntries(m_jar).size(), "Transforming classes...");
+ }
+
+ int i = 0;
+ for (CtClass c : JarClassIterator.classes(m_jar)) {
+ if (progress != null) {
+ progress.onProgress(i++, c.getName());
+ }
+
+ try {
+ c = transformer.transform(c);
+ outJar.putNextEntry(new JarEntry(c.getName().replace('.', '/') + ".class"));
+ outJar.write(c.toBytecode());
+ outJar.closeEntry();
+ } catch (Throwable t) {
+ throw new Error("Unable to transform class " + c.getName(), t);
+ }
+ }
+ if (progress != null) {
+ progress.onProgress(i, "Done!");
+ }
+
+ outJar.close();
+ } catch (IOException ex) {
+ throw new Error("Unable to write to Jar file!");
+ }
+ }
+
+ public T obfuscateEntry(T deobfEntry) {
+ if (deobfEntry == null) {
+ return null;
+ }
+ return getTranslator(TranslationDirection.Obfuscating).translateEntry(deobfEntry);
+ }
+
+ public T deobfuscateEntry(T obfEntry) {
+ if (obfEntry == null) {
+ return null;
+ }
+ return getTranslator(TranslationDirection.Deobfuscating).translateEntry(obfEntry);
+ }
+
+ public EntryReference obfuscateReference(EntryReference deobfReference) {
+ if (deobfReference == null) {
+ return null;
+ }
+ return new EntryReference(
+ obfuscateEntry(deobfReference.entry),
+ obfuscateEntry(deobfReference.context),
+ deobfReference
+ );
+ }
+
+ public EntryReference deobfuscateReference(EntryReference obfReference) {
+ if (obfReference == null) {
+ return null;
+ }
+ return new EntryReference(
+ deobfuscateEntry(obfReference.entry),
+ deobfuscateEntry(obfReference.context),
+ obfReference
+ );
+ }
+
+ public boolean isObfuscatedIdentifier(Entry obfEntry) {
+
+ if (obfEntry instanceof MethodEntry) {
+
+ // HACKHACK: Object methods are not obfuscated identifiers
+ MethodEntry obfMethodEntry = (MethodEntry)obfEntry;
+ String name = obfMethodEntry.getName();
+ String sig = obfMethodEntry.getSignature().toString();
+ if (name.equals("clone") && sig.equals("()Ljava/lang/Object;")) {
+ return false;
+ } else if (name.equals("equals") && sig.equals("(Ljava/lang/Object;)Z")) {
+ return false;
+ } else if (name.equals("finalize") && sig.equals("()V")) {
+ return false;
+ } else if (name.equals("getClass") && sig.equals("()Ljava/lang/Class;")) {
+ return false;
+ } else if (name.equals("hashCode") && sig.equals("()I")) {
+ return false;
+ } else if (name.equals("notify") && sig.equals("()V")) {
+ return false;
+ } else if (name.equals("notifyAll") && sig.equals("()V")) {
+ return false;
+ } else if (name.equals("toString") && sig.equals("()Ljava/lang/String;")) {
+ return false;
+ } else if (name.equals("wait") && sig.equals("()V")) {
+ return false;
+ } else if (name.equals("wait") && sig.equals("(J)V")) {
+ return false;
+ } else if (name.equals("wait") && sig.equals("(JI)V")) {
+ return false;
+ }
+ }
+
+ return m_jarIndex.containsObfEntry(obfEntry);
+ }
+
+ public boolean isRenameable(EntryReference obfReference) {
+ return obfReference.isNamed() && isObfuscatedIdentifier(obfReference.getNameableEntry());
+ }
+
+ // NOTE: these methods are a bit messy... oh well
+
+ public boolean hasDeobfuscatedName(Entry obfEntry) {
+ Translator translator = getTranslator(TranslationDirection.Deobfuscating);
+ if (obfEntry instanceof ClassEntry) {
+ ClassEntry obfClass = (ClassEntry)obfEntry;
+ List mappingChain = m_mappings.getClassMappingChain(obfClass);
+ ClassMapping classMapping = mappingChain.get(mappingChain.size() - 1);
+ return classMapping != null && classMapping.getDeobfName() != null;
+ } else if (obfEntry instanceof FieldEntry) {
+ return translator.translate((FieldEntry)obfEntry) != null;
+ } else if (obfEntry instanceof MethodEntry) {
+ return translator.translate((MethodEntry)obfEntry) != null;
+ } else if (obfEntry instanceof ConstructorEntry) {
+ // constructors have no names
+ return false;
+ } else if (obfEntry instanceof ArgumentEntry) {
+ return translator.translate((ArgumentEntry)obfEntry) != null;
+ } else {
+ throw new Error("Unknown entry type: " + obfEntry.getClass().getName());
+ }
+ }
+
+ public void rename(Entry obfEntry, String newName) {
+ if (obfEntry instanceof ClassEntry) {
+ m_renamer.setClassName((ClassEntry)obfEntry, Descriptor.toJvmName(newName));
+ } else if (obfEntry instanceof FieldEntry) {
+ m_renamer.setFieldName((FieldEntry)obfEntry, newName);
+ } else if (obfEntry instanceof MethodEntry) {
+ m_renamer.setMethodTreeName((MethodEntry)obfEntry, newName);
+ } else if (obfEntry instanceof ConstructorEntry) {
+ throw new IllegalArgumentException("Cannot rename constructors");
+ } else if (obfEntry instanceof ArgumentEntry) {
+ m_renamer.setArgumentName((ArgumentEntry)obfEntry, newName);
+ } else {
+ throw new Error("Unknown entry type: " + obfEntry.getClass().getName());
+ }
+
+ // clear caches
+ m_translatorCache.clear();
+ }
+
+ public void removeMapping(Entry obfEntry) {
+ if (obfEntry instanceof ClassEntry) {
+ m_renamer.removeClassMapping((ClassEntry)obfEntry);
+ } else if (obfEntry instanceof FieldEntry) {
+ m_renamer.removeFieldMapping((FieldEntry)obfEntry);
+ } else if (obfEntry instanceof MethodEntry) {
+ m_renamer.removeMethodTreeMapping((MethodEntry)obfEntry);
+ } else if (obfEntry instanceof ConstructorEntry) {
+ throw new IllegalArgumentException("Cannot rename constructors");
+ } else if (obfEntry instanceof ArgumentEntry) {
+ m_renamer.removeArgumentMapping((ArgumentEntry)obfEntry);
+ } else {
+ throw new Error("Unknown entry type: " + obfEntry);
+ }
+
+ // clear caches
+ m_translatorCache.clear();
+ }
+
+ public void markAsDeobfuscated(Entry obfEntry) {
+ if (obfEntry instanceof ClassEntry) {
+ m_renamer.markClassAsDeobfuscated((ClassEntry)obfEntry);
+ } else if (obfEntry instanceof FieldEntry) {
+ m_renamer.markFieldAsDeobfuscated((FieldEntry)obfEntry);
+ } else if (obfEntry instanceof MethodEntry) {
+ m_renamer.markMethodTreeAsDeobfuscated((MethodEntry)obfEntry);
+ } else if (obfEntry instanceof ConstructorEntry) {
+ throw new IllegalArgumentException("Cannot rename constructors");
+ } else if (obfEntry instanceof ArgumentEntry) {
+ m_renamer.markArgumentAsDeobfuscated((ArgumentEntry)obfEntry);
+ } else {
+ throw new Error("Unknown entry type: " + obfEntry);
+ }
+
+ // clear caches
+ m_translatorCache.clear();
+ }
+}
diff --git a/src/cuchaz/enigma/ExceptionIgnorer.java b/src/cuchaz/enigma/ExceptionIgnorer.java
new file mode 100644
index 00000000..d8726d13
--- /dev/null
+++ b/src/cuchaz/enigma/ExceptionIgnorer.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+public class ExceptionIgnorer {
+
+ public static boolean shouldIgnore(Throwable t) {
+
+ // is this that pesky concurrent access bug in the highlight painter system?
+ // (ancient ui code is ancient)
+ if (t instanceof ArrayIndexOutOfBoundsException) {
+ StackTraceElement[] stackTrace = t.getStackTrace();
+ if (stackTrace.length > 1) {
+
+ // does this stack frame match javax.swing.text.DefaultHighlighter.paint*() ?
+ StackTraceElement frame = stackTrace[1];
+ if (frame.getClassName().equals("javax.swing.text.DefaultHighlighter") && frame.getMethodName().startsWith("paint")) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/src/cuchaz/enigma/Main.java b/src/cuchaz/enigma/Main.java
new file mode 100644
index 00000000..4842a795
--- /dev/null
+++ b/src/cuchaz/enigma/Main.java
@@ -0,0 +1,51 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+import java.io.File;
+import java.util.jar.JarFile;
+
+import cuchaz.enigma.gui.Gui;
+
+public class Main {
+
+ public static void main(String[] args) throws Exception {
+ Gui gui = new Gui();
+
+ // parse command-line args
+ if (args.length >= 1) {
+ gui.getController().openJar(new JarFile(getFile(args[0])));
+ }
+ if (args.length >= 2) {
+ gui.getController().openMappings(getFile(args[1]));
+ }
+
+ // DEBUG
+ //gui.getController().openDeclaration(new ClassEntry("none/bxq"));
+ }
+
+ private static File getFile(String path) {
+ // expand ~ to the home dir
+ if (path.startsWith("~")) {
+ // get the home dir
+ File dirHome = new File(System.getProperty("user.home"));
+
+ // is the path just ~/ or is it ~user/ ?
+ if (path.startsWith("~/")) {
+ return new File(dirHome, path.substring(2));
+ } else {
+ return new File(dirHome.getParentFile(), path.substring(1));
+ }
+ }
+
+ return new File(path);
+ }
+}
diff --git a/src/cuchaz/enigma/MainFormatConverter.java b/src/cuchaz/enigma/MainFormatConverter.java
new file mode 100644
index 00000000..73ee41f4
--- /dev/null
+++ b/src/cuchaz/enigma/MainFormatConverter.java
@@ -0,0 +1,130 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.lang.reflect.Field;
+import java.util.Map;
+import java.util.jar.JarFile;
+
+import javassist.CtClass;
+import javassist.CtField;
+
+import com.google.common.collect.Maps;
+
+import cuchaz.enigma.analysis.JarClassIterator;
+import cuchaz.enigma.mapping.ClassEntry;
+import cuchaz.enigma.mapping.ClassMapping;
+import cuchaz.enigma.mapping.ClassNameReplacer;
+import cuchaz.enigma.mapping.FieldEntry;
+import cuchaz.enigma.mapping.FieldMapping;
+import cuchaz.enigma.mapping.EntryFactory;
+import cuchaz.enigma.mapping.Mappings;
+import cuchaz.enigma.mapping.MappingsReader;
+import cuchaz.enigma.mapping.MappingsWriter;
+import cuchaz.enigma.mapping.Type;
+
+public class MainFormatConverter {
+
+ public static void main(String[] args)
+ throws Exception {
+
+ System.out.println("Getting field types from jar...");
+
+ JarFile jar = new JarFile(System.getProperty("user.home") + "/.minecraft/versions/1.8/1.8.jar");
+ Map fieldTypes = Maps.newHashMap();
+ for (CtClass c : JarClassIterator.classes(jar)) {
+ for (CtField field : c.getDeclaredFields()) {
+ FieldEntry fieldEntry = EntryFactory.getFieldEntry(field);
+ fieldTypes.put(getFieldKey(fieldEntry), moveClasssesOutOfDefaultPackage(fieldEntry.getType()));
+ }
+ }
+
+ System.out.println("Reading mappings...");
+
+ File fileMappings = new File("../Enigma Mappings/1.8.mappings");
+ MappingsReader mappingsReader = new MappingsReader() {
+
+ @Override
+ protected FieldMapping readField(String[] parts) {
+ // assume the void type for now
+ return new FieldMapping(parts[1], new Type("V"), parts[2]);
+ }
+ };
+ Mappings mappings = mappingsReader.read(new FileReader(fileMappings));
+
+ System.out.println("Updating field types...");
+
+ for (ClassMapping classMapping : mappings.classes()) {
+ updateFieldsInClass(fieldTypes, classMapping);
+ }
+
+ System.out.println("Saving mappings...");
+
+ try (FileWriter writer = new FileWriter(fileMappings)) {
+ new MappingsWriter().write(writer, mappings);
+ }
+
+ System.out.println("Done!");
+ }
+
+ private static Type moveClasssesOutOfDefaultPackage(Type type) {
+ return new Type(type, new ClassNameReplacer() {
+ @Override
+ public String replace(String className) {
+ ClassEntry entry = new ClassEntry(className);
+ if (entry.isInDefaultPackage()) {
+ return Constants.NonePackage + "/" + className;
+ }
+ return null;
+ }
+ });
+ }
+
+ private static void updateFieldsInClass(Map fieldTypes, ClassMapping classMapping)
+ throws Exception {
+
+ // update the fields
+ for (FieldMapping fieldMapping : classMapping.fields()) {
+ setFieldType(fieldTypes, classMapping, fieldMapping);
+ }
+
+ // recurse
+ for (ClassMapping innerClassMapping : classMapping.innerClasses()) {
+ updateFieldsInClass(fieldTypes, innerClassMapping);
+ }
+ }
+
+ private static void setFieldType(Map fieldTypes, ClassMapping classMapping, FieldMapping fieldMapping)
+ throws Exception {
+
+ // get the new type
+ Type newType = fieldTypes.get(getFieldKey(classMapping, fieldMapping));
+ if (newType == null) {
+ throw new Error("Can't find type for field: " + getFieldKey(classMapping, fieldMapping));
+ }
+
+ // hack in the new field type
+ Field field = fieldMapping.getClass().getDeclaredField("m_obfType");
+ field.setAccessible(true);
+ field.set(fieldMapping, newType);
+ }
+
+ private static Object getFieldKey(ClassMapping classMapping, FieldMapping fieldMapping) {
+ return classMapping.getObfSimpleName() + "." + fieldMapping.getObfName();
+ }
+
+ private static String getFieldKey(FieldEntry obfFieldEntry) {
+ return obfFieldEntry.getClassEntry().getSimpleName() + "." + obfFieldEntry.getName();
+ }
+}
diff --git a/src/cuchaz/enigma/TranslatingTypeLoader.java b/src/cuchaz/enigma/TranslatingTypeLoader.java
new file mode 100644
index 00000000..a2185e5c
--- /dev/null
+++ b/src/cuchaz/enigma/TranslatingTypeLoader.java
@@ -0,0 +1,249 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+import javassist.ByteArrayClassPath;
+import javassist.CannotCompileException;
+import javassist.ClassPool;
+import javassist.CtClass;
+import javassist.NotFoundException;
+import javassist.bytecode.Descriptor;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.strobel.assembler.metadata.Buffer;
+import com.strobel.assembler.metadata.ClasspathTypeLoader;
+import com.strobel.assembler.metadata.ITypeLoader;
+
+import cuchaz.enigma.analysis.BridgeMarker;
+import cuchaz.enigma.analysis.JarIndex;
+import cuchaz.enigma.bytecode.ClassRenamer;
+import cuchaz.enigma.bytecode.ClassTranslator;
+import cuchaz.enigma.bytecode.InnerClassWriter;
+import cuchaz.enigma.bytecode.LocalVariableRenamer;
+import cuchaz.enigma.bytecode.MethodParameterWriter;
+import cuchaz.enigma.mapping.ClassEntry;
+import cuchaz.enigma.mapping.Translator;
+
+public class TranslatingTypeLoader implements ITypeLoader {
+
+ private JarFile m_jar;
+ private JarIndex m_jarIndex;
+ private Translator m_obfuscatingTranslator;
+ private Translator m_deobfuscatingTranslator;
+ private Map m_cache;
+ private ClasspathTypeLoader m_defaultTypeLoader;
+
+ public TranslatingTypeLoader(JarFile jar, JarIndex jarIndex) {
+ this(jar, jarIndex, new Translator(), new Translator());
+ }
+
+ public TranslatingTypeLoader(JarFile jar, JarIndex jarIndex, Translator obfuscatingTranslator, Translator deobfuscatingTranslator) {
+ m_jar = jar;
+ m_jarIndex = jarIndex;
+ m_obfuscatingTranslator = obfuscatingTranslator;
+ m_deobfuscatingTranslator = deobfuscatingTranslator;
+ m_cache = Maps.newHashMap();
+ m_defaultTypeLoader = new ClasspathTypeLoader();
+ }
+
+ public void clearCache() {
+ m_cache.clear();
+ }
+
+ @Override
+ public boolean tryLoadType(String className, Buffer out) {
+
+ // check the cache
+ byte[] data;
+ if (m_cache.containsKey(className)) {
+ data = m_cache.get(className);
+ } else {
+ data = loadType(className);
+ m_cache.put(className, data);
+ }
+
+ if (data == null) {
+ // chain to default type loader
+ return m_defaultTypeLoader.tryLoadType(className, out);
+ }
+
+ // send the class to the decompiler
+ out.reset(data.length);
+ System.arraycopy(data, 0, out.array(), out.position(), data.length);
+ out.position(0);
+ return true;
+ }
+
+ public CtClass loadClass(String deobfClassName) {
+
+ byte[] data = loadType(deobfClassName);
+ if (data == null) {
+ return null;
+ }
+
+ // return a javassist handle for the class
+ String javaClassFileName = Descriptor.toJavaName(deobfClassName);
+ ClassPool classPool = new ClassPool();
+ classPool.insertClassPath(new ByteArrayClassPath(javaClassFileName, data));
+ try {
+ return classPool.get(javaClassFileName);
+ } catch (NotFoundException ex) {
+ throw new Error(ex);
+ }
+ }
+
+ private byte[] loadType(String className) {
+
+ // NOTE: don't know if class name is obf or deobf
+ ClassEntry classEntry = new ClassEntry(className);
+ ClassEntry obfClassEntry = m_obfuscatingTranslator.translateEntry(classEntry);
+
+ // is this an inner class referenced directly? (ie trying to load b instead of a$b)
+ if (!obfClassEntry.isInnerClass()) {
+ List classChain = m_jarIndex.getObfClassChain(obfClassEntry);
+ if (classChain.size() > 1) {
+ System.err.println(String.format("WARNING: no class %s after inner class reconstruction. Try %s",
+ className, obfClassEntry.buildClassEntry(classChain)
+ ));
+ return null;
+ }
+ }
+
+ // is this a class we should even know about?
+ if (!m_jarIndex.containsObfClass(obfClassEntry)) {
+ return null;
+ }
+
+ // DEBUG
+ //System.out.println(String.format("Looking for %s (obf: %s)", classEntry.getName(), obfClassEntry.getName()));
+
+ // find the class in the jar
+ String classInJarName = findClassInJar(obfClassEntry);
+ if (classInJarName == null) {
+ // couldn't find it
+ return null;
+ }
+
+ try {
+ // read the class file into a buffer
+ ByteArrayOutputStream data = new ByteArrayOutputStream();
+ byte[] buf = new byte[1024 * 1024]; // 1 KiB
+ InputStream in = m_jar.getInputStream(m_jar.getJarEntry(classInJarName + ".class"));
+ while (true) {
+ int bytesRead = in.read(buf);
+ if (bytesRead <= 0) {
+ break;
+ }
+ data.write(buf, 0, bytesRead);
+ }
+ data.close();
+ in.close();
+ buf = data.toByteArray();
+
+ // load the javassist handle to the raw class
+ ClassPool classPool = new ClassPool();
+ String classInJarJavaName = Descriptor.toJavaName(classInJarName);
+ classPool.insertClassPath(new ByteArrayClassPath(classInJarJavaName, buf));
+ CtClass c = classPool.get(classInJarJavaName);
+
+ c = transformClass(c);
+
+ // sanity checking
+ assertClassName(c, classEntry);
+
+ // DEBUG
+ //Util.writeClass( c );
+
+ // we have a transformed class!
+ return c.toBytecode();
+ } catch (IOException | NotFoundException | CannotCompileException ex) {
+ throw new Error(ex);
+ }
+ }
+
+ private String findClassInJar(ClassEntry obfClassEntry) {
+
+ // try to find the class in the jar
+ for (String className : getClassNamesToTry(obfClassEntry)) {
+ JarEntry jarEntry = m_jar.getJarEntry(className + ".class");
+ if (jarEntry != null) {
+ return className;
+ }
+ }
+
+ // didn't find it ;_;
+ return null;
+ }
+
+ public List getClassNamesToTry(String className) {
+ return getClassNamesToTry(m_obfuscatingTranslator.translateEntry(new ClassEntry(className)));
+ }
+
+ public List getClassNamesToTry(ClassEntry obfClassEntry) {
+ List classNamesToTry = Lists.newArrayList();
+ classNamesToTry.add(obfClassEntry.getName());
+ if (obfClassEntry.getPackageName().equals(Constants.NonePackage)) {
+ // taking off the none package, if any
+ classNamesToTry.add(obfClassEntry.getSimpleName());
+ }
+ if (obfClassEntry.isInnerClass()) {
+ // try just the inner class name
+ classNamesToTry.add(obfClassEntry.getInnermostClassName());
+ }
+ return classNamesToTry;
+ }
+
+ public CtClass transformClass(CtClass c)
+ throws IOException, NotFoundException, CannotCompileException {
+
+ // we moved a lot of classes out of the default package into the none package
+ // make sure all the class references are consistent
+ ClassRenamer.moveAllClassesOutOfDefaultPackage(c, Constants.NonePackage);
+
+ // reconstruct inner classes
+ new InnerClassWriter(m_jarIndex).write(c);
+
+ // re-get the javassist handle since we changed class names
+ ClassEntry obfClassEntry = new ClassEntry(Descriptor.toJvmName(c.getName()));
+ String javaClassReconstructedName = Descriptor.toJavaName(obfClassEntry.getName());
+ ClassPool classPool = new ClassPool();
+ classPool.insertClassPath(new ByteArrayClassPath(javaClassReconstructedName, c.toBytecode()));
+ c = classPool.get(javaClassReconstructedName);
+
+ // check that the file is correct after inner class reconstruction (ie cause Javassist to fail fast if something is wrong)
+ assertClassName(c, obfClassEntry);
+
+ // do all kinds of deobfuscating transformations on the class
+ new BridgeMarker(m_jarIndex).markBridges(c);
+ new MethodParameterWriter(m_deobfuscatingTranslator).writeMethodArguments(c);
+ new LocalVariableRenamer(m_deobfuscatingTranslator).rename(c);
+ new ClassTranslator(m_deobfuscatingTranslator).translate(c);
+
+ return c;
+ }
+
+ private void assertClassName(CtClass c, ClassEntry obfClassEntry) {
+ String name1 = Descriptor.toJvmName(c.getName());
+ assert (name1.equals(obfClassEntry.getName())) : String.format("Looking for %s, instead found %s", obfClassEntry.getName(), name1);
+
+ String name2 = Descriptor.toJvmName(c.getClassFile().getName());
+ assert (name2.equals(obfClassEntry.getName())) : String.format("Looking for %s, instead found %s", obfClassEntry.getName(), name2);
+ }
+}
diff --git a/src/cuchaz/enigma/Util.java b/src/cuchaz/enigma/Util.java
new file mode 100644
index 00000000..c7e509fa
--- /dev/null
+++ b/src/cuchaz/enigma/Util.java
@@ -0,0 +1,104 @@
+/*******************************************************************************
+ * Copyright (c) 2015 Jeff Martin.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public
+ * License v3.0 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Jeff Martin - initial API and implementation
+ ******************************************************************************/
+package cuchaz.enigma;
+
+import java.awt.Desktop;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.jar.JarFile;
+
+import javassist.CannotCompileException;
+import javassist.CtClass;
+import javassist.bytecode.Descriptor;
+
+import com.google.common.io.CharStreams;
+
+public class Util {
+
+ public static int combineHashesOrdered(Object... objs) {
+ return combineHashesOrdered(Arrays.asList(objs));
+ }
+
+ public static int combineHashesOrdered(Iterable