From 959cb5fd4f9586ec3bd265b452fe25fe1db82e3f Mon Sep 17 00:00:00 2001 From: jeff Date: Tue, 13 Jan 2015 23:25:04 -0500 Subject: source format change don't hate me too much if you were planning a big merge. =P --- src/cuchaz/enigma/CommandMain.java | 7 + src/cuchaz/enigma/Constants.java | 8 +- src/cuchaz/enigma/Deobfuscator.java | 595 ++++----- src/cuchaz/enigma/Main.java | 41 +- src/cuchaz/enigma/TranslatingTypeLoader.java | 176 ++- src/cuchaz/enigma/Util.java | 107 +- src/cuchaz/enigma/analysis/Access.java | 30 +- .../enigma/analysis/BehaviorReferenceTreeNode.java | 56 +- src/cuchaz/enigma/analysis/BridgeFixer.java | 51 +- .../analysis/ClassImplementationsTreeNode.java | 48 +- .../enigma/analysis/ClassInheritanceTreeNode.java | 58 +- src/cuchaz/enigma/analysis/EntryReference.java | 94 +- src/cuchaz/enigma/analysis/EntryRenamer.java | 173 ++- .../enigma/analysis/FieldReferenceTreeNode.java | 65 +- src/cuchaz/enigma/analysis/JarClassIterator.java | 107 +- src/cuchaz/enigma/analysis/JarIndex.java | 820 ++++++------- .../analysis/MethodImplementationsTreeNode.java | 66 +- .../enigma/analysis/MethodInheritanceTreeNode.java | 80 +- src/cuchaz/enigma/analysis/ReferenceTreeNode.java | 3 +- src/cuchaz/enigma/analysis/SourceIndex.java | 144 +-- .../analysis/SourceIndexBehaviorVisitor.java | 159 +-- .../enigma/analysis/SourceIndexClassVisitor.java | 97 +- src/cuchaz/enigma/analysis/SourceIndexVisitor.java | 370 +++--- src/cuchaz/enigma/analysis/Token.java | 41 +- src/cuchaz/enigma/analysis/TranslationIndex.java | 93 +- src/cuchaz/enigma/analysis/TreeDumpVisitor.java | 424 +++---- .../enigma/bytecode/BytecodeIndexIterator.java | 121 +- src/cuchaz/enigma/bytecode/BytecodeTools.java | 269 ++--- src/cuchaz/enigma/bytecode/CheckCastIterator.java | 98 +- src/cuchaz/enigma/bytecode/ClassRenamer.java | 103 +- src/cuchaz/enigma/bytecode/ClassTranslator.java | 104 +- src/cuchaz/enigma/bytecode/ConstPoolEditor.java | 295 ++--- src/cuchaz/enigma/bytecode/InfoType.java | 347 +++--- src/cuchaz/enigma/bytecode/InnerClassWriter.java | 103 +- .../enigma/bytecode/MethodParameterWriter.java | 47 +- .../enigma/bytecode/MethodParametersAttribute.java | 65 +- .../bytecode/accessors/ClassInfoAccessor.java | 58 +- .../bytecode/accessors/ConstInfoAccessor.java | 181 ++- .../accessors/InvokeDynamicInfoAccessor.java | 90 +- .../bytecode/accessors/MemberRefInfoAccessor.java | 90 +- .../accessors/MethodHandleInfoAccessor.java | 90 +- .../bytecode/accessors/MethodTypeInfoAccessor.java | 58 +- .../accessors/NameAndTypeInfoAccessor.java | 90 +- .../bytecode/accessors/StringInfoAccessor.java | 58 +- .../bytecode/accessors/Utf8InfoAccessor.java | 23 +- src/cuchaz/enigma/convert/ClassIdentity.java | 436 +++---- src/cuchaz/enigma/convert/ClassMatcher.java | 412 +++---- src/cuchaz/enigma/convert/ClassMatching.java | 152 +-- src/cuchaz/enigma/convert/ClassNamer.java | 53 +- src/cuchaz/enigma/gui/AboutDialog.java | 80 +- src/cuchaz/enigma/gui/BoxHighlightPainter.java | 37 +- src/cuchaz/enigma/gui/BrowserCaret.java | 21 +- src/cuchaz/enigma/gui/ClassListCellRenderer.java | 14 +- src/cuchaz/enigma/gui/ClassSelector.java | 131 +- src/cuchaz/enigma/gui/ClassSelectorClassNode.java | 13 +- .../enigma/gui/ClassSelectorPackageNode.java | 13 +- src/cuchaz/enigma/gui/CrashDialog.java | 77 +- .../enigma/gui/DeobfuscatedHighlightPainter.java | 9 +- src/cuchaz/enigma/gui/Gui.java | 1265 ++++++++------------ src/cuchaz/enigma/gui/GuiController.java | 349 +++--- src/cuchaz/enigma/gui/GuiTricks.java | 23 +- .../enigma/gui/ObfuscatedHighlightPainter.java | 9 +- src/cuchaz/enigma/gui/OtherHighlightPainter.java | 9 +- src/cuchaz/enigma/gui/ProgressDialog.java | 90 +- src/cuchaz/enigma/gui/ReadableToken.java | 22 +- src/cuchaz/enigma/gui/RenameListener.java | 5 +- .../enigma/gui/SelectionHighlightPainter.java | 15 +- src/cuchaz/enigma/gui/TokenListCellRenderer.java | 14 +- src/cuchaz/enigma/mapping/ArgumentEntry.java | 85 +- src/cuchaz/enigma/mapping/ArgumentMapping.java | 26 +- src/cuchaz/enigma/mapping/BehaviorEntry.java | 3 +- .../enigma/mapping/BehaviorEntryFactory.java | 71 +- src/cuchaz/enigma/mapping/ClassEntry.java | 116 +- src/cuchaz/enigma/mapping/ClassMapping.java | 520 ++++---- src/cuchaz/enigma/mapping/ConstructorEntry.java | 99 +- src/cuchaz/enigma/mapping/Entry.java | 11 +- src/cuchaz/enigma/mapping/EntryPair.java | 9 +- src/cuchaz/enigma/mapping/FieldEntry.java | 65 +- src/cuchaz/enigma/mapping/FieldMapping.java | 30 +- .../enigma/mapping/IllegalNameException.java | 29 +- .../enigma/mapping/MappingParseException.java | 10 +- src/cuchaz/enigma/mapping/Mappings.java | 230 ++-- src/cuchaz/enigma/mapping/MappingsReader.java | 218 ++-- src/cuchaz/enigma/mapping/MappingsRenamer.java | 308 ++--- src/cuchaz/enigma/mapping/MappingsWriter.java | 110 +- src/cuchaz/enigma/mapping/MethodEntry.java | 79 +- src/cuchaz/enigma/mapping/MethodMapping.java | 168 ++- src/cuchaz/enigma/mapping/NameValidator.java | 79 +- src/cuchaz/enigma/mapping/SignatureUpdater.java | 88 +- .../enigma/mapping/TranslationDirection.java | 21 +- src/cuchaz/enigma/mapping/Translator.java | 280 ++--- test/cuchaz/enigma/EntryFactory.java | 44 +- test/cuchaz/enigma/TestDeobfuscator.java | 34 +- test/cuchaz/enigma/TestInnerClasses.java | 48 +- .../enigma/TestJarIndexConstructorReferences.java | 160 ++- .../cuchaz/enigma/TestJarIndexInheritanceTree.java | 254 ++-- test/cuchaz/enigma/TestJarIndexLoneClass.java | 168 ++- test/cuchaz/enigma/TestSourceIndex.java | 36 +- test/cuchaz/enigma/TestTokensConstructors.java | 137 +-- test/cuchaz/enigma/TokenChecker.java | 46 +- test/cuchaz/enigma/inputs/Keep.java | 8 +- .../enigma/inputs/constructors/BaseClass.java | 16 +- test/cuchaz/enigma/inputs/constructors/Caller.java | 49 +- .../inputs/constructors/DefaultConstructable.java | 3 +- .../enigma/inputs/constructors/SubClass.java | 20 +- .../enigma/inputs/constructors/SubSubClass.java | 9 +- .../enigma/inputs/inheritanceTree/BaseClass.java | 12 +- .../enigma/inputs/inheritanceTree/SubclassA.java | 9 +- .../enigma/inputs/inheritanceTree/SubclassB.java | 19 +- .../inputs/inheritanceTree/SubsubclassAA.java | 17 +- .../enigma/inputs/innerClasses/Anonymous.java | 13 +- .../innerClasses/AnonymousWithScopeArgs.java | 15 +- .../inputs/innerClasses/ConstructorArgs.java | 18 +- test/cuchaz/enigma/inputs/innerClasses/Simple.java | 7 +- test/cuchaz/enigma/inputs/loneClass/LoneClass.java | 10 +- 115 files changed, 5378 insertions(+), 7881 deletions(-) create mode 100644 src/cuchaz/enigma/CommandMain.java diff --git a/src/cuchaz/enigma/CommandMain.java b/src/cuchaz/enigma/CommandMain.java new file mode 100644 index 0000000..7f88174 --- /dev/null +++ b/src/cuchaz/enigma/CommandMain.java @@ -0,0 +1,7 @@ +package cuchaz.enigma; + +public class CommandMain { + + public static void main(String[] args) { + } +} diff --git a/src/cuchaz/enigma/Constants.java b/src/cuchaz/enigma/Constants.java index 29a08b7..a1ba2e9 100644 --- a/src/cuchaz/enigma/Constants.java +++ b/src/cuchaz/enigma/Constants.java @@ -10,13 +10,11 @@ ******************************************************************************/ package cuchaz.enigma; - -public class Constants -{ +public class Constants { public static final String Name = "Enigma"; public static final String Version = "0.6 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 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/Deobfuscator.java b/src/cuchaz/enigma/Deobfuscator.java index 82c786c..679518a 100644 --- a/src/cuchaz/enigma/Deobfuscator.java +++ b/src/cuchaz/enigma/Deobfuscator.java @@ -61,12 +61,11 @@ 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 ); +public class Deobfuscator { + + public interface ProgressListener { + void init(int totalWork, String title); + void onProgress(int numDone, String message); } private File m_file; @@ -77,121 +76,104 @@ public class Deobfuscator private MappingsRenamer m_renamer; private Map m_translatorCache; - public Deobfuscator( File file ) - throws IOException - { + public Deobfuscator(File file) throws IOException { m_file = file; - m_jar = new JarFile( m_file ); + m_jar = new JarFile(m_file); // build the jar index m_jarIndex = new JarIndex(); - m_jarIndex.indexJar( m_jar, true ); + 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.setMergeVariables(true); + m_settings.setForceExplicitImports(true); + m_settings.setForceExplicitTypeArguments(true); // DEBUG - //m_settings.setShowSyntheticMembers( true ); + // m_settings.setShowSyntheticMembers( true ); // init defaults m_translatorCache = Maps.newTreeMap(); // init mappings - setMappings( new Mappings() ); + setMappings(new Mappings()); } - public String getJarName( ) - { + public String getJarName() { return m_file.getName(); } - public JarIndex getJarIndex( ) - { + public JarIndex getJarIndex() { return m_jarIndex; } - public Mappings getMappings( ) - { + public Mappings getMappings() { return m_mappings; } - public void setMappings( Mappings val ) - { - if( val == null ) - { + + public void setMappings(Mappings val) { + if (val == null) { val = new Mappings(); } // pass 1: look for any classes that got moved to inner classes Map renames = Maps.newHashMap(); - for( ClassMapping classMapping : val.classes() ) - { + for (ClassMapping classMapping : val.classes()) { // make sure we strip the packages off of obfuscated inner classes - String innerClassName = new ClassEntry( classMapping.getObfName() ).getSimpleName(); - String outerClassName = m_jarIndex.getOuterClass( innerClassName ); - if( outerClassName != null ) - { + String innerClassName = new ClassEntry(classMapping.getObfName()).getSimpleName(); + String outerClassName = m_jarIndex.getOuterClass(innerClassName); + if (outerClassName != null) { // build the composite class name String newName = outerClassName + "$" + innerClassName; // add a rename - renames.put( classMapping.getObfName(), newName ); + renames.put(classMapping.getObfName(), newName); - System.out.println( String.format( "Converted class mapping %s to %s", classMapping.getObfName(), newName ) ); + System.out.println(String.format("Converted class mapping %s to %s", classMapping.getObfName(), newName)); } } - for( Map.Entry entry : renames.entrySet() ) - { - val.renameObfClass( entry.getKey(), entry.getValue() ); + for (Map.Entry entry : renames.entrySet()) { + val.renameObfClass(entry.getKey(), entry.getValue()); } // pass 2: look for fields/methods that are actually declared in superclasses - MappingsRenamer renamer = new MappingsRenamer( m_jarIndex, val ); - for( ClassMapping classMapping : val.classes() ) - { - ClassEntry obfClassEntry = new ClassEntry( classMapping.getObfName() ); + MappingsRenamer renamer = new MappingsRenamer(m_jarIndex, val); + for (ClassMapping classMapping : val.classes()) { + ClassEntry obfClassEntry = new ClassEntry(classMapping.getObfName()); // fields - for( FieldMapping fieldMapping : Lists.newArrayList( classMapping.fields() ) ) - { - FieldEntry fieldEntry = new FieldEntry( obfClassEntry, fieldMapping.getObfName() ); - ClassEntry resolvedObfClassEntry = m_jarIndex.resolveEntryClass( fieldEntry ); - if( resolvedObfClassEntry != null && !resolvedObfClassEntry.equals( fieldEntry.getClassEntry() ) ) - { - boolean wasMoved = renamer.moveFieldToObfClass( classMapping, fieldMapping, resolvedObfClassEntry ); - if( wasMoved ) - { - System.out.println( String.format( "Moved field %s to class %s", fieldEntry, resolvedObfClassEntry ) ); - } - else - { - System.err.println( String.format( "WARNING: Would move field %s to class %s but the field was already there. Dropping instead.", fieldEntry, resolvedObfClassEntry ) ); + for (FieldMapping fieldMapping : Lists.newArrayList(classMapping.fields())) { + FieldEntry fieldEntry = new FieldEntry(obfClassEntry, fieldMapping.getObfName()); + ClassEntry resolvedObfClassEntry = m_jarIndex.resolveEntryClass(fieldEntry); + if (resolvedObfClassEntry != null && !resolvedObfClassEntry.equals(fieldEntry.getClassEntry())) { + boolean wasMoved = renamer.moveFieldToObfClass(classMapping, fieldMapping, resolvedObfClassEntry); + if (wasMoved) { + System.out.println(String.format("Moved field %s to class %s", fieldEntry, resolvedObfClassEntry)); + } else { + System.err.println(String.format("WARNING: Would move field %s to class %s but the field was already there. Dropping instead.", fieldEntry, resolvedObfClassEntry)); } } } // methods - for( MethodMapping methodMapping : Lists.newArrayList( classMapping.methods() ) ) - { + for (MethodMapping methodMapping : Lists.newArrayList(classMapping.methods())) { // skip constructors - if( methodMapping.isConstructor() ) - { + if (methodMapping.isConstructor()) { continue; } - MethodEntry methodEntry = new MethodEntry( obfClassEntry, methodMapping.getObfName(), methodMapping.getObfSignature() ); - ClassEntry resolvedObfClassEntry = m_jarIndex.resolveEntryClass( methodEntry ); - if( resolvedObfClassEntry != null && !resolvedObfClassEntry.equals( methodEntry.getClassEntry() ) ) - { - boolean wasMoved = renamer.moveMethodToObfClass( classMapping, methodMapping, resolvedObfClassEntry ); - if( wasMoved ) - { - System.out.println( String.format( "Moved method %s to class %s", methodEntry, resolvedObfClassEntry ) ); - } - else - { - System.err.println( String.format( "WARNING: Would move method %s to class %s but the method was already there. Dropping instead.", methodEntry, resolvedObfClassEntry ) ); + MethodEntry methodEntry = new MethodEntry( + obfClassEntry, + methodMapping.getObfName(), + methodMapping.getObfSignature() + ); + ClassEntry resolvedObfClassEntry = m_jarIndex.resolveEntryClass(methodEntry); + if (resolvedObfClassEntry != null && !resolvedObfClassEntry.equals(methodEntry.getClassEntry())) { + boolean wasMoved = renamer.moveMethodToObfClass(classMapping, methodMapping, resolvedObfClassEntry); + if (wasMoved) { + System.out.println(String.format("Moved method %s to class %s", methodEntry, resolvedObfClassEntry)); + } else { + System.err.println(String.format("WARNING: Would move method %s to class %s but the method was already there. Dropping instead.", methodEntry, resolvedObfClassEntry)); } } } @@ -201,13 +183,11 @@ public class Deobfuscator // drop mappings that don't match the jar List unknownClasses = Lists.newArrayList(); - for( ClassMapping classMapping : val.classes() ) - { - checkClassMapping( unknownClasses, classMapping ); + for (ClassMapping classMapping : val.classes()) { + checkClassMapping(unknownClasses, classMapping); } - if( !unknownClasses.isEmpty() ) - { - throw new Error( "Unable to find classes in jar: " + unknownClasses ); + if (!unknownClasses.isEmpty()) { + throw new Error("Unable to find classes in jar: " + unknownClasses); } m_mappings = val; @@ -215,453 +195,346 @@ public class Deobfuscator m_translatorCache.clear(); } - private void checkClassMapping( List unknownClasses, ClassMapping classMapping ) - { + private void checkClassMapping(List unknownClasses, ClassMapping classMapping) { // check the class - ClassEntry classEntry = new ClassEntry( classMapping.getObfName() ); - String outerClassName = m_jarIndex.getOuterClass( classEntry.getSimpleName() ); - if( outerClassName != null ) - { - classEntry = new ClassEntry( outerClassName + "$" + classMapping.getObfName() ); + ClassEntry classEntry = new ClassEntry(classMapping.getObfName()); + String outerClassName = m_jarIndex.getOuterClass(classEntry.getSimpleName()); + if (outerClassName != null) { + classEntry = new ClassEntry(outerClassName + "$" + classMapping.getObfName()); } - if( !m_jarIndex.getObfClassEntries().contains( classEntry ) ) - { - unknownClasses.add( classEntry ); + if (!m_jarIndex.getObfClassEntries().contains(classEntry)) { + unknownClasses.add(classEntry); } // check the fields - for( FieldMapping fieldMapping : Lists.newArrayList( classMapping.fields() ) ) - { - FieldEntry fieldEntry = new FieldEntry( classEntry, fieldMapping.getObfName() ); - if( !m_jarIndex.containsObfField( fieldEntry ) ) - { - System.err.println( "WARNING: unable to find field " + fieldEntry + ". dropping mapping." ); - classMapping.removeFieldMapping( fieldMapping ); + for (FieldMapping fieldMapping : Lists.newArrayList(classMapping.fields())) { + FieldEntry fieldEntry = new FieldEntry(classEntry, fieldMapping.getObfName()); + if (!m_jarIndex.containsObfField(fieldEntry)) { + System.err.println("WARNING: unable to find field " + fieldEntry + ". dropping mapping."); + classMapping.removeFieldMapping(fieldMapping); } } // check methods - for( MethodMapping methodMapping : Lists.newArrayList( classMapping.methods() ) ) - { - BehaviorEntry obfBehaviorEntry = BehaviorEntryFactory.createObf( classEntry, methodMapping ); - if( !m_jarIndex.containsObfBehavior( obfBehaviorEntry ) ) - { - System.err.println( "WARNING: unable to find behavior " + obfBehaviorEntry + ". dropping mapping." ); - classMapping.removeMethodMapping( methodMapping ); - } + for (MethodMapping methodMapping : Lists.newArrayList(classMapping.methods())) { + BehaviorEntry obfBehaviorEntry = BehaviorEntryFactory.createObf(classEntry, methodMapping); + if (!m_jarIndex.containsObfBehavior(obfBehaviorEntry)) { + System.err.println("WARNING: unable to find behavior " + obfBehaviorEntry + ". dropping mapping."); + classMapping.removeMethodMapping(methodMapping); + } } // check inner classes - for( ClassMapping innerClassMapping : classMapping.innerClasses() ) - { - checkClassMapping( unknownClasses, innerClassMapping ); + for (ClassMapping innerClassMapping : classMapping.innerClasses()) { + checkClassMapping(unknownClasses, innerClassMapping); } } - - public Translator getTranslator( TranslationDirection direction ) - { - Translator translator = m_translatorCache.get( direction ); - if( translator == null ) - { - translator = m_mappings.getTranslator( direction ); - m_translatorCache.put( direction, translator ); + + public Translator getTranslator(TranslationDirection direction) { + Translator translator = m_translatorCache.get(direction); + if (translator == null) { + translator = m_mappings.getTranslator(direction); + m_translatorCache.put(direction, translator); } return translator; } - public void getSeparatedClasses( List obfClasses, List deobfClasses ) - { - for( ClassEntry obfClassEntry : m_jarIndex.getObfClassEntries() ) - { + public void getSeparatedClasses(List obfClasses, List deobfClasses) { + for (ClassEntry obfClassEntry : m_jarIndex.getObfClassEntries()) { // skip inner classes - if( obfClassEntry.isInnerClass() ) - { + if (obfClassEntry.isInnerClass()) { continue; } // separate the classes - ClassEntry deobfClassEntry = deobfuscateEntry( obfClassEntry ); - if( !deobfClassEntry.equals( obfClassEntry ) ) - { + 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 ) ) - { + 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 - { + deobfClasses.add(obfClassEntry); + } else { // otherwise, assume it's still obfuscated - obfClasses.add( obfClassEntry ); + obfClasses.add(obfClassEntry); } } } - public CompilationUnit getSourceTree( String obfClassName ) - { + public CompilationUnit getSourceTree(String obfClassName) { // is this class deobfuscated? // we need to tell the decompiler the deobfuscated name so it doesn't get freaked out // the decompiler only sees the deobfuscated class, so we need to load it by the deobfuscated name String lookupClassName = obfClassName; - ClassMapping classMapping = m_mappings.getClassByObf( obfClassName ); - if( classMapping != null && classMapping.getDeobfName() != null ) - { + ClassMapping classMapping = m_mappings.getClassByObf(obfClassName); + if (classMapping != null && classMapping.getDeobfName() != null) { lookupClassName = classMapping.getDeobfName(); } // is this class even in the jar? - if( !m_jarIndex.containsObfClass( new ClassEntry( obfClassName ) ) ) - { + if (!m_jarIndex.containsObfClass(new ClassEntry(obfClassName))) { return null; } // set the type loader - m_settings.setTypeLoader( new TranslatingTypeLoader( + m_settings.setTypeLoader(new TranslatingTypeLoader( m_jar, m_jarIndex, - getTranslator( TranslationDirection.Obfuscating ), - getTranslator( TranslationDirection.Deobfuscating ) - ) ); + getTranslator(TranslationDirection.Obfuscating), + getTranslator(TranslationDirection.Deobfuscating) + )); // decompile it! - TypeDefinition resolvedType = new MetadataSystem( m_settings.getTypeLoader() ).lookupType( lookupClassName ).resolve(); + TypeDefinition resolvedType = new MetadataSystem(m_settings.getTypeLoader()).lookupType(lookupClassName).resolve(); DecompilerContext context = new DecompilerContext(); - context.setCurrentType( resolvedType ); - context.setSettings( m_settings ); - AstBuilder builder = new AstBuilder( context ); - builder.addType( resolvedType ); - builder.runTransformations( null ); + 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 ) - { + public SourceIndex getSourceIndex(CompilationUnit sourceTree, String source) { // build the source index - SourceIndex index = new SourceIndex( source ); - sourceTree.acceptVisitor( new SourceIndexVisitor(), index ); + SourceIndex index = new SourceIndex(source); + sourceTree.acceptVisitor(new SourceIndexVisitor(), index); // DEBUG - //sourceTree.acceptVisitor( new TreeDumpVisitor( new File( "tree.txt" ) ), null ); + // 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 ); + for (Token token : index.referenceTokens()) { + EntryReference deobfReference = index.getDeobfReference(token); // get the obfuscated entry - Entry obfEntry = obfuscateEntry( deobfReference.entry ); + Entry obfEntry = obfuscateEntry(deobfReference.entry); // try to resolve the class - ClassEntry resolvedObfClassEntry = m_jarIndex.resolveEntryClass( obfEntry ); - if( resolvedObfClassEntry != null && !resolvedObfClassEntry.equals( obfEntry.getClassEntry() ) ) - { + ClassEntry resolvedObfClassEntry = m_jarIndex.resolveEntryClass(obfEntry); + if (resolvedObfClassEntry != null && !resolvedObfClassEntry.equals(obfEntry.getClassEntry())) { // change the class of the entry - obfEntry = obfEntry.cloneToNewClass( resolvedObfClassEntry ); + obfEntry = obfEntry.cloneToNewClass(resolvedObfClassEntry); // save the new deobfuscated reference - deobfReference.entry = deobfuscateEntry( obfEntry ); - index.replaceDeobfReference( token, deobfReference ); + deobfReference.entry = deobfuscateEntry(obfEntry); + index.replaceDeobfReference(token, deobfReference); } // DEBUG - //System.out.println( token + " -> " + reference + " -> " + index.getReferenceToken( reference ) ); + // System.out.println( token + " -> " + reference + " -> " + index.getReferenceToken( reference ) ); } return index; } - public String getSource( CompilationUnit sourceTree ) - { + 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 ); + 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 - { + public void writeSources(File dirOut, ProgressListener progress) throws IOException { // get the classes to decompile Set classEntries = Sets.newHashSet(); - for( ClassEntry obfClassEntry : m_jarIndex.getObfClassEntries() ) - { + for (ClassEntry obfClassEntry : m_jarIndex.getObfClassEntries()) { // skip inner classes - if( obfClassEntry.isInnerClass() ) - { + if (obfClassEntry.isInnerClass()) { continue; } - classEntries.add( obfClassEntry ); + classEntries.add(obfClassEntry); } - if( progress != null ) - { - progress.init( classEntries.size(), "Decompiling classes..." ); + 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() ); + for (ClassEntry obfClassEntry : classEntries) { + ClassEntry deobfClassEntry = deobfuscateEntry(new ClassEntry(obfClassEntry)); + if (progress != null) { + progress.onProgress(i++, deobfClassEntry.toString()); } - try - { + try { // get the source - String source = getSource( getSourceTree( obfClassEntry.getName() ) ); + String source = getSource(getSourceTree(obfClassEntry.getName())); // write the file - File file = new File( dirOut, deobfClassEntry.getName().replace( '.', '/' ) + ".java" ); + File file = new File(dirOut, deobfClassEntry.getName().replace('.', '/') + ".java"); file.getParentFile().mkdirs(); - try( FileWriter out = new FileWriter( file ) ) - { - out.write( source ); + try (FileWriter out = new FileWriter(file)) { + out.write(source); } - } - catch( Throwable t ) - { - throw new Error( "Unable to deobfuscate class " + deobfClassEntry.toString() + " (" + obfClassEntry.toString() + ")", t ); + } catch (Throwable t) { + throw new Error("Unable to deobfuscate class " + deobfClassEntry.toString() + " (" + obfClassEntry.toString() + ")", t); } } - if( progress != null ) - { - progress.onProgress( i, "Done!" ); + if (progress != null) { + progress.onProgress(i, "Done!"); } } - public void writeJar( File out, ProgressListener progress ) - { - try( JarOutputStream outJar = new JarOutputStream( new FileOutputStream( out ) ) ) - { - if( progress != null ) - { - progress.init( JarClassIterator.getClassEntries( m_jar ).size(), "Translating classes..." ); + public void writeJar(File out, ProgressListener progress) { + try (JarOutputStream outJar = new JarOutputStream(new FileOutputStream(out))) { + if (progress != null) { + progress.init(JarClassIterator.getClassEntries(m_jar).size(), "Translating classes..."); } // prep the loader TranslatingTypeLoader loader = new TranslatingTypeLoader( m_jar, m_jarIndex, - getTranslator( TranslationDirection.Obfuscating ), - getTranslator( TranslationDirection.Deobfuscating ) + getTranslator(TranslationDirection.Obfuscating), + getTranslator(TranslationDirection.Deobfuscating) ); int i = 0; - for( CtClass c : JarClassIterator.classes( m_jar ) ) - { - if( progress != null ) - { - progress.onProgress( i++, c.getName() ); + for (CtClass c : JarClassIterator.classes(m_jar)) { + if (progress != null) { + progress.onProgress(i++, c.getName()); } - try - { - c = loader.transformClass( c ); - outJar.putNextEntry( new JarEntry( c.getName().replace( '.', '/' ) + ".class" ) ); - outJar.write( c.toBytecode() ); + try { + c = loader.transformClass(c); + outJar.putNextEntry(new JarEntry(c.getName().replace('.', '/') + ".class")); + outJar.write(c.toBytecode()); outJar.closeEntry(); - } - catch( Throwable t ) - { - throw new Error( "Unable to deobfuscate class " + c.getName(), t ); + } catch (Throwable t) { + throw new Error("Unable to deobfuscate class " + c.getName(), t); } } - if( progress != null ) - { - progress.onProgress( i, "Done!" ); + if (progress != null) { + progress.onProgress(i, "Done!"); } outJar.close(); - } - catch( IOException ex ) - { - throw new Error( "Unable to write to Jar file!" ); + } catch (IOException ex) { + throw new Error("Unable to write to Jar file!"); } } - public T obfuscateEntry( T deobfEntry ) - { - if( deobfEntry == null ) - { + public T obfuscateEntry(T deobfEntry) { + if (deobfEntry == null) { return null; } - return getTranslator( TranslationDirection.Obfuscating ).translateEntry( deobfEntry ); + return getTranslator(TranslationDirection.Obfuscating).translateEntry(deobfEntry); } - public T deobfuscateEntry( T obfEntry ) - { - if( obfEntry == null ) - { + public T deobfuscateEntry(T obfEntry) { + if (obfEntry == null) { return null; } - return getTranslator( TranslationDirection.Deobfuscating ).translateEntry( obfEntry ); + return getTranslator(TranslationDirection.Deobfuscating).translateEntry(obfEntry); } - public EntryReference obfuscateReference( EntryReference deobfReference ) - { - if( deobfReference == null ) - { + public EntryReference obfuscateReference(EntryReference deobfReference) { + if (deobfReference == null) { return null; } return new EntryReference( - obfuscateEntry( deobfReference.entry ), - obfuscateEntry( deobfReference.context ), + obfuscateEntry(deobfReference.entry), + obfuscateEntry(deobfReference.context), deobfReference ); } - public EntryReference deobfuscateReference( EntryReference obfReference ) - { - if( obfReference == null ) - { + public EntryReference deobfuscateReference(EntryReference obfReference) { + if (obfReference == null) { return null; } return new EntryReference( - deobfuscateEntry( obfReference.entry ), - deobfuscateEntry( obfReference.context ), + deobfuscateEntry(obfReference.entry), + deobfuscateEntry(obfReference.context), obfReference ); } - public boolean isObfuscatedIdentifier( Entry obfEntry ) - { - return m_jarIndex.containsObfEntry( obfEntry ); + public boolean isObfuscatedIdentifier(Entry obfEntry) { + return m_jarIndex.containsObfEntry(obfEntry); } - public boolean isRenameable( EntryReference obfReference ) - { - return obfReference.isNamed() && isObfuscatedIdentifier( obfReference.getNameableEntry() ); + 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 ) - { - return translator.translate( (ClassEntry)obfEntry ) != 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 ) - { + + public boolean hasDeobfuscatedName(Entry obfEntry) { + Translator translator = getTranslator(TranslationDirection.Deobfuscating); + if (obfEntry instanceof ClassEntry) { + return translator.translate((ClassEntry)obfEntry) != 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() ); + } 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() ); + + 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 ); + 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" ); + 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); } - 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/Main.java b/src/cuchaz/enigma/Main.java index 73a12db..f8d3afe 100644 --- a/src/cuchaz/enigma/Main.java +++ b/src/cuchaz/enigma/Main.java @@ -14,46 +14,37 @@ import java.io.File; import cuchaz.enigma.gui.Gui; -public class Main -{ - public static void main( String[] args ) - throws Exception - { +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( getFile( args[0] ) ); + if (args.length >= 1) { + gui.getController().openJar(getFile(args[0])); } - if( args.length >= 2 ) - { - gui.getController().openMappings( getFile( args[1] ) ); + if (args.length >= 2) { + gui.getController().openMappings(getFile(args[1])); } // DEBUG - //gui.getController().openDeclaration( new ClassEntry( "none/ces" ) ); + // gui.getController().openDeclaration( new ClassEntry( "none/ces" ) ); } - private static File getFile( String path ) - { + private static File getFile(String path) { // expand ~ to the home dir - if( path.startsWith( "~" ) ) - { + if (path.startsWith("~")) { // get the home dir - File dirHome = new File( System.getProperty( "user.home" ) ); + 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 ) ); + if (path.startsWith("~/")) { + return new File(dirHome, path.substring(2)); + } else { + return new File(dirHome.getParentFile(), path.substring(1)); } } - return new File( path ); + return new File(path); } } diff --git a/src/cuchaz/enigma/TranslatingTypeLoader.java b/src/cuchaz/enigma/TranslatingTypeLoader.java index e69e5cf..091f916 100644 --- a/src/cuchaz/enigma/TranslatingTypeLoader.java +++ b/src/cuchaz/enigma/TranslatingTypeLoader.java @@ -38,8 +38,8 @@ import cuchaz.enigma.bytecode.MethodParameterWriter; import cuchaz.enigma.mapping.ClassEntry; import cuchaz.enigma.mapping.Translator; -public class TranslatingTypeLoader implements ITypeLoader -{ +public class TranslatingTypeLoader implements ITypeLoader { + private JarFile m_jar; private JarIndex m_jarIndex; private Translator m_obfuscatingTranslator; @@ -47,13 +47,11 @@ public class TranslatingTypeLoader implements ITypeLoader 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) { + this(jar, jarIndex, new Translator(), new Translator()); } - public TranslatingTypeLoader( JarFile jar, JarIndex jarIndex, Translator obfuscatingTranslator, Translator deobfuscatingTranslator ) - { + public TranslatingTypeLoader(JarFile jar, JarIndex jarIndex, Translator obfuscatingTranslator, Translator deobfuscatingTranslator) { m_jar = jar; m_jarIndex = jarIndex; m_obfuscatingTranslator = obfuscatingTranslator; @@ -62,184 +60,154 @@ public class TranslatingTypeLoader implements ITypeLoader m_defaultTypeLoader = new ClasspathTypeLoader(); } - public void clearCache( ) - { + public void clearCache() { m_cache.clear(); } @Override - public boolean tryLoadType( String deobfClassName, Buffer out ) - { + public boolean tryLoadType(String deobfClassName, Buffer out) { // check the cache byte[] data; - if( m_cache.containsKey( deobfClassName ) ) - { - data = m_cache.get( deobfClassName ); - } - else - { - data = loadType( deobfClassName ); - m_cache.put( deobfClassName, data ); + if (m_cache.containsKey(deobfClassName)) { + data = m_cache.get(deobfClassName); + } else { + data = loadType(deobfClassName); + m_cache.put(deobfClassName, data); } - if( data == null ) - { + if (data == null) { // chain to default type loader - return m_defaultTypeLoader.tryLoadType( deobfClassName, out ); + return m_defaultTypeLoader.tryLoadType(deobfClassName, out); } // send the class to the decompiler - out.reset( data.length ); - System.arraycopy( data, 0, out.array(), out.position(), data.length ); - out.position( 0 ); + 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 ) - { + 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 ); + 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 ); + classPool.insertClassPath(new ByteArrayClassPath(javaClassFileName, data)); + try { + return classPool.get(javaClassFileName); + } catch (NotFoundException ex) { + throw new Error(ex); } } - private byte[] loadType( String deobfClassName ) - { - ClassEntry deobfClassEntry = new ClassEntry( deobfClassName ); - ClassEntry obfClassEntry = m_obfuscatingTranslator.translateEntry( deobfClassEntry ); + private byte[] loadType(String deobfClassName) { + ClassEntry deobfClassEntry = new ClassEntry(deobfClassName); + ClassEntry obfClassEntry = m_obfuscatingTranslator.translateEntry(deobfClassEntry); // is this an inner class referenced directly? - String obfOuterClassName = m_jarIndex.getOuterClass( obfClassEntry.getSimpleName() ); - if( obfOuterClassName != null ) - { + String obfOuterClassName = m_jarIndex.getOuterClass(obfClassEntry.getSimpleName()); + if (obfOuterClassName != null) { // this class doesn't really exist. Reference it by outer$inner instead - System.err.println( String.format( "WARNING: class %s referenced by bare inner name instead of via outer class %s", deobfClassName, obfOuterClassName ) ); + System.err.println(String.format("WARNING: class %s referenced by bare inner name instead of via outer class %s", deobfClassName, obfOuterClassName)); return null; } /* DEBUG - if( !Arrays.asList( "java", "org", "io" ).contains( deobfClassName.split( "/" )[0] ) ) - { + if( !Arrays.asList( "java", "org", "io" ).contains( deobfClassName.split( "/" )[0] ) ) { System.out.println( String.format( "Looking for %s (%s)", deobfClassEntry.getName(), obfClassEntry.getName() ) ); } */ // get the jar entry String classFileName; - if( obfClassEntry.isInnerClass() ) - { + if (obfClassEntry.isInnerClass()) { // use just the inner class name for inner classes classFileName = obfClassEntry.getInnerClassName(); - } - else if( obfClassEntry.getPackageName().equals( Constants.NonePackage ) ) - { + } else if (obfClassEntry.getPackageName().equals(Constants.NonePackage)) { // use the outer class simple name for classes in the none package classFileName = obfClassEntry.getSimpleName(); - } - else - { + } else { // otherwise, just use the class name (ie for classes in packages) classFileName = obfClassEntry.getName(); } - JarEntry entry = m_jar.getJarEntry( classFileName + ".class" ); - if( entry == null ) - { + JarEntry entry = m_jar.getJarEntry(classFileName + ".class"); + if (entry == null) { return null; } - - try - { + + 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( entry ); - while( true ) - { - int bytesRead = in.read( buf ); - if( bytesRead <= 0 ) - { + byte[] buf = new byte[1024 * 1024]; // 1 KiB + InputStream in = m_jar.getInputStream(entry); + while (true) { + int bytesRead = in.read(buf); + if (bytesRead <= 0) { break; } - data.write( buf, 0, bytesRead ); + data.write(buf, 0, bytesRead); } data.close(); in.close(); buf = data.toByteArray(); // load the javassist handle to the raw class - String javaClassFileName = Descriptor.toJavaName( classFileName ); + String javaClassFileName = Descriptor.toJavaName(classFileName); ClassPool classPool = new ClassPool(); - classPool.insertClassPath( new ByteArrayClassPath( javaClassFileName, buf ) ); - CtClass c = classPool.get( javaClassFileName ); + classPool.insertClassPath(new ByteArrayClassPath(javaClassFileName, buf)); + CtClass c = classPool.get(javaClassFileName); - c = transformClass( c ); + c = transformClass(c); // sanity checking - assertClassName( c, deobfClassEntry ); + assertClassName(c, deobfClassEntry); // DEBUG - //Util.writeClass( c ); - + // Util.writeClass( c ); + // we have a transformed class! return c.toBytecode(); - } - catch( IOException | NotFoundException | CannotCompileException ex ) - { - throw new Error( ex ); + } catch (IOException | NotFoundException | CannotCompileException ex) { + throw new Error(ex); } } - public CtClass transformClass( CtClass c ) - throws IOException, NotFoundException, CannotCompileException - { + 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 ); + ClassRenamer.moveAllClassesOutOfDefaultPackage(c, Constants.NonePackage); // reconstruct inner classes - new InnerClassWriter( m_jarIndex ).write( c ); + 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() ); + 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 ); + 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 ); + assertClassName(c, obfClassEntry); // do all kinds of deobfuscating transformations on the class - new BridgeFixer( m_jarIndex ).fixBridges( c ); - new MethodParameterWriter( m_deobfuscatingTranslator ).writeMethodArguments( c ); - new ClassTranslator( m_deobfuscatingTranslator ).translate( c ); + new BridgeFixer(m_jarIndex).fixBridges(c); + new MethodParameterWriter(m_deobfuscatingTranslator).writeMethodArguments(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 ); + + 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 ); + 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 index 678de54..7f04bda 100644 --- a/src/cuchaz/enigma/Util.java +++ b/src/cuchaz/enigma/Util.java @@ -28,108 +28,77 @@ 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 class Util { + + public static int combineHashesOrdered(Object... objs) { + return combineHashesOrdered(Arrays.asList(objs)); } - public static int combineHashesOrdered( Iterable objs ) - { + public static int combineHashesOrdered(Iterable objs) { final int prime = 67; int result = 1; - for( Object obj : objs ) - { + for (Object obj : objs) { result *= prime; - if( obj != null ) - { + if (obj != null) { result += obj.hashCode(); } } return result; } - public static void closeQuietly( Closeable closeable ) - { - if( closeable != null ) - { - try - { + public static void closeQuietly(Closeable closeable) { + if (closeable != null) { + try { closeable.close(); - } - catch( IOException ex ) - { + } catch (IOException ex) { // just ignore any further exceptions } } } - public static void closeQuietly( JarFile jarFile ) - { + public static void closeQuietly(JarFile jarFile) { // silly library should implement Closeable... - if( jarFile != null ) - { - try - { + if (jarFile != null) { + try { jarFile.close(); - } - catch( IOException ex ) - { + } catch (IOException ex) { // just ignore any further exceptions } } } - - public static String readStreamToString( InputStream in ) - throws IOException - { - return CharStreams.toString( new InputStreamReader( in, "UTF-8" ) ); + + public static String readStreamToString(InputStream in) throws IOException { + return CharStreams.toString(new InputStreamReader(in, "UTF-8")); } - public static String readResourceToString( String path ) - throws IOException - { - InputStream in = Util.class.getResourceAsStream( path ); - if( in == null ) - { - throw new IllegalArgumentException( "Resource not found! " + path ); + public static String readResourceToString(String path) throws IOException { + InputStream in = Util.class.getResourceAsStream(path); + if (in == null) { + throw new IllegalArgumentException("Resource not found! " + path); } - return readStreamToString( in ); + return readStreamToString(in); } - public static void openUrl( String url ) - { - if( Desktop.isDesktopSupported() ) - { + public static void openUrl(String url) { + if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); - try - { - desktop.browse( new URI( url ) ); - } - catch( IOException ex ) - { - throw new Error( ex ); - } - catch( URISyntaxException ex ) - { - throw new IllegalArgumentException( ex ); + try { + desktop.browse(new URI(url)); + } catch (IOException ex) { + throw new Error(ex); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException(ex); } } } - public static void writeClass( CtClass c ) - { - String name = Descriptor.toJavaName( c.getName() ); - File file = new File( name + ".class" ); - try( FileOutputStream out = new FileOutputStream( file ) ) - { - out.write( c.toBytecode() ); - } - catch( IOException | CannotCompileException ex ) - { - throw new Error( ex ); + public static void writeClass(CtClass c) { + String name = Descriptor.toJavaName(c.getName()); + File file = new File(name + ".class"); + try (FileOutputStream out = new FileOutputStream(file)) { + out.write(c.toBytecode()); + } catch (IOException | CannotCompileException ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/analysis/Access.java b/src/cuchaz/enigma/analysis/Access.java index e35bb21..8d3409a 100644 --- a/src/cuchaz/enigma/analysis/Access.java +++ b/src/cuchaz/enigma/analysis/Access.java @@ -15,37 +15,29 @@ import java.lang.reflect.Modifier; import javassist.CtBehavior; import javassist.CtField; -public enum Access -{ +public enum Access { + Public, Protected, Private; - public static Access get( CtBehavior behavior ) - { - return get( behavior.getModifiers() ); + public static Access get(CtBehavior behavior) { + return get(behavior.getModifiers()); } - public static Access get( CtField field ) - { - return get( field.getModifiers() ); + public static Access get(CtField field) { + return get(field.getModifiers()); } - public static Access get( int modifiers ) - { - if( Modifier.isPublic( modifiers ) ) - { + public static Access get(int modifiers) { + if (Modifier.isPublic(modifiers)) { return Public; - } - else if( Modifier.isProtected( modifiers ) ) - { + } else if (Modifier.isProtected(modifiers)) { return Protected; - } - else if( Modifier.isPrivate( modifiers ) ) - { + } else if (Modifier.isPrivate(modifiers)) { return Private; } // assume public by default return Public; } -} \ No newline at end of file +} diff --git a/src/cuchaz/enigma/analysis/BehaviorReferenceTreeNode.java b/src/cuchaz/enigma/analysis/BehaviorReferenceTreeNode.java index 20f1d47..9adac5e 100644 --- a/src/cuchaz/enigma/analysis/BehaviorReferenceTreeNode.java +++ b/src/cuchaz/enigma/analysis/BehaviorReferenceTreeNode.java @@ -21,8 +21,8 @@ import cuchaz.enigma.mapping.BehaviorEntry; import cuchaz.enigma.mapping.Entry; import cuchaz.enigma.mapping.Translator; -public class BehaviorReferenceTreeNode extends DefaultMutableTreeNode implements ReferenceTreeNode -{ +public class BehaviorReferenceTreeNode extends DefaultMutableTreeNode implements ReferenceTreeNode { + private static final long serialVersionUID = -3658163700783307520L; private Translator m_deobfuscatingTranslator; @@ -30,15 +30,13 @@ public class BehaviorReferenceTreeNode extends DefaultMutableTreeNode implements private EntryReference m_reference; private Access m_access; - public BehaviorReferenceTreeNode( Translator deobfuscatingTranslator, BehaviorEntry entry ) - { + public BehaviorReferenceTreeNode(Translator deobfuscatingTranslator, BehaviorEntry entry) { m_deobfuscatingTranslator = deobfuscatingTranslator; m_entry = entry; m_reference = null; } - public BehaviorReferenceTreeNode( Translator deobfuscatingTranslator, EntryReference reference, Access access ) - { + public BehaviorReferenceTreeNode(Translator deobfuscatingTranslator, EntryReference reference, Access access) { m_deobfuscatingTranslator = deobfuscatingTranslator; m_entry = reference.entry; m_reference = reference; @@ -46,60 +44,48 @@ public class BehaviorReferenceTreeNode extends DefaultMutableTreeNode implements } @Override - public BehaviorEntry getEntry( ) - { + public BehaviorEntry getEntry() { return m_entry; } @Override - public EntryReference getReference( ) - { + public EntryReference getReference() { return m_reference; } @Override - public String toString( ) - { - if( m_reference != null ) - { - return String.format( "%s (%s)", m_deobfuscatingTranslator.translateEntry( m_reference.context ), m_access ); + public String toString() { + if (m_reference != null) { + return String.format("%s (%s)", m_deobfuscatingTranslator.translateEntry(m_reference.context), m_access); } - return m_deobfuscatingTranslator.translateEntry( m_entry ).toString(); + return m_deobfuscatingTranslator.translateEntry(m_entry).toString(); } - public void load( JarIndex index, boolean recurse ) - { + public void load(JarIndex index, boolean recurse) { // get all the child nodes - for( EntryReference reference : index.getBehaviorReferences( m_entry ) ) - { - add( new BehaviorReferenceTreeNode( m_deobfuscatingTranslator, reference, index.getAccess( m_entry ) ) ); + for (EntryReference reference : index.getBehaviorReferences(m_entry)) { + add(new BehaviorReferenceTreeNode(m_deobfuscatingTranslator, reference, index.getAccess(m_entry))); } - if( recurse && children != null ) - { - for( Object child : children ) - { - if( child instanceof BehaviorReferenceTreeNode ) - { + if (recurse && children != null) { + for (Object child : children) { + if (child instanceof BehaviorReferenceTreeNode) { BehaviorReferenceTreeNode node = (BehaviorReferenceTreeNode)child; // don't recurse into ancestor Set ancestors = Sets.newHashSet(); TreeNode n = (TreeNode)node; - while( n.getParent() != null ) - { + while (n.getParent() != null) { n = n.getParent(); - if( n instanceof BehaviorReferenceTreeNode ) - { - ancestors.add( ((BehaviorReferenceTreeNode)n).getEntry() ); + if (n instanceof BehaviorReferenceTreeNode) { + ancestors.add( ((BehaviorReferenceTreeNode)n).getEntry()); } } - if( ancestors.contains( node.getEntry() ) ) - { + if (ancestors.contains(node.getEntry())) { continue; } - node.load( index, true ); + node.load(index, true); } } } diff --git a/src/cuchaz/enigma/analysis/BridgeFixer.java b/src/cuchaz/enigma/analysis/BridgeFixer.java index 112b864..ad23b00 100644 --- a/src/cuchaz/enigma/analysis/BridgeFixer.java +++ b/src/cuchaz/enigma/analysis/BridgeFixer.java @@ -20,61 +20,48 @@ import cuchaz.enigma.mapping.BehaviorEntryFactory; import cuchaz.enigma.mapping.ClassEntry; import cuchaz.enigma.mapping.MethodEntry; -public class BridgeFixer -{ +public class BridgeFixer { + private JarIndex m_index; - public BridgeFixer( JarIndex index ) - { + public BridgeFixer(JarIndex index) { m_index = index; } - - public void fixBridges( CtClass c ) - { + + public void fixBridges(CtClass c) { // rename declared methods - for( CtMethod method : c.getDeclaredMethods() ) - { + for (CtMethod method : c.getDeclaredMethods()) { // get the method entry MethodEntry methodEntry = new MethodEntry( - new ClassEntry( Descriptor.toJvmName( c.getName() ) ), + new ClassEntry(Descriptor.toJvmName(c.getName())), method.getName(), method.getSignature() ); - MethodEntry bridgeMethodEntry = m_index.getBridgeMethod( methodEntry ); - if( bridgeMethodEntry != null ) - { + MethodEntry bridgeMethodEntry = m_index.getBridgeMethod(methodEntry); + if (bridgeMethodEntry != null) { // fix this bridged method - method.setName( bridgeMethodEntry.getName() ); + method.setName(bridgeMethodEntry.getName()); } } // rename method references // translate all the field and method references in the code by editing the constant pool ConstPool constants = c.getClassFile().getConstPool(); - ConstPoolEditor editor = new ConstPoolEditor( constants ); - for( int i=1; i nodes = Lists.newArrayList(); - for( String implementingClassName : index.getImplementingClasses( m_entry.getClassName() ) ) - { - nodes.add( new ClassImplementationsTreeNode( m_deobfuscatingTranslator, new ClassEntry( implementingClassName ) ) ); + for (String implementingClassName : index.getImplementingClasses(m_entry.getClassName())) { + nodes.add(new ClassImplementationsTreeNode(m_deobfuscatingTranslator, new ClassEntry(implementingClassName))); } // add them to this node - for( ClassImplementationsTreeNode node : nodes ) - { - this.add( node ); + for (ClassImplementationsTreeNode node : nodes) { + this.add(node); } } - public static ClassImplementationsTreeNode findNode( ClassImplementationsTreeNode node, MethodEntry entry ) - { + public static ClassImplementationsTreeNode findNode(ClassImplementationsTreeNode node, MethodEntry entry) { // is this the node? - if( node.m_entry.equals( entry ) ) - { + if (node.m_entry.equals(entry)) { return node; } // recurse - for( int i=0; i nodes = Lists.newArrayList(); - for( String subclassName : ancestries.getSubclassNames( m_obfClassName ) ) - { - nodes.add( new ClassInheritanceTreeNode( m_deobfuscatingTranslator, subclassName ) ); + for (String subclassName : ancestries.getSubclassNames(m_obfClassName)) { + nodes.add(new ClassInheritanceTreeNode(m_deobfuscatingTranslator, subclassName)); } // add them to this node - for( ClassInheritanceTreeNode node : nodes ) - { - this.add( node ); + for (ClassInheritanceTreeNode node : nodes) { + this.add(node); } - if( recurse ) - { - for( ClassInheritanceTreeNode node : nodes ) - { - node.load( ancestries, true ); + if (recurse) { + for (ClassInheritanceTreeNode node : nodes) { + node.load(ancestries, true); } } } - - public static ClassInheritanceTreeNode findNode( ClassInheritanceTreeNode node, ClassEntry entry ) - { + + public static ClassInheritanceTreeNode findNode(ClassInheritanceTreeNode node, ClassEntry entry) { // is this the node? - if( node.getObfClassName().equals( entry.getName() ) ) - { + if (node.getObfClassName().equals(entry.getName())) { return node; } // recurse - for( int i=0; i -{ - private static final List ConstructorNonNames = Arrays.asList( "this", "super", "static" ); +public class EntryReference { + + private static final List ConstructorNonNames = Arrays.asList("this", "super", "static"); public E entry; public C context; private boolean m_isNamed; - public EntryReference( E entry, String sourceName ) - { - this( entry, sourceName, null ); + public EntryReference(E entry, String sourceName) { + this(entry, sourceName, null); } - public EntryReference( E entry, String sourceName, C context ) - { - if( entry == null ) - { - throw new IllegalArgumentException( "Entry cannot be null!" ); + public EntryReference(E entry, String sourceName, C context) { + if (entry == null) { + throw new IllegalArgumentException("Entry cannot be null!"); } this.entry = entry; this.context = context; m_isNamed = sourceName != null && sourceName.length() > 0; - if( entry instanceof ConstructorEntry && ConstructorNonNames.contains( sourceName ) ) - { + if (entry instanceof ConstructorEntry && ConstructorNonNames.contains(sourceName)) { m_isNamed = false; } } - public EntryReference( E entry, C context, EntryReference other ) - { + public EntryReference(E entry, C context, EntryReference other) { this.entry = entry; this.context = context; m_isNamed = other.m_isNamed; } - public ClassEntry getLocationClassEntry( ) - { - if( context != null ) - { + public ClassEntry getLocationClassEntry() { + if (context != null) { return context.getClassEntry(); } return entry.getClassEntry(); } - public boolean isNamed( ) - { + public boolean isNamed() { return m_isNamed; } - public Entry getNameableEntry( ) - { - if( entry instanceof ConstructorEntry ) - { + public Entry getNameableEntry() { + if (entry instanceof ConstructorEntry) { // renaming a constructor really means renaming the class return entry.getClassEntry(); } return entry; } - public String getNamableName( ) - { - if( getNameableEntry() instanceof ClassEntry ) - { + public String getNamableName() { + if (getNameableEntry() instanceof ClassEntry) { ClassEntry classEntry = (ClassEntry)getNameableEntry(); - if( classEntry.isInnerClass() ) - { + if (classEntry.isInnerClass()) { // make sure we only rename the inner class name return classEntry.getInnerClassName(); } @@ -95,55 +82,44 @@ public class EntryReference } @Override - public int hashCode( ) - { - if( context != null ) - { - return Util.combineHashesOrdered( entry.hashCode(), context.hashCode() ); + public int hashCode() { + if (context != null) { + return Util.combineHashesOrdered(entry.hashCode(), context.hashCode()); } return entry.hashCode(); } @Override - public boolean equals( Object other ) - { - if( other instanceof EntryReference ) - { - return equals( (EntryReference)other ); + public boolean equals(Object other) { + if (other instanceof EntryReference) { + return equals((EntryReference)other); } return false; } - public boolean equals( EntryReference other ) - { + public boolean equals(EntryReference other) { // check entry first - boolean isEntrySame = entry.equals( other.entry ); - if( !isEntrySame ) - { + boolean isEntrySame = entry.equals(other.entry); + if (!isEntrySame) { return false; } // check caller - if( context == null && other.context == null ) - { + if (context == null && other.context == null) { return true; - } - else if( context != null && other.context != null ) - { - return context.equals( other.context ); + } else if (context != null && other.context != null) { + return context.equals(other.context); } return false; } @Override - public String toString( ) - { + public String toString() { StringBuilder buf = new StringBuilder(); - buf.append( entry ); - if( context != null ) - { - buf.append( " called from " ); - buf.append( context ); + buf.append(entry); + if (context != null) { + buf.append(" called from "); + buf.append(context); } return buf.toString(); } diff --git a/src/cuchaz/enigma/analysis/EntryRenamer.java b/src/cuchaz/enigma/analysis/EntryRenamer.java index 2d59fe9..b54489c 100644 --- a/src/cuchaz/enigma/analysis/EntryRenamer.java +++ b/src/cuchaz/enigma/analysis/EntryRenamer.java @@ -26,100 +26,83 @@ import cuchaz.enigma.mapping.Entry; import cuchaz.enigma.mapping.FieldEntry; import cuchaz.enigma.mapping.MethodEntry; -public class EntryRenamer -{ - public static void renameClassesInSet( Map renames, Set set ) - { +public class EntryRenamer { + + public static void renameClassesInSet(Map renames, Set set) { List entries = Lists.newArrayList(); - for( T val : set ) - { - entries.add( renameClassesInThing( renames, val ) ); + for (T val : set) { + entries.add(renameClassesInThing(renames, val)); } set.clear(); - set.addAll( entries ); + set.addAll(entries); } - public static void renameClassesInMap( Map renames, Map map ) - { + public static void renameClassesInMap(Map renames, Map map) { // for each key/value pair... Set> entriesToAdd = Sets.newHashSet(); - for( Map.Entry entry : map.entrySet() ) - { - entriesToAdd.add( new AbstractMap.SimpleEntry( - renameClassesInThing( renames, entry.getKey() ), - renameClassesInThing( renames, entry.getValue() ) - ) ); + for (Map.Entry entry : map.entrySet()) { + entriesToAdd.add(new AbstractMap.SimpleEntry( + renameClassesInThing(renames, entry.getKey()), + renameClassesInThing(renames, entry.getValue()) + )); } map.clear(); - for( Map.Entry entry : entriesToAdd ) - { - map.put( entry.getKey(), entry.getValue() ); + for (Map.Entry entry : entriesToAdd) { + map.put(entry.getKey(), entry.getValue()); } } - public static void renameClassesInMultimap( Map renames, Multimap map ) - { + public static void renameClassesInMultimap(Map renames, Multimap map) { // for each key/value pair... Set> entriesToAdd = Sets.newHashSet(); - for( Map.Entry entry : map.entries() ) - { - entriesToAdd.add( new AbstractMap.SimpleEntry( - renameClassesInThing( renames, entry.getKey() ), - renameClassesInThing( renames, entry.getValue() ) - ) ); + for (Map.Entry entry : map.entries()) { + entriesToAdd.add(new AbstractMap.SimpleEntry( + renameClassesInThing(renames, entry.getKey()), + renameClassesInThing(renames, entry.getValue()) + )); } map.clear(); - for( Map.Entry entry : entriesToAdd ) - { - map.put( entry.getKey(), entry.getValue() ); + for (Map.Entry entry : entriesToAdd) { + map.put(entry.getKey(), entry.getValue()); } } - public static void renameMethodsInMultimap( Map renames, Multimap map ) - { + public static void renameMethodsInMultimap(Map renames, Multimap map) { // for each key/value pair... Set> entriesToAdd = Sets.newHashSet(); - for( Map.Entry entry : map.entries() ) - { - entriesToAdd.add( new AbstractMap.SimpleEntry( - renameMethodsInThing( renames, entry.getKey() ), - renameMethodsInThing( renames, entry.getValue() ) - ) ); + for (Map.Entry entry : map.entries()) { + entriesToAdd.add(new AbstractMap.SimpleEntry( + renameMethodsInThing(renames, entry.getKey()), + renameMethodsInThing(renames, entry.getValue()) + )); } map.clear(); - for( Map.Entry entry : entriesToAdd ) - { - map.put( entry.getKey(), entry.getValue() ); + for (Map.Entry entry : entriesToAdd) { + map.put(entry.getKey(), entry.getValue()); } } - public static void renameMethodsInMap( Map renames, Map map ) - { + public static void renameMethodsInMap(Map renames, Map map) { // for each key/value pair... Set> entriesToAdd = Sets.newHashSet(); - for( Map.Entry entry : map.entrySet() ) - { - entriesToAdd.add( new AbstractMap.SimpleEntry( - renameMethodsInThing( renames, entry.getKey() ), - renameMethodsInThing( renames, entry.getValue() ) - ) ); + for (Map.Entry entry : map.entrySet()) { + entriesToAdd.add(new AbstractMap.SimpleEntry( + renameMethodsInThing(renames, entry.getKey()), + renameMethodsInThing(renames, entry.getValue()) + )); } map.clear(); - for( Map.Entry entry : entriesToAdd ) - { - map.put( entry.getKey(), entry.getValue() ); + for (Map.Entry entry : entriesToAdd) { + map.put(entry.getKey(), entry.getValue()); } } - @SuppressWarnings( "unchecked" ) - public static T renameMethodsInThing( Map renames, T thing ) - { - if( thing instanceof MethodEntry ) - { + @SuppressWarnings("unchecked") + public static T renameMethodsInThing(Map renames, T thing) { + if (thing instanceof MethodEntry) { MethodEntry methodEntry = (MethodEntry)thing; - MethodEntry newMethodEntry = renames.get( methodEntry ); - if( newMethodEntry != null ) - { + MethodEntry newMethodEntry = renames.get(methodEntry); + if (newMethodEntry != null) { return (T)new MethodEntry( methodEntry.getClassEntry(), newMethodEntry.getName(), @@ -127,81 +110,59 @@ public class EntryRenamer ); } return thing; - } - else if( thing instanceof ArgumentEntry ) - { + } else if (thing instanceof ArgumentEntry) { ArgumentEntry argumentEntry = (ArgumentEntry)thing; return (T)new ArgumentEntry( - renameMethodsInThing( renames, argumentEntry.getBehaviorEntry() ), + renameMethodsInThing(renames, argumentEntry.getBehaviorEntry()), argumentEntry.getIndex(), argumentEntry.getName() ); - } - else if( thing instanceof EntryReference ) - { + } else if (thing instanceof EntryReference) { EntryReference reference = (EntryReference)thing; - reference.entry = renameMethodsInThing( renames, reference.entry ); - reference.context = renameMethodsInThing( renames, reference.context ); + reference.entry = renameMethodsInThing(renames, reference.entry); + reference.context = renameMethodsInThing(renames, reference.context); return thing; } return thing; } - - @SuppressWarnings( "unchecked" ) - public static T renameClassesInThing( Map renames, T thing ) - { - if( thing instanceof String ) - { + + @SuppressWarnings("unchecked") + public static T renameClassesInThing(Map renames, T thing) { + if (thing instanceof String) { String stringEntry = (String)thing; - if( renames.containsKey( stringEntry ) ) - { - return (T)renames.get( stringEntry ); + if (renames.containsKey(stringEntry)) { + return (T)renames.get(stringEntry); } - } - else if( thing instanceof ClassEntry ) - { + } else if (thing instanceof ClassEntry) { ClassEntry classEntry = (ClassEntry)thing; - return (T)new ClassEntry( renameClassesInThing( renames, classEntry.getClassName() ) ); - } - else if( thing instanceof FieldEntry ) - { + return (T)new ClassEntry(renameClassesInThing(renames, classEntry.getClassName())); + } else if (thing instanceof FieldEntry) { FieldEntry fieldEntry = (FieldEntry)thing; - return (T)new FieldEntry( - renameClassesInThing( renames, fieldEntry.getClassEntry() ), - fieldEntry.getName() - ); - } - else if( thing instanceof ConstructorEntry ) - { + return (T)new FieldEntry(renameClassesInThing(renames, fieldEntry.getClassEntry()), fieldEntry.getName()); + } else if (thing instanceof ConstructorEntry) { ConstructorEntry constructorEntry = (ConstructorEntry)thing; return (T)new ConstructorEntry( - renameClassesInThing( renames, constructorEntry.getClassEntry() ), + renameClassesInThing(renames, constructorEntry.getClassEntry()), constructorEntry.getSignature() ); - } - else if( thing instanceof MethodEntry ) - { + } else if (thing instanceof MethodEntry) { MethodEntry methodEntry = (MethodEntry)thing; return (T)new MethodEntry( - renameClassesInThing( renames, methodEntry.getClassEntry() ), + renameClassesInThing(renames, methodEntry.getClassEntry()), methodEntry.getName(), methodEntry.getSignature() ); - } - else if( thing instanceof ArgumentEntry ) - { + } else if (thing instanceof ArgumentEntry) { ArgumentEntry argumentEntry = (ArgumentEntry)thing; return (T)new ArgumentEntry( - renameClassesInThing( renames, argumentEntry.getBehaviorEntry() ), + renameClassesInThing(renames, argumentEntry.getBehaviorEntry()), argumentEntry.getIndex(), argumentEntry.getName() ); - } - else if( thing instanceof EntryReference ) - { + } else if (thing instanceof EntryReference) { EntryReference reference = (EntryReference)thing; - reference.entry = renameClassesInThing( renames, reference.entry ); - reference.context = renameClassesInThing( renames, reference.context ); + reference.entry = renameClassesInThing(renames, reference.entry); + reference.context = renameClassesInThing(renames, reference.context); return thing; } diff --git a/src/cuchaz/enigma/analysis/FieldReferenceTreeNode.java b/src/cuchaz/enigma/analysis/FieldReferenceTreeNode.java index 2652f64..2173eea 100644 --- a/src/cuchaz/enigma/analysis/FieldReferenceTreeNode.java +++ b/src/cuchaz/enigma/analysis/FieldReferenceTreeNode.java @@ -16,24 +16,22 @@ import cuchaz.enigma.mapping.BehaviorEntry; import cuchaz.enigma.mapping.FieldEntry; import cuchaz.enigma.mapping.Translator; -public class FieldReferenceTreeNode extends DefaultMutableTreeNode implements ReferenceTreeNode -{ +public class FieldReferenceTreeNode extends DefaultMutableTreeNode implements ReferenceTreeNode { + private static final long serialVersionUID = -7934108091928699835L; private Translator m_deobfuscatingTranslator; private FieldEntry m_entry; private EntryReference m_reference; private Access m_access; - - public FieldReferenceTreeNode( Translator deobfuscatingTranslator, FieldEntry entry ) - { + + public FieldReferenceTreeNode(Translator deobfuscatingTranslator, FieldEntry entry) { m_deobfuscatingTranslator = deobfuscatingTranslator; m_entry = entry; m_reference = null; } - private FieldReferenceTreeNode( Translator deobfuscatingTranslator, EntryReference reference, Access access ) - { + private FieldReferenceTreeNode(Translator deobfuscatingTranslator, EntryReference reference, Access access) { m_deobfuscatingTranslator = deobfuscatingTranslator; m_entry = reference.entry; m_reference = reference; @@ -41,56 +39,41 @@ public class FieldReferenceTreeNode extends DefaultMutableTreeNode implements Re } @Override - public FieldEntry getEntry( ) - { + public FieldEntry getEntry() { return m_entry; } @Override - public EntryReference getReference( ) - { + public EntryReference getReference() { return m_reference; } @Override - public String toString( ) - { - if( m_reference != null ) - { - return String.format( "%s (%s)", m_deobfuscatingTranslator.translateEntry( m_reference.context ), m_access ); + public String toString() { + if (m_reference != null) { + return String.format("%s (%s)", m_deobfuscatingTranslator.translateEntry(m_reference.context), m_access); } - return m_deobfuscatingTranslator.translateEntry( m_entry ).toString(); + return m_deobfuscatingTranslator.translateEntry(m_entry).toString(); } - public void load( JarIndex index, boolean recurse ) - { + public void load(JarIndex index, boolean recurse) { // get all the child nodes - if( m_reference == null ) - { - for( EntryReference reference : index.getFieldReferences( m_entry ) ) - { - add( new FieldReferenceTreeNode( m_deobfuscatingTranslator, reference, index.getAccess( m_entry ) ) ); + if (m_reference == null) { + for (EntryReference reference : index.getFieldReferences(m_entry)) { + add(new FieldReferenceTreeNode(m_deobfuscatingTranslator, reference, index.getAccess(m_entry))); } - } - else - { - for( EntryReference reference : index.getBehaviorReferences( m_reference.context ) ) - { - add( new BehaviorReferenceTreeNode( m_deobfuscatingTranslator, reference, index.getAccess( m_reference.context ) ) ); + } else { + for (EntryReference reference : index.getBehaviorReferences(m_reference.context)) { + add(new BehaviorReferenceTreeNode(m_deobfuscatingTranslator, reference, index.getAccess(m_reference.context))); } } - if( recurse && children != null ) - { - for( Object node : children ) - { - if( node instanceof BehaviorReferenceTreeNode ) - { - ((BehaviorReferenceTreeNode)node).load( index, true ); - } - else if( node instanceof FieldReferenceTreeNode ) - { - ((FieldReferenceTreeNode)node).load( index, true ); + if (recurse && children != null) { + for (Object node : children) { + if (node instanceof BehaviorReferenceTreeNode) { + ((BehaviorReferenceTreeNode)node).load(index, true); + } else if (node instanceof FieldReferenceTreeNode) { + ((FieldReferenceTreeNode)node).load(index, true); } } } diff --git a/src/cuchaz/enigma/analysis/JarClassIterator.java b/src/cuchaz/enigma/analysis/JarClassIterator.java index f65b8e7..8d9947c 100644 --- a/src/cuchaz/enigma/analysis/JarClassIterator.java +++ b/src/cuchaz/enigma/analysis/JarClassIterator.java @@ -30,132 +30,107 @@ import com.google.common.collect.Lists; import cuchaz.enigma.Constants; import cuchaz.enigma.mapping.ClassEntry; -public class JarClassIterator implements Iterator -{ +public class JarClassIterator implements Iterator { + private JarFile m_jar; private Iterator m_iter; - public JarClassIterator( JarFile jar ) - { + public JarClassIterator(JarFile jar) { m_jar = jar; // get the jar entries that correspond to classes List classEntries = Lists.newArrayList(); Enumeration entries = m_jar.entries(); - while( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); // is this a class file? - if( entry.getName().endsWith( ".class" ) ) - { - classEntries.add( entry ); + if (entry.getName().endsWith(".class")) { + classEntries.add(entry); } } m_iter = classEntries.iterator(); } @Override - public boolean hasNext( ) - { + public boolean hasNext() { return m_iter.hasNext(); } - + @Override - public CtClass next( ) - { + public CtClass next() { JarEntry entry = m_iter.next(); - try - { - return getClass( m_jar, entry ); - } - catch( IOException | NotFoundException ex ) - { - throw new Error( "Unable to load class: " + entry.getName() ); + try { + return getClass(m_jar, entry); + } catch (IOException | NotFoundException ex) { + throw new Error("Unable to load class: " + entry.getName()); } } - + @Override - public void remove( ) - { + public void remove() { throw new UnsupportedOperationException(); } - public static List getClassEntries( JarFile jar ) - { + public static List getClassEntries(JarFile jar) { List classEntries = Lists.newArrayList(); Enumeration entries = jar.entries(); - while( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); // is this a class file? - if( !entry.isDirectory() && entry.getName().endsWith( ".class" ) ) - { - classEntries.add( getClassEntry( entry ) ); + if (!entry.isDirectory() && entry.getName().endsWith(".class")) { + classEntries.add(getClassEntry(entry)); } } return classEntries; } - public static Iterable classes( final JarFile jar ) - { - return new Iterable( ) - { + public static Iterable classes(final JarFile jar) { + return new Iterable() { @Override - public Iterator iterator( ) - { - return new JarClassIterator( jar ); + public Iterator iterator() { + return new JarClassIterator(jar); } }; } - public static CtClass getClass( JarFile jar, ClassEntry classEntry ) - { - try - { - return getClass( jar, new JarEntry( classEntry.getName() + ".class" ) ); - } - catch( IOException | NotFoundException ex ) - { - throw new Error( "Unable to load class: " + classEntry.getName() ); + public static CtClass getClass(JarFile jar, ClassEntry classEntry) { + try { + return getClass(jar, new JarEntry(classEntry.getName() + ".class")); + } catch (IOException | NotFoundException ex) { + throw new Error("Unable to load class: " + classEntry.getName()); } } - private static CtClass getClass( JarFile jar, JarEntry entry ) - throws IOException, NotFoundException - { + private static CtClass getClass(JarFile jar, JarEntry entry) throws IOException, NotFoundException { // read the class into a buffer ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[Constants.KiB]; int totalNumBytesRead = 0; - InputStream in = jar.getInputStream( entry ); - while( in.available() > 0 ) - { - int numBytesRead = in.read( buf ); - if( numBytesRead < 0 ) - { + InputStream in = jar.getInputStream(entry); + while (in.available() > 0) { + int numBytesRead = in.read(buf); + if (numBytesRead < 0) { break; } - bos.write( buf, 0, numBytesRead ); + bos.write(buf, 0, numBytesRead); // sanity checking totalNumBytesRead += numBytesRead; - if( totalNumBytesRead > Constants.MiB ) - { - throw new Error( "Class file " + entry.getName() + " larger than 1 MiB! Something is wrong!" ); + if (totalNumBytesRead > Constants.MiB) { + throw new Error("Class file " + entry.getName() + " larger than 1 MiB! Something is wrong!"); } } // get a javassist handle for the class - String className = Descriptor.toJavaName( getClassEntry( entry ).getName() ); + String className = Descriptor.toJavaName(getClassEntry(entry).getName()); ClassPool classPool = new ClassPool(); - classPool.insertClassPath( new ByteArrayClassPath( className, bos.toByteArray() ) ); - return classPool.get( className ); + classPool.insertClassPath(new ByteArrayClassPath(className, bos.toByteArray())); + return classPool.get(className); } - private static ClassEntry getClassEntry( JarEntry entry ) - { - return new ClassEntry( entry.getName().substring( 0, entry.getName().length() - ".class".length() ) ); + private static ClassEntry getClassEntry(JarEntry entry) { + return new ClassEntry(entry.getName().substring(0, entry.getName().length() - ".class".length())); } } diff --git a/src/cuchaz/enigma/analysis/JarIndex.java b/src/cuchaz/enigma/analysis/JarIndex.java index 0954564..4b03a33 100644 --- a/src/cuchaz/enigma/analysis/JarIndex.java +++ b/src/cuchaz/enigma/analysis/JarIndex.java @@ -53,8 +53,8 @@ import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.SignatureUpdater; import cuchaz.enigma.mapping.Translator; -public class JarIndex -{ +public class JarIndex { + private Set m_obfClassEntries; private TranslationIndex m_translationIndex; private Multimap m_interfaces; @@ -68,8 +68,7 @@ public class JarIndex private Map m_anonymousClasses; private Map m_bridgeMethods; - public JarIndex( ) - { + public JarIndex() { m_obfClassEntries = Sets.newHashSet(); m_translationIndex = new TranslationIndex(); m_interfaces = HashMultimap.create(); @@ -84,192 +83,161 @@ public class JarIndex m_bridgeMethods = Maps.newHashMap(); } - public void indexJar( JarFile jar, boolean buildInnerClasses ) - { + public void indexJar(JarFile jar, boolean buildInnerClasses) { // step 1: read the class names - for( ClassEntry classEntry : JarClassIterator.getClassEntries( jar ) ) - { - if( classEntry.isInDefaultPackage() ) - { + for (ClassEntry classEntry : JarClassIterator.getClassEntries(jar)) { + if (classEntry.isInDefaultPackage()) { // move out of default package - classEntry = new ClassEntry( Constants.NonePackage + "/" + classEntry.getName() ); + classEntry = new ClassEntry(Constants.NonePackage + "/" + classEntry.getName()); } - m_obfClassEntries.add( classEntry ); + m_obfClassEntries.add(classEntry); } // step 2: index field/method/constructor access - for( CtClass c : JarClassIterator.classes( jar ) ) - { - ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage ); - ClassEntry classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) ); - for( CtField field : c.getDeclaredFields() ) - { - FieldEntry fieldEntry = new FieldEntry( classEntry, field.getName() ); - m_access.put( fieldEntry, Access.get( field ) ); + for (CtClass c : JarClassIterator.classes(jar)) { + ClassRenamer.moveAllClassesOutOfDefaultPackage(c, Constants.NonePackage); + ClassEntry classEntry = new ClassEntry(Descriptor.toJvmName(c.getName())); + for (CtField field : c.getDeclaredFields()) { + FieldEntry fieldEntry = new FieldEntry(classEntry, field.getName()); + m_access.put(fieldEntry, Access.get(field)); } - for( CtMethod method : c.getDeclaredMethods() ) - { - MethodEntry methodEntry = new MethodEntry( classEntry, method.getName(), method.getSignature() ); - m_access.put( methodEntry, Access.get( method ) ); + for (CtMethod method : c.getDeclaredMethods()) { + MethodEntry methodEntry = new MethodEntry(classEntry, method.getName(), method.getSignature()); + m_access.put(methodEntry, Access.get(method)); } - for( CtConstructor constructor : c.getDeclaredConstructors() ) - { - ConstructorEntry constructorEntry = new ConstructorEntry( classEntry, constructor.getSignature() ); - m_access.put( constructorEntry, Access.get( constructor ) ); + for (CtConstructor constructor : c.getDeclaredConstructors()) { + ConstructorEntry constructorEntry = new ConstructorEntry(classEntry, constructor.getSignature()); + m_access.put(constructorEntry, Access.get(constructor)); } } // step 3: index extends, implements, fields, and methods - for( CtClass c : JarClassIterator.classes( jar ) ) - { - ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage ); - String className = Descriptor.toJvmName( c.getName() ); - m_translationIndex.addSuperclass( className, Descriptor.toJvmName( c.getClassFile().getSuperclass() ) ); - for( String interfaceName : c.getClassFile().getInterfaces() ) - { - className = Descriptor.toJvmName( className ); - interfaceName = Descriptor.toJvmName( interfaceName ); - if( className.equals( interfaceName ) ) - { - throw new IllegalArgumentException( "Class cannot be its own interface! " + className ); + for (CtClass c : JarClassIterator.classes(jar)) { + ClassRenamer.moveAllClassesOutOfDefaultPackage(c, Constants.NonePackage); + String className = Descriptor.toJvmName(c.getName()); + m_translationIndex.addSuperclass(className, Descriptor.toJvmName(c.getClassFile().getSuperclass())); + for (String interfaceName : c.getClassFile().getInterfaces()) { + className = Descriptor.toJvmName(className); + interfaceName = Descriptor.toJvmName(interfaceName); + if (className.equals(interfaceName)) { + throw new IllegalArgumentException("Class cannot be its own interface! " + className); } - m_interfaces.put( className, interfaceName ); + m_interfaces.put(className, interfaceName); } - for( CtField field : c.getDeclaredFields() ) - { - indexField( field ); + for (CtField field : c.getDeclaredFields()) { + indexField(field); } - for( CtBehavior behavior : c.getDeclaredBehaviors() ) - { - indexBehavior( behavior ); + for (CtBehavior behavior : c.getDeclaredBehaviors()) { + indexBehavior(behavior); } } // step 4: index field, method, constructor references - for( CtClass c : JarClassIterator.classes( jar ) ) - { - ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage ); - for( CtBehavior behavior : c.getDeclaredBehaviors() ) - { - indexBehaviorReferences( behavior ); + for (CtClass c : JarClassIterator.classes(jar)) { + ClassRenamer.moveAllClassesOutOfDefaultPackage(c, Constants.NonePackage); + for (CtBehavior behavior : c.getDeclaredBehaviors()) { + indexBehaviorReferences(behavior); } } - if( buildInnerClasses ) - { + if (buildInnerClasses) { // step 5: index inner classes and anonymous classes - for( CtClass c : JarClassIterator.classes( jar ) ) - { - ClassRenamer.moveAllClassesOutOfDefaultPackage( c, Constants.NonePackage ); - String outerClassName = findOuterClass( c ); - if( outerClassName != null ) - { + for (CtClass c : JarClassIterator.classes(jar)) { + ClassRenamer.moveAllClassesOutOfDefaultPackage(c, Constants.NonePackage); + String outerClassName = findOuterClass(c); + if (outerClassName != null) { String innerClassName = c.getSimpleName(); - m_innerClasses.put( outerClassName, innerClassName ); - boolean innerWasAdded = m_outerClasses.put( innerClassName, outerClassName ) == null; - assert( innerWasAdded ); + m_innerClasses.put(outerClassName, innerClassName); + boolean innerWasAdded = m_outerClasses.put(innerClassName, outerClassName) == null; + assert (innerWasAdded); - BehaviorEntry enclosingBehavior = isAnonymousClass( c, outerClassName ); - if( enclosingBehavior != null ) - { - m_anonymousClasses.put( innerClassName, enclosingBehavior ); + BehaviorEntry enclosingBehavior = isAnonymousClass(c, outerClassName); + if (enclosingBehavior != null) { + m_anonymousClasses.put(innerClassName, enclosingBehavior); // DEBUG - //System.out.println( "ANONYMOUS: " + outerClassName + "$" + innerClassName ); - } - else - { + // System.out.println( "ANONYMOUS: " + outerClassName + "$" + innerClassName ); + } else { // DEBUG - //System.out.println( "INNER: " + outerClassName + "$" + innerClassName ); + // System.out.println( "INNER: " + outerClassName + "$" + innerClassName ); } } } // step 6: update other indices with inner class info Map renames = Maps.newHashMap(); - for( Map.Entry entry : m_outerClasses.entrySet() ) - { - renames.put( Constants.NonePackage + "/" + entry.getKey(), entry.getValue() + "$" + entry.getKey() ); + for (Map.Entry entry : m_outerClasses.entrySet()) { + renames.put(Constants.NonePackage + "/" + entry.getKey(), entry.getValue() + "$" + entry.getKey()); } - EntryRenamer.renameClassesInSet( renames, m_obfClassEntries ); - m_translationIndex.renameClasses( renames ); - EntryRenamer.renameClassesInMultimap( renames, m_interfaces ); - EntryRenamer.renameClassesInMultimap( renames, m_methodImplementations ); - EntryRenamer.renameClassesInMultimap( renames, m_behaviorReferences ); - EntryRenamer.renameClassesInMultimap( renames, m_fieldReferences ); - EntryRenamer.renameClassesInMap( renames, m_bridgeMethods ); - EntryRenamer.renameClassesInMap( renames, m_access ); + EntryRenamer.renameClassesInSet(renames, m_obfClassEntries); + m_translationIndex.renameClasses(renames); + EntryRenamer.renameClassesInMultimap(renames, m_interfaces); + EntryRenamer.renameClassesInMultimap(renames, m_methodImplementations); + EntryRenamer.renameClassesInMultimap(renames, m_behaviorReferences); + EntryRenamer.renameClassesInMultimap(renames, m_fieldReferences); + EntryRenamer.renameClassesInMap(renames, m_bridgeMethods); + EntryRenamer.renameClassesInMap(renames, m_access); } // step 6: update other indices with bridge method info - EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_methodImplementations ); - EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_behaviorReferences ); - EntryRenamer.renameMethodsInMultimap( m_bridgeMethods, m_fieldReferences ); - EntryRenamer.renameMethodsInMap( m_bridgeMethods, m_access ); + EntryRenamer.renameMethodsInMultimap(m_bridgeMethods, m_methodImplementations); + EntryRenamer.renameMethodsInMultimap(m_bridgeMethods, m_behaviorReferences); + EntryRenamer.renameMethodsInMultimap(m_bridgeMethods, m_fieldReferences); + EntryRenamer.renameMethodsInMap(m_bridgeMethods, m_access); } - private void indexField( CtField field ) - { + private void indexField(CtField field) { // get the field entry - String className = Descriptor.toJvmName( field.getDeclaringClass().getName() ); - FieldEntry fieldEntry = new FieldEntry( new ClassEntry( className ), field.getName() ); + String className = Descriptor.toJvmName(field.getDeclaringClass().getName()); + FieldEntry fieldEntry = new FieldEntry(new ClassEntry(className), field.getName()); - m_translationIndex.addField( className, field.getName() ); + m_translationIndex.addField(className, field.getName()); // is the field a class type? - if( field.getSignature().startsWith( "L" ) ) - { - ClassEntry fieldTypeEntry = new ClassEntry( field.getSignature().substring( 1, field.getSignature().length() - 1 ) ); - m_fieldClasses.put( fieldEntry, fieldTypeEntry ); + if (field.getSignature().startsWith("L")) { + ClassEntry fieldTypeEntry = new ClassEntry(field.getSignature().substring(1, field.getSignature().length() - 1)); + m_fieldClasses.put(fieldEntry, fieldTypeEntry); } } - - private void indexBehavior( CtBehavior behavior ) - { + + private void indexBehavior(CtBehavior behavior) { // get the behavior entry - final BehaviorEntry behaviorEntry = BehaviorEntryFactory.create( behavior ); - if( behaviorEntry instanceof MethodEntry ) - { + final BehaviorEntry behaviorEntry = BehaviorEntryFactory.create(behavior); + if (behaviorEntry instanceof MethodEntry) { MethodEntry methodEntry = (MethodEntry)behaviorEntry; // index implementation - m_methodImplementations.put( behaviorEntry.getClassName(), methodEntry ); + m_methodImplementations.put(behaviorEntry.getClassName(), methodEntry); // look for bridge methods - CtMethod bridgedMethod = getBridgedMethod( (CtMethod)behavior ); - if( bridgedMethod != null ) - { + CtMethod bridgedMethod = getBridgedMethod((CtMethod)behavior); + if (bridgedMethod != null) { MethodEntry bridgedMethodEntry = new MethodEntry( behaviorEntry.getClassEntry(), bridgedMethod.getName(), bridgedMethod.getSignature() ); - m_bridgeMethods.put( bridgedMethodEntry, methodEntry ); + m_bridgeMethods.put(bridgedMethodEntry, methodEntry); } } // looks like we don't care about constructors here } - private void indexBehaviorReferences( CtBehavior behavior ) - { + private void indexBehaviorReferences(CtBehavior behavior) { // index method calls - final BehaviorEntry behaviorEntry = BehaviorEntryFactory.create( behavior ); - try - { - behavior.instrument( new ExprEditor( ) - { + final BehaviorEntry behaviorEntry = BehaviorEntryFactory.create(behavior); + try { + behavior.instrument(new ExprEditor() { @Override - public void edit( MethodCall call ) - { - String className = Descriptor.toJvmName( call.getClassName() ); + public void edit(MethodCall call) { + String className = Descriptor.toJvmName(call.getClassName()); MethodEntry calledMethodEntry = new MethodEntry( - new ClassEntry( className ), + new ClassEntry(className), call.getMethodName(), call.getSignature() ); - ClassEntry resolvedClassEntry = resolveEntryClass( calledMethodEntry ); - if( resolvedClassEntry != null && !resolvedClassEntry.equals( calledMethodEntry.getClassEntry() ) ) - { + ClassEntry resolvedClassEntry = resolveEntryClass(calledMethodEntry); + if (resolvedClassEntry != null && !resolvedClassEntry.equals(calledMethodEntry.getClassEntry())) { calledMethodEntry = new MethodEntry( resolvedClassEntry, call.getMethodName(), @@ -281,39 +249,33 @@ public class JarIndex call.getMethodName(), behaviorEntry ); - m_behaviorReferences.put( calledMethodEntry, reference ); + m_behaviorReferences.put(calledMethodEntry, reference); } @Override - public void edit( FieldAccess call ) - { - String className = Descriptor.toJvmName( call.getClassName() ); + public void edit(FieldAccess call) { + String className = Descriptor.toJvmName(call.getClassName()); FieldEntry calledFieldEntry = new FieldEntry( - new ClassEntry( className ), + new ClassEntry(className), call.getFieldName() ); - ClassEntry resolvedClassEntry = resolveEntryClass( calledFieldEntry ); - if( resolvedClassEntry != null && !resolvedClassEntry.equals( calledFieldEntry.getClassEntry() ) ) - { - calledFieldEntry = new FieldEntry( - resolvedClassEntry, - call.getFieldName() - ); + ClassEntry resolvedClassEntry = resolveEntryClass(calledFieldEntry); + if (resolvedClassEntry != null && !resolvedClassEntry.equals(calledFieldEntry.getClassEntry())) { + calledFieldEntry = new FieldEntry(resolvedClassEntry, call.getFieldName()); } EntryReference reference = new EntryReference( calledFieldEntry, call.getFieldName(), behaviorEntry ); - m_fieldReferences.put( calledFieldEntry, reference ); + m_fieldReferences.put(calledFieldEntry, reference); } @Override - public void edit( ConstructorCall call ) - { - String className = Descriptor.toJvmName( call.getClassName() ); + public void edit(ConstructorCall call) { + String className = Descriptor.toJvmName(call.getClassName()); ConstructorEntry calledConstructorEntry = new ConstructorEntry( - new ClassEntry( className ), + new ClassEntry(className), call.getSignature() ); EntryReference reference = new EntryReference( @@ -321,15 +283,14 @@ public class JarIndex call.getMethodName(), behaviorEntry ); - m_behaviorReferences.put( calledConstructorEntry, reference ); + m_behaviorReferences.put(calledConstructorEntry, reference); } @Override - public void edit( NewExpr call ) - { - String className = Descriptor.toJvmName( call.getClassName() ); + public void edit(NewExpr call) { + String className = Descriptor.toJvmName(call.getClassName()); ConstructorEntry calledConstructorEntry = new ConstructorEntry( - new ClassEntry( className ), + new ClassEntry(className), call.getSignature() ); EntryReference reference = new EntryReference( @@ -337,173 +298,141 @@ public class JarIndex call.getClassName(), behaviorEntry ); - m_behaviorReferences.put( calledConstructorEntry, reference ); + m_behaviorReferences.put(calledConstructorEntry, reference); } - } ); - } - catch( CannotCompileException ex ) - { - throw new Error( ex ); + }); + } catch (CannotCompileException ex) { + throw new Error(ex); } } - public ClassEntry resolveEntryClass( Entry obfEntry ) - { + public ClassEntry resolveEntryClass(Entry obfEntry) { + // this entry could refer to a method on a class where the method is not actually implemented // travel up the inheritance tree to find the closest implementation - while( !containsObfEntry( obfEntry ) ) - { + while (!containsObfEntry(obfEntry)) { // is there a parent class? - String superclassName = m_translationIndex.getSuperclassName( obfEntry.getClassName() ); - if( superclassName == null ) - { + String superclassName = m_translationIndex.getSuperclassName(obfEntry.getClassName()); + if (superclassName == null) { // this is probably a method from a class in a library // we can't trace the implementation up any higher unless we index the library return null; } // move up to the parent class - obfEntry = obfEntry.cloneToNewClass( new ClassEntry( superclassName ) ); + obfEntry = obfEntry.cloneToNewClass(new ClassEntry(superclassName)); } return obfEntry.getClassEntry(); } - - private CtMethod getBridgedMethod( CtMethod method ) - { + + private CtMethod getBridgedMethod(CtMethod method) { + // bridge methods just call another method, cast it to the return type, and return the result // let's see if we can detect this scenario // skip non-synthetic methods - if( ( method.getModifiers() & AccessFlag.SYNTHETIC ) == 0 ) - { + if ( (method.getModifiers() & AccessFlag.SYNTHETIC) == 0) { return null; } - + // get all the called methods final List methodCalls = Lists.newArrayList(); - try - { - method.instrument( new ExprEditor( ) - { + try { + method.instrument(new ExprEditor() { @Override - public void edit( MethodCall call ) - { - methodCalls.add( call ); + public void edit(MethodCall call) { + methodCalls.add(call); } - } ); - } - catch( CannotCompileException ex ) - { + }); + } catch (CannotCompileException ex) { // this is stupid... we're not even compiling anything - throw new Error( ex ); + throw new Error(ex); } // is there just one? - if( methodCalls.size() != 1 ) - { + if (methodCalls.size() != 1) { return null; } - MethodCall call = methodCalls.get( 0 ); + MethodCall call = methodCalls.get(0); - try - { + try { // we have a bridge method! return call.getMethod(); - } - catch( NotFoundException ex ) - { + } catch (NotFoundException ex) { // can't find the type? not a bridge method return null; } } - private String findOuterClass( CtClass c ) - { + private String findOuterClass(CtClass c) { + // inner classes: - // have constructors that can (illegally) set synthetic fields - // the outer class is the only class that calls constructors + // have constructors that can (illegally) set synthetic fields + // the outer class is the only class that calls constructors // use the synthetic fields to find the synthetic constructors - for( CtConstructor constructor : c.getDeclaredConstructors() ) - { + for (CtConstructor constructor : c.getDeclaredConstructors()) { Set syntheticFieldTypes = Sets.newHashSet(); - if( !isIllegalConstructor( syntheticFieldTypes, constructor ) ) - { + if (!isIllegalConstructor(syntheticFieldTypes, constructor)) { continue; } - ClassEntry classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) ); - ConstructorEntry constructorEntry = new ConstructorEntry( classEntry, constructor.getMethodInfo().getDescriptor() ); + ClassEntry classEntry = new ClassEntry(Descriptor.toJvmName(c.getName())); + ConstructorEntry constructorEntry = new ConstructorEntry( + classEntry, + constructor.getMethodInfo().getDescriptor() + ); // gather the classes from the illegally-set synthetic fields Set illegallySetClasses = Sets.newHashSet(); - for( String type : syntheticFieldTypes ) - { - if( type.startsWith( "L" ) ) - { - ClassEntry outerClassEntry = new ClassEntry( type.substring( 1, type.length() - 1 ) ); - if( isSaneOuterClass( outerClassEntry, classEntry ) ) - { - illegallySetClasses.add( outerClassEntry ); + for (String type : syntheticFieldTypes) { + if (type.startsWith("L")) { + ClassEntry outerClassEntry = new ClassEntry(type.substring(1, type.length() - 1)); + if (isSaneOuterClass(outerClassEntry, classEntry)) { + illegallySetClasses.add(outerClassEntry); } } } // who calls this constructor? Set callerClasses = Sets.newHashSet(); - for( EntryReference reference : getBehaviorReferences( constructorEntry ) ) - { + for (EntryReference reference : getBehaviorReferences(constructorEntry)) { + // make sure it's not a call to super - if( reference.entry instanceof ConstructorEntry && reference.context instanceof ConstructorEntry ) - { + if (reference.entry instanceof ConstructorEntry && reference.context instanceof ConstructorEntry) { + // is the entry a superclass of the context? String calledClassName = reference.entry.getClassName(); - String callerSuperclassName = m_translationIndex.getSuperclassName( reference.context.getClassName() ); - if( callerSuperclassName != null && callerSuperclassName.equals( calledClassName ) ) - { + String callerSuperclassName = m_translationIndex.getSuperclassName(reference.context.getClassName()); + if (callerSuperclassName != null && callerSuperclassName.equals(calledClassName)) { // it's a super call, skip continue; } } - if( isSaneOuterClass( reference.context.getClassEntry(), classEntry ) ) - { - callerClasses.add( reference.context.getClassEntry() ); + if (isSaneOuterClass(reference.context.getClassEntry(), classEntry)) { + callerClasses.add(reference.context.getClassEntry()); } } // do we have an answer yet? - if( callerClasses.isEmpty() ) - { - if( illegallySetClasses.size() == 1 ) - { + if (callerClasses.isEmpty()) { + if (illegallySetClasses.size() == 1) { return illegallySetClasses.iterator().next().getName(); + } else { + System.out.println(String.format("WARNING: Unable to find outer class for %s. No caller and no illegally set field classes.", classEntry)); } - else - { - System.out.println( String.format( "WARNING: Unable to find outer class for %s. No caller and no illegally set field classes.", classEntry ) ); - } - } - else - { - if( callerClasses.size() == 1 ) - { + } else { + if (callerClasses.size() == 1) { return callerClasses.iterator().next().getName(); - } - else - { + } else { // multiple callers, do the illegally set classes narrow it down? - Set intersection = Sets.newHashSet( callerClasses ); - intersection.retainAll( illegallySetClasses ); - if( intersection.size() == 1 ) - { + Set intersection = Sets.newHashSet(callerClasses); + intersection.retainAll(illegallySetClasses); + if (intersection.size() == 1) { return intersection.iterator().next().getName(); - } - else - { - System.out.println( String.format( "WARNING: Unable to choose outer class for %s among options: %s", - classEntry, callerClasses - ) ); + } else { + System.out.println(String.format("WARNING: Unable to choose outer class for %s among options: %s", classEntry, callerClasses)); } } } @@ -512,99 +441,82 @@ public class JarIndex return null; } - private boolean isSaneOuterClass( ClassEntry outerClassEntry, ClassEntry innerClassEntry ) - { + private boolean isSaneOuterClass(ClassEntry outerClassEntry, ClassEntry innerClassEntry) { + // clearly this would be silly - if( outerClassEntry.equals( innerClassEntry ) ) - { + if (outerClassEntry.equals(innerClassEntry)) { return false; } // is the outer class in the jar? - if( !m_obfClassEntries.contains( outerClassEntry ) ) - { + if (!m_obfClassEntries.contains(outerClassEntry)) { return false; } return true; } - - @SuppressWarnings( "unchecked" ) - private boolean isIllegalConstructor( Set syntheticFieldTypes, CtConstructor constructor ) - { + + @SuppressWarnings("unchecked") + private boolean isIllegalConstructor(Set syntheticFieldTypes, CtConstructor constructor) { + // illegal constructors only set synthetic member fields, then call super() String className = constructor.getDeclaringClass().getName(); // collect all the field accesses, constructor calls, and method calls final List illegalFieldWrites = Lists.newArrayList(); final List constructorCalls = Lists.newArrayList(); - try - { - constructor.instrument( new ExprEditor( ) - { + try { + constructor.instrument(new ExprEditor() { @Override - public void edit( FieldAccess fieldAccess ) - { - if( fieldAccess.isWriter() && constructorCalls.isEmpty() ) - { - illegalFieldWrites.add( fieldAccess ); + public void edit(FieldAccess fieldAccess) { + if (fieldAccess.isWriter() && constructorCalls.isEmpty()) { + illegalFieldWrites.add(fieldAccess); } } @Override - public void edit( ConstructorCall constructorCall ) - { - constructorCalls.add( constructorCall ); + public void edit(ConstructorCall constructorCall) { + constructorCalls.add(constructorCall); } - } ); - } - catch( CannotCompileException ex ) - { + }); + } catch (CannotCompileException ex) { // we're not compiling anything... this is stupid - throw new Error( ex ); + throw new Error(ex); } // are there any illegal field writes? - if( illegalFieldWrites.isEmpty() ) - { + if (illegalFieldWrites.isEmpty()) { return false; } // are all the writes to synthetic fields? - for( FieldAccess fieldWrite : illegalFieldWrites ) - { + for (FieldAccess fieldWrite : illegalFieldWrites) { + // all illegal writes have to be to the local class - if( !fieldWrite.getClassName().equals( className ) ) - { - System.err.println( String.format( "WARNING: illegal write to non-member field %s.%s", fieldWrite.getClassName(), fieldWrite.getFieldName() ) ); + if (!fieldWrite.getClassName().equals(className)) { + System.err.println(String.format("WARNING: illegal write to non-member field %s.%s", fieldWrite.getClassName(), fieldWrite.getFieldName())); return false; } // find the field FieldInfo fieldInfo = null; - for( FieldInfo info : (List)constructor.getDeclaringClass().getClassFile().getFields() ) - { - if( info.getName().equals( fieldWrite.getFieldName() ) && info.getDescriptor().equals( fieldWrite.getSignature() ) ) - { + for (FieldInfo info : (List)constructor.getDeclaringClass().getClassFile().getFields()) { + if (info.getName().equals(fieldWrite.getFieldName()) && info.getDescriptor().equals(fieldWrite.getSignature())) { fieldInfo = info; break; } } - if( fieldInfo == null ) - { + if (fieldInfo == null) { // field is in a superclass or something, can't be a local synthetic member return false; } // is this field synthetic? boolean isSynthetic = (fieldInfo.getAccessFlags() & AccessFlag.SYNTHETIC) != 0; - if( isSynthetic ) - { - syntheticFieldTypes.add( fieldInfo.getDescriptor() ); - } - else - { - System.err.println( String.format( "WARNING: illegal write to non synthetic field %s %s.%s", fieldInfo.getDescriptor(), className, fieldInfo.getName() ) ); + if (isSynthetic) { + syntheticFieldTypes.add(fieldInfo.getDescriptor()); + } else { + System.err.println(String.format("WARNING: illegal write to non synthetic field %s %s.%s", fieldInfo.getDescriptor(), className, fieldInfo.getName())); return false; } } @@ -612,56 +524,51 @@ public class JarIndex // we passed all the tests! return true; } - - private BehaviorEntry isAnonymousClass( CtClass c, String outerClassName ) - { - ClassEntry innerClassEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) ); + + private BehaviorEntry isAnonymousClass(CtClass c, String outerClassName) { + + ClassEntry innerClassEntry = new ClassEntry(Descriptor.toJvmName(c.getName())); // anonymous classes: - // can't be abstract - // have only one constructor - // it's called exactly once by the outer class - // the type the instance is assigned to can't be this type + // can't be abstract + // have only one constructor + // it's called exactly once by the outer class + // the type the instance is assigned to can't be this type // is abstract? - if( Modifier.isAbstract( c.getModifiers() ) ) - { + if (Modifier.isAbstract(c.getModifiers())) { return null; } // is there exactly one constructor? - if( c.getDeclaredConstructors().length != 1 ) - { + if (c.getDeclaredConstructors().length != 1) { return null; } CtConstructor constructor = c.getDeclaredConstructors()[0]; // is this constructor called exactly once? - ConstructorEntry constructorEntry = new ConstructorEntry( innerClassEntry, constructor.getMethodInfo().getDescriptor() ); - Collection> references = getBehaviorReferences( constructorEntry ); - if( references.size() != 1 ) - { + ConstructorEntry constructorEntry = new ConstructorEntry( + innerClassEntry, + constructor.getMethodInfo().getDescriptor() + ); + Collection> references = getBehaviorReferences(constructorEntry); + if (references.size() != 1) { return null; } // does the caller use this type? BehaviorEntry caller = references.iterator().next().context; - for( FieldEntry fieldEntry : getReferencedFields( caller ) ) - { - ClassEntry fieldClass = getFieldClass( fieldEntry ); - if( fieldClass != null && fieldClass.equals( innerClassEntry ) ) - { + for (FieldEntry fieldEntry : getReferencedFields(caller)) { + ClassEntry fieldClass = getFieldClass(fieldEntry); + if (fieldClass != null && fieldClass.equals(innerClassEntry)) { // caller references this type, so it can't be anonymous return null; } } - for( BehaviorEntry behaviorEntry : getReferencedBehaviors( caller ) ) - { + for (BehaviorEntry behaviorEntry : getReferencedBehaviors(caller)) { // get the class types from the signature - for( String className : SignatureUpdater.getClasses( behaviorEntry.getSignature() ) ) - { - if( className.equals( innerClassEntry.getName() ) ) - { + for (String className : SignatureUpdater.getClasses(behaviorEntry.getSignature())) { + if (className.equals(innerClassEntry.getName())) { // caller references this type, so it can't be anonymous return null; } @@ -670,330 +577,275 @@ public class JarIndex return caller; } - - public Set getObfClassEntries( ) - { + + public Set getObfClassEntries() { return m_obfClassEntries; } - public TranslationIndex getTranslationIndex( ) - { + public TranslationIndex getTranslationIndex() { return m_translationIndex; } - public Access getAccess( Entry entry ) - { - return m_access.get( entry ); + public Access getAccess(Entry entry) { + return m_access.get(entry); } - public ClassEntry getFieldClass( FieldEntry fieldEntry ) - { - return m_fieldClasses.get( fieldEntry ); + public ClassEntry getFieldClass(FieldEntry fieldEntry) { + return m_fieldClasses.get(fieldEntry); } - public ClassInheritanceTreeNode getClassInheritance( Translator deobfuscatingTranslator, ClassEntry obfClassEntry ) - { + public ClassInheritanceTreeNode getClassInheritance(Translator deobfuscatingTranslator, ClassEntry obfClassEntry) { + // get the root node List ancestry = Lists.newArrayList(); - ancestry.add( obfClassEntry.getName() ); - ancestry.addAll( m_translationIndex.getAncestry( obfClassEntry.getName() ) ); - ClassInheritanceTreeNode rootNode = new ClassInheritanceTreeNode( deobfuscatingTranslator, ancestry.get( ancestry.size() - 1 ) ); + ancestry.add(obfClassEntry.getName()); + ancestry.addAll(m_translationIndex.getAncestry(obfClassEntry.getName())); + ClassInheritanceTreeNode rootNode = new ClassInheritanceTreeNode( + deobfuscatingTranslator, + ancestry.get(ancestry.size() - 1) + ); // expand all children recursively - rootNode.load( m_translationIndex, true ); + rootNode.load(m_translationIndex, true); return rootNode; } - public ClassImplementationsTreeNode getClassImplementations( Translator deobfuscatingTranslator, ClassEntry obfClassEntry ) - { + public ClassImplementationsTreeNode getClassImplementations(Translator deobfuscatingTranslator, ClassEntry obfClassEntry) { + // is this even an interface? - if( isInterface( obfClassEntry.getClassName() ) ) - { - ClassImplementationsTreeNode node = new ClassImplementationsTreeNode( deobfuscatingTranslator, obfClassEntry ); - node.load( this ); + if (isInterface(obfClassEntry.getClassName())) { + ClassImplementationsTreeNode node = new ClassImplementationsTreeNode(deobfuscatingTranslator, obfClassEntry); + node.load(this); return node; } return null; } - public MethodInheritanceTreeNode getMethodInheritance( Translator deobfuscatingTranslator, MethodEntry obfMethodEntry ) - { + public MethodInheritanceTreeNode getMethodInheritance(Translator deobfuscatingTranslator, MethodEntry obfMethodEntry) { + // travel to the ancestor implementation String baseImplementationClassName = obfMethodEntry.getClassName(); - for( String ancestorClassName : m_translationIndex.getAncestry( obfMethodEntry.getClassName() ) ) - { + for (String ancestorClassName : m_translationIndex.getAncestry(obfMethodEntry.getClassName())) { MethodEntry ancestorMethodEntry = new MethodEntry( - new ClassEntry( ancestorClassName ), + new ClassEntry(ancestorClassName), obfMethodEntry.getName(), obfMethodEntry.getSignature() ); - if( containsObfBehavior( ancestorMethodEntry ) ) - { + if (containsObfBehavior(ancestorMethodEntry)) { baseImplementationClassName = ancestorClassName; } } // make a root node at the base MethodEntry methodEntry = new MethodEntry( - new ClassEntry( baseImplementationClassName ), + new ClassEntry(baseImplementationClassName), obfMethodEntry.getName(), obfMethodEntry.getSignature() ); MethodInheritanceTreeNode rootNode = new MethodInheritanceTreeNode( deobfuscatingTranslator, methodEntry, - containsObfBehavior( methodEntry ) + containsObfBehavior(methodEntry) ); // expand the full tree - rootNode.load( this, true ); + rootNode.load(this, true); return rootNode; } - public MethodImplementationsTreeNode getMethodImplementations( Translator deobfuscatingTranslator, MethodEntry obfMethodEntry ) - { + public MethodImplementationsTreeNode getMethodImplementations(Translator deobfuscatingTranslator, MethodEntry obfMethodEntry) { + MethodEntry interfaceMethodEntry; // is this method on an interface? - if( isInterface( obfMethodEntry.getClassName() ) ) - { + if (isInterface(obfMethodEntry.getClassName())) { interfaceMethodEntry = obfMethodEntry; - } - else - { + } else { // get the interface class List methodInterfaces = Lists.newArrayList(); - for( String interfaceName : getInterfaces( obfMethodEntry.getClassName() ) ) - { + for (String interfaceName : getInterfaces(obfMethodEntry.getClassName())) { // is this method defined in this interface? MethodEntry methodInterface = new MethodEntry( - new ClassEntry( interfaceName ), + new ClassEntry(interfaceName), obfMethodEntry.getName(), obfMethodEntry.getSignature() ); - if( containsObfBehavior( methodInterface ) ) - { - methodInterfaces.add( methodInterface ); + if (containsObfBehavior(methodInterface)) { + methodInterfaces.add(methodInterface); } } - if( methodInterfaces.isEmpty() ) - { + if (methodInterfaces.isEmpty()) { return null; } - if( methodInterfaces.size() > 1 ) - { - throw new Error( "Too many interfaces define this method! This is not yet supported by Enigma!" ); + if (methodInterfaces.size() > 1) { + throw new Error("Too many interfaces define this method! This is not yet supported by Enigma!"); } - interfaceMethodEntry = methodInterfaces.get( 0 ); + interfaceMethodEntry = methodInterfaces.get(0); } - MethodImplementationsTreeNode rootNode = new MethodImplementationsTreeNode( deobfuscatingTranslator, interfaceMethodEntry ); - rootNode.load( this ); + MethodImplementationsTreeNode rootNode = new MethodImplementationsTreeNode(deobfuscatingTranslator, interfaceMethodEntry); + rootNode.load(this); return rootNode; } - public Set getRelatedMethodImplementations( MethodEntry obfMethodEntry ) - { + public Set getRelatedMethodImplementations(MethodEntry obfMethodEntry) { Set methodEntries = Sets.newHashSet(); - getRelatedMethodImplementations( methodEntries, getMethodInheritance( null, obfMethodEntry ) ); + getRelatedMethodImplementations(methodEntries, getMethodInheritance(null, obfMethodEntry)); return methodEntries; } - private void getRelatedMethodImplementations( Set methodEntries, MethodInheritanceTreeNode node ) - { + private void getRelatedMethodImplementations(Set methodEntries, MethodInheritanceTreeNode node) { MethodEntry methodEntry = node.getMethodEntry(); - if( containsObfBehavior( methodEntry ) ) - { + if (containsObfBehavior(methodEntry)) { // collect the entry - methodEntries.add( methodEntry ); + methodEntries.add(methodEntry); } // look at interface methods too - MethodImplementationsTreeNode implementations = getMethodImplementations( null, methodEntry ); - if( implementations != null ) - { - getRelatedMethodImplementations( methodEntries, implementations ); + MethodImplementationsTreeNode implementations = getMethodImplementations(null, methodEntry); + if (implementations != null) { + getRelatedMethodImplementations(methodEntries, implementations); } // recurse - for( int i=0; i methodEntries, MethodImplementationsTreeNode node ) - { + private void getRelatedMethodImplementations(Set methodEntries, MethodImplementationsTreeNode node) { MethodEntry methodEntry = node.getMethodEntry(); - if( containsObfBehavior( methodEntry ) ) - { + if (containsObfBehavior(methodEntry)) { // collect the entry - methodEntries.add( methodEntry ); + methodEntries.add(methodEntry); } // recurse - for( int i=0; i> getFieldReferences( FieldEntry fieldEntry ) - { - return m_fieldReferences.get( fieldEntry ); + + public Collection> getFieldReferences(FieldEntry fieldEntry) { + return m_fieldReferences.get(fieldEntry); } - public Collection getReferencedFields( BehaviorEntry behaviorEntry ) - { + public Collection getReferencedFields(BehaviorEntry behaviorEntry) { // linear search is fast enough for now Set fieldEntries = Sets.newHashSet(); - for( EntryReference reference : m_fieldReferences.values() ) - { - if( reference.context == behaviorEntry ) - { - fieldEntries.add( reference.entry ); + for (EntryReference reference : m_fieldReferences.values()) { + if (reference.context == behaviorEntry) { + fieldEntries.add(reference.entry); } } return fieldEntries; } - public Collection> getBehaviorReferences( BehaviorEntry behaviorEntry ) - { - return m_behaviorReferences.get( behaviorEntry ); + public Collection> getBehaviorReferences(BehaviorEntry behaviorEntry) { + return m_behaviorReferences.get(behaviorEntry); } - - public Collection getReferencedBehaviors( BehaviorEntry behaviorEntry ) - { + + public Collection getReferencedBehaviors(BehaviorEntry behaviorEntry) { // linear search is fast enough for now Set behaviorEntries = Sets.newHashSet(); - for( EntryReference reference : m_behaviorReferences.values() ) - { - if( reference.context == behaviorEntry ) - { - behaviorEntries.add( reference.entry ); + for (EntryReference reference : m_behaviorReferences.values()) { + if (reference.context == behaviorEntry) { + behaviorEntries.add(reference.entry); } } return behaviorEntries; } - public Collection getInnerClasses( String obfOuterClassName ) - { - return m_innerClasses.get( obfOuterClassName ); + public Collection getInnerClasses(String obfOuterClassName) { + return m_innerClasses.get(obfOuterClassName); } - public String getOuterClass( String obfInnerClassName ) - { + public String getOuterClass(String obfInnerClassName) { // make sure we use the right name - if( new ClassEntry( obfInnerClassName ).getPackageName() != null ) - { - throw new IllegalArgumentException( "Don't reference obfuscated inner classes using packages: " + obfInnerClassName ); + if (new ClassEntry(obfInnerClassName).getPackageName() != null) { + throw new IllegalArgumentException("Don't reference obfuscated inner classes using packages: " + obfInnerClassName); } - return m_outerClasses.get( obfInnerClassName ); + return m_outerClasses.get(obfInnerClassName); } - public boolean isAnonymousClass( String obfInnerClassName ) - { - return m_anonymousClasses.containsKey( obfInnerClassName ); + public boolean isAnonymousClass(String obfInnerClassName) { + return m_anonymousClasses.containsKey(obfInnerClassName); } - public BehaviorEntry getAnonymousClassCaller( String obfInnerClassName ) - { - return m_anonymousClasses.get( obfInnerClassName ); + public BehaviorEntry getAnonymousClassCaller(String obfInnerClassName) { + return m_anonymousClasses.get(obfInnerClassName); } - public Set getInterfaces( String className ) - { + public Set getInterfaces(String className) { Set interfaceNames = new HashSet(); - interfaceNames.addAll( m_interfaces.get( className ) ); - for( String ancestor : m_translationIndex.getAncestry( className ) ) - { - interfaceNames.addAll( m_interfaces.get( ancestor ) ); + interfaceNames.addAll(m_interfaces.get(className)); + for (String ancestor : m_translationIndex.getAncestry(className)) { + interfaceNames.addAll(m_interfaces.get(ancestor)); } return interfaceNames; } - public Set getImplementingClasses( String targetInterfaceName ) - { + public Set getImplementingClasses(String targetInterfaceName) { // linear search is fast enough for now Set classNames = Sets.newHashSet(); - for( Map.Entry entry : m_interfaces.entries() ) - { + for (Map.Entry entry : m_interfaces.entries()) { String className = entry.getKey(); String interfaceName = entry.getValue(); - if( interfaceName.equals( targetInterfaceName ) ) - { - classNames.add( className ); - m_translationIndex.getSubclassNamesRecursively( classNames, className ); + if (interfaceName.equals(targetInterfaceName)) { + classNames.add(className); + m_translationIndex.getSubclassNamesRecursively(classNames, className); } } return classNames; } - public boolean isInterface( String className ) - { - return m_interfaces.containsValue( className ); + public boolean isInterface(String className) { + return m_interfaces.containsValue(className); } - public MethodEntry getBridgeMethod( MethodEntry methodEntry ) - { - return m_bridgeMethods.get( methodEntry ); + public MethodEntry getBridgeMethod(MethodEntry methodEntry) { + return m_bridgeMethods.get(methodEntry); } - public boolean containsObfClass( ClassEntry obfClassEntry ) - { - return m_obfClassEntries.contains( obfClassEntry ); + public boolean containsObfClass(ClassEntry obfClassEntry) { + return m_obfClassEntries.contains(obfClassEntry); } - - public boolean containsObfField( FieldEntry obfFieldEntry ) - { - return m_access.containsKey( obfFieldEntry ); + + public boolean containsObfField(FieldEntry obfFieldEntry) { + return m_access.containsKey(obfFieldEntry); } - - public boolean containsObfBehavior( BehaviorEntry obfBehaviorEntry ) - { - return m_access.containsKey( obfBehaviorEntry ); + + public boolean containsObfBehavior(BehaviorEntry obfBehaviorEntry) { + return m_access.containsKey(obfBehaviorEntry); } - public boolean containsObfArgument( ArgumentEntry obfArgumentEntry ) - { + public boolean containsObfArgument(ArgumentEntry obfArgumentEntry) { // check the behavior - if( !containsObfBehavior( obfArgumentEntry.getBehaviorEntry() ) ) - { + if (!containsObfBehavior(obfArgumentEntry.getBehaviorEntry())) { return false; } // check the argument - if( obfArgumentEntry.getIndex() >= Descriptor.numOfParameters( obfArgumentEntry.getBehaviorEntry().getSignature() ) ) - { + if (obfArgumentEntry.getIndex() >= Descriptor.numOfParameters(obfArgumentEntry.getBehaviorEntry().getSignature())) { return false; } return true; } - public boolean containsObfEntry( Entry obfEntry ) - { - if( obfEntry instanceof ClassEntry ) - { - return containsObfClass( (ClassEntry)obfEntry ); - } - else if( obfEntry instanceof FieldEntry ) - { - return containsObfField( (FieldEntry)obfEntry ); - } - else if( obfEntry instanceof BehaviorEntry ) - { - return containsObfBehavior( (BehaviorEntry)obfEntry ); - } - else if( obfEntry instanceof ArgumentEntry ) - { - return containsObfArgument( (ArgumentEntry)obfEntry ); - } - else - { - throw new Error( "Entry type not supported: " + obfEntry.getClass().getName() ); + public boolean containsObfEntry(Entry obfEntry) { + if (obfEntry instanceof ClassEntry) { + return containsObfClass((ClassEntry)obfEntry); + } else if (obfEntry instanceof FieldEntry) { + return containsObfField((FieldEntry)obfEntry); + } else if (obfEntry instanceof BehaviorEntry) { + return containsObfBehavior((BehaviorEntry)obfEntry); + } else if (obfEntry instanceof ArgumentEntry) { + return containsObfArgument((ArgumentEntry)obfEntry); + } else { + throw new Error("Entry type not supported: " + obfEntry.getClass().getName()); } } } diff --git a/src/cuchaz/enigma/analysis/MethodImplementationsTreeNode.java b/src/cuchaz/enigma/analysis/MethodImplementationsTreeNode.java index a050282..1009226 100644 --- a/src/cuchaz/enigma/analysis/MethodImplementationsTreeNode.java +++ b/src/cuchaz/enigma/analysis/MethodImplementationsTreeNode.java @@ -20,94 +20,78 @@ import cuchaz.enigma.mapping.ClassEntry; import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.Translator; -public class MethodImplementationsTreeNode extends DefaultMutableTreeNode -{ +public class MethodImplementationsTreeNode extends DefaultMutableTreeNode { + private static final long serialVersionUID = 3781080657461899915L; private Translator m_deobfuscatingTranslator; private MethodEntry m_entry; - public MethodImplementationsTreeNode( Translator deobfuscatingTranslator, MethodEntry entry ) - { - if( entry == null ) - { - throw new IllegalArgumentException( "entry cannot be null!" ); + public MethodImplementationsTreeNode(Translator deobfuscatingTranslator, MethodEntry entry) { + if (entry == null) { + throw new IllegalArgumentException("entry cannot be null!"); } m_deobfuscatingTranslator = deobfuscatingTranslator; m_entry = entry; } - public MethodEntry getMethodEntry( ) - { + public MethodEntry getMethodEntry() { return m_entry; } - public String getDeobfClassName( ) - { - return m_deobfuscatingTranslator.translateClass( m_entry.getClassName() ); + public String getDeobfClassName() { + return m_deobfuscatingTranslator.translateClass(m_entry.getClassName()); } - public String getDeobfMethodName( ) - { - return m_deobfuscatingTranslator.translate( m_entry ); + public String getDeobfMethodName() { + return m_deobfuscatingTranslator.translate(m_entry); } @Override - public String toString( ) - { + public String toString() { String className = getDeobfClassName(); - if( className == null ) - { + if (className == null) { className = m_entry.getClassName(); } String methodName = getDeobfMethodName(); - if( methodName == null ) - { + if (methodName == null) { methodName = m_entry.getName(); } return className + "." + methodName + "()"; } - public void load( JarIndex index ) - { + public void load(JarIndex index) { // get all method implementations List nodes = Lists.newArrayList(); - for( String implementingClassName : index.getImplementingClasses( m_entry.getClassName() ) ) - { + for (String implementingClassName : index.getImplementingClasses(m_entry.getClassName())) { MethodEntry methodEntry = new MethodEntry( - new ClassEntry( implementingClassName ), + new ClassEntry(implementingClassName), m_entry.getName(), m_entry.getSignature() ); - if( index.containsObfBehavior( methodEntry ) ) - { - nodes.add( new MethodImplementationsTreeNode( m_deobfuscatingTranslator, methodEntry ) ); + if (index.containsObfBehavior(methodEntry)) { + nodes.add(new MethodImplementationsTreeNode(m_deobfuscatingTranslator, methodEntry)); } } // add them to this node - for( MethodImplementationsTreeNode node : nodes ) - { - this.add( node ); + for (MethodImplementationsTreeNode node : nodes) { + this.add(node); } } - public static MethodImplementationsTreeNode findNode( MethodImplementationsTreeNode node, MethodEntry entry ) - { + public static MethodImplementationsTreeNode findNode(MethodImplementationsTreeNode node, MethodEntry entry) { // is this the node? - if( node.getMethodEntry().equals( entry ) ) - { + if (node.getMethodEntry().equals(entry)) { return node; } // recurse - for( int i=0; i nodes = Lists.newArrayList(); - for( String subclassName : index.getTranslationIndex().getSubclassNames( m_entry.getClassName() ) ) - { + for (String subclassName : index.getTranslationIndex().getSubclassNames(m_entry.getClassName())) { MethodEntry methodEntry = new MethodEntry( - new ClassEntry( subclassName ), + new ClassEntry(subclassName), m_entry.getName(), m_entry.getSignature() ); - nodes.add( new MethodInheritanceTreeNode( + nodes.add(new MethodInheritanceTreeNode( m_deobfuscatingTranslator, methodEntry, - index.containsObfBehavior( methodEntry ) - ) ); + index.containsObfBehavior(methodEntry) + )); } // add them to this node - for( MethodInheritanceTreeNode node : nodes ) - { - this.add( node ); + for (MethodInheritanceTreeNode node : nodes) { + this.add(node); } - if( recurse ) - { - for( MethodInheritanceTreeNode node : nodes ) - { - node.load( index, true ); + if (recurse) { + for (MethodInheritanceTreeNode node : nodes) { + node.load(index, true); } } } - public static MethodInheritanceTreeNode findNode( MethodInheritanceTreeNode node, MethodEntry entry ) - { + public static MethodInheritanceTreeNode findNode(MethodInheritanceTreeNode node, MethodEntry entry) { // is this the node? - if( node.getMethodEntry().equals( entry ) ) - { + if (node.getMethodEntry().equals(entry)) { return node; } // recurse - for( int i=0; i -{ +public interface ReferenceTreeNode { E getEntry(); EntryReference getReference(); } diff --git a/src/cuchaz/enigma/analysis/SourceIndex.java b/src/cuchaz/enigma/analysis/SourceIndex.java index 0e33de0..b43ab61 100644 --- a/src/cuchaz/enigma/analysis/SourceIndex.java +++ b/src/cuchaz/enigma/analysis/SourceIndex.java @@ -25,16 +25,15 @@ import com.strobel.decompiler.languages.java.ast.Identifier; import cuchaz.enigma.mapping.Entry; -public class SourceIndex -{ +public class SourceIndex { + private String m_source; private TreeMap> m_tokenToReference; private Multimap,Token> m_referenceToTokens; private Map m_declarationToToken; private List m_lineOffsets; - public SourceIndex( String source ) - { + public SourceIndex(String source) { m_source = source; m_tokenToReference = Maps.newTreeMap(); m_referenceToTokens = HashMultimap.create(); @@ -42,142 +41,119 @@ public class SourceIndex m_lineOffsets = Lists.newArrayList(); // count the lines - m_lineOffsets.add( 0 ); - for( int i=0; i= 0 ) - { + int pos = name.lastIndexOf('$'); + if (pos >= 0) { token.end -= pos + 1; } return token; } - public void addReference( AstNode node, Entry deobfEntry, Entry deobfContext ) - { - Token token = getToken( node ); - if( token != null ) - { - EntryReference deobfReference = new EntryReference( deobfEntry, token.text, deobfContext ); - m_tokenToReference.put( token, deobfReference ); - m_referenceToTokens.put( deobfReference, token ); + public void addReference(AstNode node, Entry deobfEntry, Entry deobfContext) { + Token token = getToken(node); + if (token != null) { + EntryReference deobfReference = new EntryReference(deobfEntry, token.text, deobfContext); + m_tokenToReference.put(token, deobfReference); + m_referenceToTokens.put(deobfReference, token); } } - public void addDeclaration( AstNode node, Entry deobfEntry ) - { - Token token = getToken( node ); - if( token != null ) - { - EntryReference reference = new EntryReference( deobfEntry, token.text ); - m_tokenToReference.put( token, reference ); - m_referenceToTokens.put( reference, token ); - m_declarationToToken.put( deobfEntry, token ); + public void addDeclaration(AstNode node, Entry deobfEntry) { + Token token = getToken(node); + if (token != null) { + EntryReference reference = new EntryReference(deobfEntry, token.text); + m_tokenToReference.put(token, reference); + m_referenceToTokens.put(reference, token); + m_declarationToToken.put(deobfEntry, token); } } - public Token getReferenceToken( int pos ) - { - Token token = m_tokenToReference.floorKey( new Token( pos, pos, null ) ); - if( token != null && token.contains( pos ) ) - { + public Token getReferenceToken(int pos) { + Token token = m_tokenToReference.floorKey(new Token(pos, pos, null)); + if (token != null && token.contains(pos)) { return token; } return null; } - public Collection getReferenceTokens( EntryReference deobfReference ) - { - return m_referenceToTokens.get( deobfReference ); + public Collection getReferenceTokens(EntryReference deobfReference) { + return m_referenceToTokens.get(deobfReference); } - public EntryReference getDeobfReference( Token token ) - { - if( token == null ) - { + public EntryReference getDeobfReference(Token token) { + if (token == null) { return null; } - return m_tokenToReference.get( token ); + return m_tokenToReference.get(token); } - public void replaceDeobfReference( Token token, EntryReference newDeobfReference ) - { - EntryReference oldDeobfReference = m_tokenToReference.get( token ); - m_tokenToReference.put( token, newDeobfReference ); - Collection tokens = m_referenceToTokens.get( oldDeobfReference ); - m_referenceToTokens.removeAll( oldDeobfReference ); - m_referenceToTokens.putAll( newDeobfReference, tokens ); + public void replaceDeobfReference(Token token, EntryReference newDeobfReference) { + EntryReference oldDeobfReference = m_tokenToReference.get(token); + m_tokenToReference.put(token, newDeobfReference); + Collection tokens = m_referenceToTokens.get(oldDeobfReference); + m_referenceToTokens.removeAll(oldDeobfReference); + m_referenceToTokens.putAll(newDeobfReference, tokens); } - public Iterable referenceTokens( ) - { + public Iterable referenceTokens() { return m_tokenToReference.keySet(); } - public Iterable declarationTokens( ) - { + public Iterable declarationTokens() { return m_declarationToToken.values(); } - public Token getDeclarationToken( Entry deobfEntry ) - { - return m_declarationToToken.get( deobfEntry ); + public Token getDeclarationToken(Entry deobfEntry) { + return m_declarationToToken.get(deobfEntry); } - public int getLineNumber( int pos ) - { + public int getLineNumber(int pos) { // line number is 1-based int line = 0; - for( Integer offset : m_lineOffsets ) - { - if( offset > pos ) - { + for (Integer offset : m_lineOffsets) { + if (offset > pos) { break; } line++; @@ -185,15 +161,13 @@ public class SourceIndex return line; } - public int getColumnNumber( int pos ) - { + public int getColumnNumber(int pos) { // column number is 1-based - return pos - m_lineOffsets.get( getLineNumber( pos ) - 1 ) + 1; + return pos - m_lineOffsets.get(getLineNumber(pos) - 1) + 1; } - - private int toPos( int line, int col ) - { + + private int toPos(int line, int col) { // line and col are 1-based - return m_lineOffsets.get( line - 1 ) + col - 1; + return m_lineOffsets.get(line - 1) + col - 1; } } diff --git a/src/cuchaz/enigma/analysis/SourceIndexBehaviorVisitor.java b/src/cuchaz/enigma/analysis/SourceIndexBehaviorVisitor.java index 7ffd170..43c1749 100644 --- a/src/cuchaz/enigma/analysis/SourceIndexBehaviorVisitor.java +++ b/src/cuchaz/enigma/analysis/SourceIndexBehaviorVisitor.java @@ -36,159 +36,128 @@ import cuchaz.enigma.mapping.ConstructorEntry; import cuchaz.enigma.mapping.FieldEntry; import cuchaz.enigma.mapping.MethodEntry; -public class SourceIndexBehaviorVisitor extends SourceIndexVisitor -{ +public class SourceIndexBehaviorVisitor extends SourceIndexVisitor { + private BehaviorEntry m_behaviorEntry; - public SourceIndexBehaviorVisitor( BehaviorEntry behaviorEntry ) - { + public SourceIndexBehaviorVisitor(BehaviorEntry behaviorEntry) { m_behaviorEntry = behaviorEntry; } @Override - public Void visitMethodDeclaration( MethodDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitMethodDeclaration(MethodDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitConstructorDeclaration( ConstructorDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitConstructorDeclaration(ConstructorDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitInvocationExpression( InvocationExpression node, SourceIndex index ) - { - MemberReference ref = node.getUserData( Keys.MEMBER_REFERENCE ); + public Void visitInvocationExpression(InvocationExpression node, SourceIndex index) { + MemberReference ref = node.getUserData(Keys.MEMBER_REFERENCE); // get the behavior entry - ClassEntry classEntry = new ClassEntry( ref.getDeclaringType().getInternalName() ); + ClassEntry classEntry = new ClassEntry(ref.getDeclaringType().getInternalName()); BehaviorEntry behaviorEntry = null; - if( ref instanceof MethodReference ) - { + if (ref instanceof MethodReference) { MethodReference methodRef = (MethodReference)ref; - if( methodRef.isConstructor() ) - { - behaviorEntry = new ConstructorEntry( classEntry, ref.getSignature() ); - } - else if( methodRef.isTypeInitializer() ) - { - behaviorEntry = new ConstructorEntry( classEntry ); - } - else - { - behaviorEntry = new MethodEntry( classEntry, ref.getName(), ref.getSignature() ); + if (methodRef.isConstructor()) { + behaviorEntry = new ConstructorEntry(classEntry, ref.getSignature()); + } else if (methodRef.isTypeInitializer()) { + behaviorEntry = new ConstructorEntry(classEntry); + } else { + behaviorEntry = new MethodEntry(classEntry, ref.getName(), ref.getSignature()); } } - if( behaviorEntry != null ) - { + if (behaviorEntry != null) { // get the node for the token AstNode tokenNode = null; - if( node.getTarget() instanceof MemberReferenceExpression ) - { + if (node.getTarget() instanceof MemberReferenceExpression) { tokenNode = ((MemberReferenceExpression)node.getTarget()).getMemberNameToken(); - } - else if( node.getTarget() instanceof SuperReferenceExpression ) - { + } else if (node.getTarget() instanceof SuperReferenceExpression) { tokenNode = node.getTarget(); - } - else if( node.getTarget() instanceof ThisReferenceExpression ) - { + } else if (node.getTarget() instanceof ThisReferenceExpression) { tokenNode = node.getTarget(); } - if( tokenNode != null ) - { - index.addReference( tokenNode, behaviorEntry, m_behaviorEntry ); + if (tokenNode != null) { + index.addReference(tokenNode, behaviorEntry, m_behaviorEntry); } } - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitMemberReferenceExpression( MemberReferenceExpression node, SourceIndex index ) - { - MemberReference ref = node.getUserData( Keys.MEMBER_REFERENCE ); - if( ref != null ) - { + public Void visitMemberReferenceExpression(MemberReferenceExpression node, SourceIndex index) { + MemberReference ref = node.getUserData(Keys.MEMBER_REFERENCE); + if (ref != null) { // make sure this is actually a field - if( ref.getSignature().indexOf( '(' ) >= 0 ) - { - throw new Error( "Expected a field here! got " + ref ); + if (ref.getSignature().indexOf('(') >= 0) { + throw new Error("Expected a field here! got " + ref); } - ClassEntry classEntry = new ClassEntry( ref.getDeclaringType().getInternalName() ); - FieldEntry fieldEntry = new FieldEntry( classEntry, ref.getName() ); - index.addReference( node.getMemberNameToken(), fieldEntry, m_behaviorEntry ); + ClassEntry classEntry = new ClassEntry(ref.getDeclaringType().getInternalName()); + FieldEntry fieldEntry = new FieldEntry(classEntry, ref.getName()); + index.addReference(node.getMemberNameToken(), fieldEntry, m_behaviorEntry); } - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitSimpleType( SimpleType node, SourceIndex index ) - { - TypeReference ref = node.getUserData( Keys.TYPE_REFERENCE ); - if( node.getIdentifierToken().getStartLocation() != TextLocation.EMPTY ) - { - ClassEntry classEntry = new ClassEntry( ref.getInternalName() ); - index.addReference( node.getIdentifierToken(), classEntry, m_behaviorEntry ); + public Void visitSimpleType(SimpleType node, SourceIndex index) { + TypeReference ref = node.getUserData(Keys.TYPE_REFERENCE); + if (node.getIdentifierToken().getStartLocation() != TextLocation.EMPTY) { + ClassEntry classEntry = new ClassEntry(ref.getInternalName()); + index.addReference(node.getIdentifierToken(), classEntry, m_behaviorEntry); } - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitParameterDeclaration( ParameterDeclaration node, SourceIndex index ) - { - ParameterDefinition def = node.getUserData( Keys.PARAMETER_DEFINITION ); - ClassEntry classEntry = new ClassEntry( def.getDeclaringType().getInternalName() ); + public Void visitParameterDeclaration(ParameterDeclaration node, SourceIndex index) { + ParameterDefinition def = node.getUserData(Keys.PARAMETER_DEFINITION); + ClassEntry classEntry = new ClassEntry(def.getDeclaringType().getInternalName()); MethodDefinition methodDef = (MethodDefinition)def.getMethod(); BehaviorEntry behaviorEntry; - if( methodDef.isConstructor() ) - { - behaviorEntry = new ConstructorEntry( classEntry, methodDef.getSignature() ); - } - else - { - behaviorEntry = new MethodEntry( classEntry, methodDef.getName(), methodDef.getSignature() ); + if (methodDef.isConstructor()) { + behaviorEntry = new ConstructorEntry(classEntry, methodDef.getSignature()); + } else { + behaviorEntry = new MethodEntry(classEntry, methodDef.getName(), methodDef.getSignature()); } - ArgumentEntry argumentEntry = new ArgumentEntry( behaviorEntry, def.getPosition(), node.getName() ); - index.addDeclaration( node.getNameToken(), argumentEntry ); + ArgumentEntry argumentEntry = new ArgumentEntry(behaviorEntry, def.getPosition(), node.getName()); + index.addDeclaration(node.getNameToken(), argumentEntry); - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitIdentifierExpression( IdentifierExpression node, SourceIndex index ) - { - MemberReference ref = node.getUserData( Keys.MEMBER_REFERENCE ); - if( ref != null ) - { - ClassEntry classEntry = new ClassEntry( ref.getDeclaringType().getInternalName() ); - FieldEntry fieldEntry = new FieldEntry( classEntry, ref.getName() ); - index.addReference( node.getIdentifierToken(), fieldEntry, m_behaviorEntry ); + public Void visitIdentifierExpression(IdentifierExpression node, SourceIndex index) { + MemberReference ref = node.getUserData(Keys.MEMBER_REFERENCE); + if (ref != null) { + ClassEntry classEntry = new ClassEntry(ref.getDeclaringType().getInternalName()); + FieldEntry fieldEntry = new FieldEntry(classEntry, ref.getName()); + index.addReference(node.getIdentifierToken(), fieldEntry, m_behaviorEntry); } - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitObjectCreationExpression( ObjectCreationExpression node, SourceIndex index ) - { - MemberReference ref = node.getUserData( Keys.MEMBER_REFERENCE ); - if( ref != null ) - { - ClassEntry classEntry = new ClassEntry( ref.getDeclaringType().getInternalName() ); - ConstructorEntry constructorEntry = new ConstructorEntry( classEntry, ref.getSignature() ); - if( node.getType() instanceof SimpleType ) - { + public Void visitObjectCreationExpression(ObjectCreationExpression node, SourceIndex index) { + MemberReference ref = node.getUserData(Keys.MEMBER_REFERENCE); + if (ref != null) { + ClassEntry classEntry = new ClassEntry(ref.getDeclaringType().getInternalName()); + ConstructorEntry constructorEntry = new ConstructorEntry(classEntry, ref.getSignature()); + if (node.getType() instanceof SimpleType) { SimpleType simpleTypeNode = (SimpleType)node.getType(); - index.addReference( simpleTypeNode.getIdentifierToken(), constructorEntry, m_behaviorEntry ); + index.addReference(simpleTypeNode.getIdentifierToken(), constructorEntry, m_behaviorEntry); } } - return recurse( node, index ); + return recurse(node, index); } } diff --git a/src/cuchaz/enigma/analysis/SourceIndexClassVisitor.java b/src/cuchaz/enigma/analysis/SourceIndexClassVisitor.java index 24c4822..7b902a9 100644 --- a/src/cuchaz/enigma/analysis/SourceIndexClassVisitor.java +++ b/src/cuchaz/enigma/analysis/SourceIndexClassVisitor.java @@ -31,95 +31,84 @@ import cuchaz.enigma.mapping.ClassEntry; import cuchaz.enigma.mapping.ConstructorEntry; import cuchaz.enigma.mapping.FieldEntry; -public class SourceIndexClassVisitor extends SourceIndexVisitor -{ +public class SourceIndexClassVisitor extends SourceIndexVisitor { + private ClassEntry m_classEntry; - public SourceIndexClassVisitor( ClassEntry classEntry ) - { + public SourceIndexClassVisitor(ClassEntry classEntry) { m_classEntry = classEntry; } @Override - public Void visitTypeDeclaration( TypeDeclaration node, SourceIndex index ) - { + public Void visitTypeDeclaration(TypeDeclaration node, SourceIndex index) { // is this this class, or a subtype? - TypeDefinition def = node.getUserData( Keys.TYPE_DEFINITION ); - ClassEntry classEntry = new ClassEntry( def.getInternalName() ); - if( !classEntry.equals( m_classEntry ) ) - { + TypeDefinition def = node.getUserData(Keys.TYPE_DEFINITION); + ClassEntry classEntry = new ClassEntry(def.getInternalName()); + if (!classEntry.equals(m_classEntry)) { // it's a sub-type, recurse - index.addDeclaration( node.getNameToken(), classEntry ); - return node.acceptVisitor( new SourceIndexClassVisitor( classEntry ), index ); + index.addDeclaration(node.getNameToken(), classEntry); + return node.acceptVisitor(new SourceIndexClassVisitor(classEntry), index); } - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitSimpleType( SimpleType node, SourceIndex index ) - { - TypeReference ref = node.getUserData( Keys.TYPE_REFERENCE ); - if( node.getIdentifierToken().getStartLocation() != TextLocation.EMPTY ) - { - ClassEntry classEntry = new ClassEntry( ref.getInternalName() ); - index.addReference( node.getIdentifierToken(), classEntry, m_classEntry ); + public Void visitSimpleType(SimpleType node, SourceIndex index) { + TypeReference ref = node.getUserData(Keys.TYPE_REFERENCE); + if (node.getIdentifierToken().getStartLocation() != TextLocation.EMPTY) { + ClassEntry classEntry = new ClassEntry(ref.getInternalName()); + index.addReference(node.getIdentifierToken(), classEntry, m_classEntry); } - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitMethodDeclaration( MethodDeclaration node, SourceIndex index ) - { - MethodDefinition def = node.getUserData( Keys.METHOD_DEFINITION ); - ClassEntry classEntry = new ClassEntry( def.getDeclaringType().getInternalName() ); - BehaviorEntry behaviorEntry = BehaviorEntryFactory.create( classEntry, def.getName(), def.getSignature() ); + public Void visitMethodDeclaration(MethodDeclaration node, SourceIndex index) { + MethodDefinition def = node.getUserData(Keys.METHOD_DEFINITION); + ClassEntry classEntry = new ClassEntry(def.getDeclaringType().getInternalName()); + BehaviorEntry behaviorEntry = BehaviorEntryFactory.create(classEntry, def.getName(), def.getSignature()); AstNode tokenNode = node.getNameToken(); - if( behaviorEntry instanceof ConstructorEntry ) - { + if (behaviorEntry instanceof ConstructorEntry) { ConstructorEntry constructorEntry = (ConstructorEntry)behaviorEntry; - if( constructorEntry.isStatic() ) - { + if (constructorEntry.isStatic()) { tokenNode = node.getModifiers().firstOrNullObject(); } } - index.addDeclaration( tokenNode, behaviorEntry ); - return node.acceptVisitor( new SourceIndexBehaviorVisitor( behaviorEntry ), index ); + index.addDeclaration(tokenNode, behaviorEntry); + return node.acceptVisitor(new SourceIndexBehaviorVisitor(behaviorEntry), index); } @Override - public Void visitConstructorDeclaration( ConstructorDeclaration node, SourceIndex index ) - { - MethodDefinition def = node.getUserData( Keys.METHOD_DEFINITION ); - ClassEntry classEntry = new ClassEntry( def.getDeclaringType().getInternalName() ); - ConstructorEntry constructorEntry = new ConstructorEntry( classEntry, def.getSignature() ); - index.addDeclaration( node.getNameToken(), constructorEntry ); - return node.acceptVisitor( new SourceIndexBehaviorVisitor( constructorEntry ), index ); + public Void visitConstructorDeclaration(ConstructorDeclaration node, SourceIndex index) { + MethodDefinition def = node.getUserData(Keys.METHOD_DEFINITION); + ClassEntry classEntry = new ClassEntry(def.getDeclaringType().getInternalName()); + ConstructorEntry constructorEntry = new ConstructorEntry(classEntry, def.getSignature()); + index.addDeclaration(node.getNameToken(), constructorEntry); + return node.acceptVisitor(new SourceIndexBehaviorVisitor(constructorEntry), index); } @Override - public Void visitFieldDeclaration( FieldDeclaration node, SourceIndex index ) - { - FieldDefinition def = node.getUserData( Keys.FIELD_DEFINITION ); - ClassEntry classEntry = new ClassEntry( def.getDeclaringType().getInternalName() ); - FieldEntry fieldEntry = new FieldEntry( classEntry, def.getName() ); - assert( node.getVariables().size() == 1 ); + public Void visitFieldDeclaration(FieldDeclaration node, SourceIndex index) { + FieldDefinition def = node.getUserData(Keys.FIELD_DEFINITION); + ClassEntry classEntry = new ClassEntry(def.getDeclaringType().getInternalName()); + FieldEntry fieldEntry = new FieldEntry(classEntry, def.getName()); + assert (node.getVariables().size() == 1); VariableInitializer variable = node.getVariables().firstOrNullObject(); - index.addDeclaration( variable.getNameToken(), fieldEntry ); + index.addDeclaration(variable.getNameToken(), fieldEntry); - return recurse( node, index ); + return recurse(node, index); } @Override - public Void visitEnumValueDeclaration( EnumValueDeclaration node, SourceIndex index ) - { + public Void visitEnumValueDeclaration(EnumValueDeclaration node, SourceIndex index) { // treat enum declarations as field declarations - FieldDefinition def = node.getUserData( Keys.FIELD_DEFINITION ); - ClassEntry classEntry = new ClassEntry( def.getDeclaringType().getInternalName() ); - FieldEntry fieldEntry = new FieldEntry( classEntry, def.getName() ); - index.addDeclaration( node.getNameToken(), fieldEntry ); + FieldDefinition def = node.getUserData(Keys.FIELD_DEFINITION); + ClassEntry classEntry = new ClassEntry(def.getDeclaringType().getInternalName()); + FieldEntry fieldEntry = new FieldEntry(classEntry, def.getName()); + index.addDeclaration(node.getNameToken(), fieldEntry); - return recurse( node, index ); + return recurse(node, index); } } diff --git a/src/cuchaz/enigma/analysis/SourceIndexVisitor.java b/src/cuchaz/enigma/analysis/SourceIndexVisitor.java index 4e98989..0d5bdc0 100644 --- a/src/cuchaz/enigma/analysis/SourceIndexVisitor.java +++ b/src/cuchaz/enigma/analysis/SourceIndexVisitor.java @@ -87,438 +87,366 @@ import com.strobel.decompiler.patterns.Pattern; import cuchaz.enigma.mapping.ClassEntry; -public class SourceIndexVisitor implements IAstVisitor -{ - @Override - public Void visitTypeDeclaration( TypeDeclaration node, SourceIndex index ) - { - TypeDefinition def = node.getUserData( Keys.TYPE_DEFINITION ); - ClassEntry classEntry = new ClassEntry( def.getInternalName() ); - index.addDeclaration( node.getNameToken(), classEntry ); +public class SourceIndexVisitor implements IAstVisitor { + + @Override + public Void visitTypeDeclaration(TypeDeclaration node, SourceIndex index) { + TypeDefinition def = node.getUserData(Keys.TYPE_DEFINITION); + ClassEntry classEntry = new ClassEntry(def.getInternalName()); + index.addDeclaration(node.getNameToken(), classEntry); - return node.acceptVisitor( new SourceIndexClassVisitor( classEntry ), index ); + return node.acceptVisitor(new SourceIndexClassVisitor(classEntry), index); } - protected Void recurse( AstNode node, SourceIndex index ) - { - for( final AstNode child : node.getChildren() ) - { - child.acceptVisitor( this, index ); + protected Void recurse(AstNode node, SourceIndex index) { + for (final AstNode child : node.getChildren()) { + child.acceptVisitor(this, index); } return null; } @Override - public Void visitMethodDeclaration( MethodDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitMethodDeclaration(MethodDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitConstructorDeclaration( ConstructorDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitConstructorDeclaration(ConstructorDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitFieldDeclaration( FieldDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitFieldDeclaration(FieldDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitEnumValueDeclaration( EnumValueDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitEnumValueDeclaration(EnumValueDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitParameterDeclaration( ParameterDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitParameterDeclaration(ParameterDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitInvocationExpression( InvocationExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitInvocationExpression(InvocationExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitMemberReferenceExpression( MemberReferenceExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitMemberReferenceExpression(MemberReferenceExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitSimpleType( SimpleType node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitSimpleType(SimpleType node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitIdentifierExpression( IdentifierExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitIdentifierExpression(IdentifierExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitComment( Comment node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitComment(Comment node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitPatternPlaceholder( AstNode node, Pattern pattern, SourceIndex index ) - { - return recurse( node, index ); + public Void visitPatternPlaceholder(AstNode node, Pattern pattern, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitTypeReference( TypeReferenceExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitTypeReference(TypeReferenceExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitJavaTokenNode( JavaTokenNode node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitJavaTokenNode(JavaTokenNode node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitIdentifier( Identifier node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitIdentifier(Identifier node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitNullReferenceExpression( NullReferenceExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitNullReferenceExpression(NullReferenceExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitThisReferenceExpression( ThisReferenceExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitThisReferenceExpression(ThisReferenceExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitSuperReferenceExpression( SuperReferenceExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitSuperReferenceExpression(SuperReferenceExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitClassOfExpression( ClassOfExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitClassOfExpression(ClassOfExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitBlockStatement( BlockStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitBlockStatement(BlockStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitExpressionStatement( ExpressionStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitExpressionStatement(ExpressionStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitBreakStatement( BreakStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitBreakStatement(BreakStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitContinueStatement( ContinueStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitContinueStatement(ContinueStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitDoWhileStatement( DoWhileStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitDoWhileStatement(DoWhileStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitEmptyStatement( EmptyStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitEmptyStatement(EmptyStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitIfElseStatement( IfElseStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitIfElseStatement(IfElseStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitLabelStatement( LabelStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitLabelStatement(LabelStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitLabeledStatement( LabeledStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitLabeledStatement(LabeledStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitReturnStatement( ReturnStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitReturnStatement(ReturnStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitSwitchStatement( SwitchStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitSwitchStatement(SwitchStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitSwitchSection( SwitchSection node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitSwitchSection(SwitchSection node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitCaseLabel( CaseLabel node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitCaseLabel(CaseLabel node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitThrowStatement( ThrowStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitThrowStatement(ThrowStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitCatchClause( CatchClause node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitCatchClause(CatchClause node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitAnnotation( Annotation node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitAnnotation(Annotation node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitNewLine( NewLineNode node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitNewLine(NewLineNode node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitVariableDeclaration( VariableDeclarationStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitVariableDeclaration(VariableDeclarationStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitVariableInitializer( VariableInitializer node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitVariableInitializer(VariableInitializer node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitText( TextNode node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitText(TextNode node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitImportDeclaration( ImportDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitImportDeclaration(ImportDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitInitializerBlock( InstanceInitializer node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitInitializerBlock(InstanceInitializer node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitTypeParameterDeclaration( TypeParameterDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitTypeParameterDeclaration(TypeParameterDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitCompilationUnit( CompilationUnit node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitCompilationUnit(CompilationUnit node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitPackageDeclaration( PackageDeclaration node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitPackageDeclaration(PackageDeclaration node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitArraySpecifier( ArraySpecifier node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitArraySpecifier(ArraySpecifier node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitComposedType( ComposedType node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitComposedType(ComposedType node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitWhileStatement( WhileStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitWhileStatement(WhileStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitPrimitiveExpression( PrimitiveExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitPrimitiveExpression(PrimitiveExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitCastExpression( CastExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitCastExpression(CastExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitBinaryOperatorExpression( BinaryOperatorExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitBinaryOperatorExpression(BinaryOperatorExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitInstanceOfExpression( InstanceOfExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitInstanceOfExpression(InstanceOfExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitIndexerExpression( IndexerExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitIndexerExpression(IndexerExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitUnaryOperatorExpression( UnaryOperatorExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitUnaryOperatorExpression(UnaryOperatorExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitConditionalExpression( ConditionalExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitConditionalExpression(ConditionalExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitArrayInitializerExpression( ArrayInitializerExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitArrayInitializerExpression(ArrayInitializerExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitObjectCreationExpression( ObjectCreationExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitObjectCreationExpression(ObjectCreationExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitArrayCreationExpression( ArrayCreationExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitArrayCreationExpression(ArrayCreationExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitAssignmentExpression( AssignmentExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitAssignmentExpression(AssignmentExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitForStatement( ForStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitForStatement(ForStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitForEachStatement( ForEachStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitForEachStatement(ForEachStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitTryCatchStatement( TryCatchStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitTryCatchStatement(TryCatchStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitGotoStatement( GotoStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitGotoStatement(GotoStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitParenthesizedExpression( ParenthesizedExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitParenthesizedExpression(ParenthesizedExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitSynchronizedStatement( SynchronizedStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitSynchronizedStatement(SynchronizedStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitAnonymousObjectCreationExpression( AnonymousObjectCreationExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitAnonymousObjectCreationExpression(AnonymousObjectCreationExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitWildcardType( WildcardType node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitWildcardType(WildcardType node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitMethodGroupExpression( MethodGroupExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitMethodGroupExpression(MethodGroupExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitAssertStatement( AssertStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitAssertStatement(AssertStatement node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitLambdaExpression( LambdaExpression node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitLambdaExpression(LambdaExpression node, SourceIndex index) { + return recurse(node, index); } @Override - public Void visitLocalTypeDeclarationStatement( LocalTypeDeclarationStatement node, SourceIndex index ) - { - return recurse( node, index ); + public Void visitLocalTypeDeclarationStatement(LocalTypeDeclarationStatement node, SourceIndex index) { + return recurse(node, index); } } diff --git a/src/cuchaz/enigma/analysis/Token.java b/src/cuchaz/enigma/analysis/Token.java index 5e70db7..481d2f4 100644 --- a/src/cuchaz/enigma/analysis/Token.java +++ b/src/cuchaz/enigma/analysis/Token.java @@ -10,56 +10,47 @@ ******************************************************************************/ package cuchaz.enigma.analysis; -public class Token implements Comparable -{ +public class Token implements Comparable { + public int start; public int end; public String text; - public Token( int start, int end ) - { - this( start, end, null ); + public Token(int start, int end) { + this(start, end, null); } - public Token( int start, int end, String source ) - { + public Token(int start, int end, String source) { this.start = start; this.end = end; - if( source != null ) - { - this.text = source.substring( start, end ); + if (source != null) { + this.text = source.substring(start, end); } } - public boolean contains( int pos ) - { + public boolean contains(int pos) { return pos >= start && pos <= end; } - + @Override - public int compareTo( Token other ) - { + public int compareTo(Token other) { return start - other.start; } @Override - public boolean equals( Object other ) - { - if( other instanceof Token ) - { - return equals( (Token)other ); + public boolean equals(Object other) { + if (other instanceof Token) { + return equals((Token)other); } return false; } - public boolean equals( Token other ) - { + public boolean equals(Token other) { return start == other.start && end == other.end; } @Override - public String toString( ) - { - return String.format( "[%d,%d]", start, end ); + public String toString() { + return String.format("[%d,%d]", start, end); } } diff --git a/src/cuchaz/enigma/analysis/TranslationIndex.java b/src/cuchaz/enigma/analysis/TranslationIndex.java index 5311ec7..c14fd59 100644 --- a/src/cuchaz/enigma/analysis/TranslationIndex.java +++ b/src/cuchaz/enigma/analysis/TranslationIndex.java @@ -23,104 +23,85 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; -public class TranslationIndex implements Serializable -{ +public class TranslationIndex implements Serializable { + private static final long serialVersionUID = 738687982126844179L; private Map m_superclasses; private Multimap m_fields; - public TranslationIndex( ) - { + public TranslationIndex() { m_superclasses = Maps.newHashMap(); m_fields = HashMultimap.create(); } - public TranslationIndex( TranslationIndex other ) - { - m_superclasses = Maps.newHashMap( other.m_superclasses ); - m_fields = HashMultimap.create( other.m_fields ); + public TranslationIndex(TranslationIndex other) { + m_superclasses = Maps.newHashMap(other.m_superclasses); + m_fields = HashMultimap.create(other.m_fields); } - public void addSuperclass( String className, String superclassName ) - { - className = Descriptor.toJvmName( className ); - superclassName = Descriptor.toJvmName( superclassName ); + public void addSuperclass(String className, String superclassName) { + className = Descriptor.toJvmName(className); + superclassName = Descriptor.toJvmName(superclassName); - if( className.equals( superclassName ) ) - { - throw new IllegalArgumentException( "Class cannot be its own superclass! " + className ); + if (className.equals(superclassName)) { + throw new IllegalArgumentException("Class cannot be its own superclass! " + className); } - if( !isJre( className ) && !isJre( superclassName ) ) - { - m_superclasses.put( className, superclassName ); + if (!isJre(className) && !isJre(superclassName)) { + m_superclasses.put(className, superclassName); } } - public void addField( String className, String fieldName ) - { - m_fields.put( className, fieldName ); + public void addField(String className, String fieldName) { + m_fields.put(className, fieldName); } - public void renameClasses( Map renames ) - { - EntryRenamer.renameClassesInMap( renames, m_superclasses ); - EntryRenamer.renameClassesInMultimap( renames, m_fields ); + public void renameClasses(Map renames) { + EntryRenamer.renameClassesInMap(renames, m_superclasses); + EntryRenamer.renameClassesInMultimap(renames, m_fields); } - public String getSuperclassName( String className ) - { - return m_superclasses.get( className ); + public String getSuperclassName(String className) { + return m_superclasses.get(className); } - public List getAncestry( String className ) - { + public List getAncestry(String className) { List ancestors = new ArrayList(); - while( className != null ) - { - className = getSuperclassName( className ); - if( className != null ) - { - ancestors.add( className ); + while (className != null) { + className = getSuperclassName(className); + if (className != null) { + ancestors.add(className); } } return ancestors; } - public List getSubclassNames( String className ) - { + public List getSubclassNames(String className) { // linear search is fast enough for now List subclasses = Lists.newArrayList(); - for( Map.Entry entry : m_superclasses.entrySet() ) - { + for (Map.Entry entry : m_superclasses.entrySet()) { String subclass = entry.getKey(); String superclass = entry.getValue(); - if( className.equals( superclass ) ) - { - subclasses.add( subclass ); + if (className.equals(superclass)) { + subclasses.add(subclass); } } return subclasses; } - public void getSubclassNamesRecursively( Set out, String className ) - { - for( String subclassName : getSubclassNames( className ) ) - { - out.add( subclassName ); - getSubclassNamesRecursively( out, subclassName ); + public void getSubclassNamesRecursively(Set out, String className) { + for (String subclassName : getSubclassNames(className)) { + out.add(subclassName); + getSubclassNamesRecursively(out, subclassName); } } - public boolean containsField( String className, String fieldName ) - { - return m_fields.containsEntry( className, fieldName ); + public boolean containsField(String className, String fieldName) { + return m_fields.containsEntry(className, fieldName); } - private boolean isJre( String className ) - { - return className.startsWith( "java/" ) - || className.startsWith( "javax/" ); + private boolean isJre(String className) { + return className.startsWith("java/") || className.startsWith("javax/"); } } diff --git a/src/cuchaz/enigma/analysis/TreeDumpVisitor.java b/src/cuchaz/enigma/analysis/TreeDumpVisitor.java index e6ecb10..23f8089 100644 --- a/src/cuchaz/enigma/analysis/TreeDumpVisitor.java +++ b/src/cuchaz/enigma/analysis/TreeDumpVisitor.java @@ -90,92 +90,73 @@ import com.strobel.decompiler.languages.java.ast.WhileStatement; import com.strobel.decompiler.languages.java.ast.WildcardType; import com.strobel.decompiler.patterns.Pattern; -public class TreeDumpVisitor implements IAstVisitor -{ +public class TreeDumpVisitor implements IAstVisitor { + private File m_file; private Writer m_out; - public TreeDumpVisitor( File file ) - { + public TreeDumpVisitor(File file) { m_file = file; m_out = null; } @Override - public Void visitCompilationUnit( CompilationUnit node, Void ignored ) - { - try - { - m_out = new FileWriter( m_file ); - recurse( node, ignored ); + public Void visitCompilationUnit(CompilationUnit node, Void ignored) { + try { + m_out = new FileWriter(m_file); + recurse(node, ignored); m_out.close(); return null; - } - catch( IOException ex ) - { - throw new Error( ex ); + } catch (IOException ex) { + throw new Error(ex); } } - - private Void recurse( AstNode node, Void ignored ) - { + + private Void recurse(AstNode node, Void ignored) { // show the tree - try - { - m_out.write( getIndent( node ) + node.getClass().getSimpleName() + " " + getText( node ) + " " + dumpUserData( node ) + " " + node.getRegion() + "\n" ); - } - catch( IOException ex ) - { - throw new Error( ex ); + try { + m_out.write(getIndent(node) + node.getClass().getSimpleName() + " " + getText(node) + " " + dumpUserData(node) + " " + node.getRegion() + "\n"); + } catch (IOException ex) { + throw new Error(ex); } // recurse - for( final AstNode child : node.getChildren() ) - { - child.acceptVisitor( this, ignored ); + for (final AstNode child : node.getChildren()) { + child.acceptVisitor(this, ignored); } return null; } - private String getText( AstNode node ) - { - if( node instanceof Identifier ) - { + private String getText(AstNode node) { + if (node instanceof Identifier) { return "\"" + ((Identifier)node).getName() + "\""; } return ""; } - private String dumpUserData( AstNode node ) - { + private String dumpUserData(AstNode node) { StringBuilder buf = new StringBuilder(); - for( Key key : Keys.ALL_KEYS ) - { - Object val = node.getUserData( key ); - if( val != null ) - { - buf.append( String.format( " [%s=%s]", key, val ) ); + for (Key key : Keys.ALL_KEYS) { + Object val = node.getUserData(key); + if (val != null) { + buf.append(String.format(" [%s=%s]", key, val)); } } return buf.toString(); } - private String getIndent( AstNode node ) - { + private String getIndent(AstNode node) { StringBuilder buf = new StringBuilder(); - int depth = getDepth( node ); - for( int i = 0; i < depth; i++ ) - { - buf.append( "\t" ); + int depth = getDepth(node); + for (int i = 0; i < depth; i++) { + buf.append("\t"); } return buf.toString(); } - private int getDepth( AstNode node ) - { + private int getDepth(AstNode node) { int depth = -1; - while( node != null ) - { + while (node != null) { depth++; node = node.getParent(); } @@ -185,416 +166,347 @@ public class TreeDumpVisitor implements IAstVisitor // OVERRIDES WE DON'T CARE ABOUT @Override - public Void visitInvocationExpression( InvocationExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitInvocationExpression(InvocationExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitMemberReferenceExpression( MemberReferenceExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitMemberReferenceExpression(MemberReferenceExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitSimpleType( SimpleType node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitSimpleType(SimpleType node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitMethodDeclaration( MethodDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitMethodDeclaration(MethodDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitConstructorDeclaration( ConstructorDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitConstructorDeclaration(ConstructorDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitParameterDeclaration( ParameterDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitParameterDeclaration(ParameterDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitFieldDeclaration( FieldDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitFieldDeclaration(FieldDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitTypeDeclaration( TypeDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitTypeDeclaration(TypeDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitComment( Comment node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitComment(Comment node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitPatternPlaceholder( AstNode node, Pattern pattern, Void ignored ) - { - return recurse( node, ignored ); + public Void visitPatternPlaceholder(AstNode node, Pattern pattern, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitTypeReference( TypeReferenceExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitTypeReference(TypeReferenceExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitJavaTokenNode( JavaTokenNode node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitJavaTokenNode(JavaTokenNode node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitIdentifier( Identifier node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitIdentifier(Identifier node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitNullReferenceExpression( NullReferenceExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitNullReferenceExpression(NullReferenceExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitThisReferenceExpression( ThisReferenceExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitThisReferenceExpression(ThisReferenceExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitSuperReferenceExpression( SuperReferenceExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitSuperReferenceExpression(SuperReferenceExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitClassOfExpression( ClassOfExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitClassOfExpression(ClassOfExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitBlockStatement( BlockStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitBlockStatement(BlockStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitExpressionStatement( ExpressionStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitExpressionStatement(ExpressionStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitBreakStatement( BreakStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitBreakStatement(BreakStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitContinueStatement( ContinueStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitContinueStatement(ContinueStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitDoWhileStatement( DoWhileStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitDoWhileStatement(DoWhileStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitEmptyStatement( EmptyStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitEmptyStatement(EmptyStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitIfElseStatement( IfElseStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitIfElseStatement(IfElseStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitLabelStatement( LabelStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitLabelStatement(LabelStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitLabeledStatement( LabeledStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitLabeledStatement(LabeledStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitReturnStatement( ReturnStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitReturnStatement(ReturnStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitSwitchStatement( SwitchStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitSwitchStatement(SwitchStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitSwitchSection( SwitchSection node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitSwitchSection(SwitchSection node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitCaseLabel( CaseLabel node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitCaseLabel(CaseLabel node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitThrowStatement( ThrowStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitThrowStatement(ThrowStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitCatchClause( CatchClause node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitCatchClause(CatchClause node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitAnnotation( Annotation node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitAnnotation(Annotation node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitNewLine( NewLineNode node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitNewLine(NewLineNode node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitVariableDeclaration( VariableDeclarationStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitVariableDeclaration(VariableDeclarationStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitVariableInitializer( VariableInitializer node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitVariableInitializer(VariableInitializer node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitText( TextNode node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitText(TextNode node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitImportDeclaration( ImportDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitImportDeclaration(ImportDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitInitializerBlock( InstanceInitializer node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitInitializerBlock(InstanceInitializer node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitTypeParameterDeclaration( TypeParameterDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitTypeParameterDeclaration(TypeParameterDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitPackageDeclaration( PackageDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitPackageDeclaration(PackageDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitArraySpecifier( ArraySpecifier node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitArraySpecifier(ArraySpecifier node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitComposedType( ComposedType node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitComposedType(ComposedType node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitWhileStatement( WhileStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitWhileStatement(WhileStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitPrimitiveExpression( PrimitiveExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitPrimitiveExpression(PrimitiveExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitCastExpression( CastExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitCastExpression(CastExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitBinaryOperatorExpression( BinaryOperatorExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitBinaryOperatorExpression(BinaryOperatorExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitInstanceOfExpression( InstanceOfExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitInstanceOfExpression(InstanceOfExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitIndexerExpression( IndexerExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitIndexerExpression(IndexerExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitIdentifierExpression( IdentifierExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitIdentifierExpression(IdentifierExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitUnaryOperatorExpression( UnaryOperatorExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitUnaryOperatorExpression(UnaryOperatorExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitConditionalExpression( ConditionalExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitConditionalExpression(ConditionalExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitArrayInitializerExpression( ArrayInitializerExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitArrayInitializerExpression(ArrayInitializerExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitObjectCreationExpression( ObjectCreationExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitObjectCreationExpression(ObjectCreationExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitArrayCreationExpression( ArrayCreationExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitArrayCreationExpression(ArrayCreationExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitAssignmentExpression( AssignmentExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitAssignmentExpression(AssignmentExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitForStatement( ForStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitForStatement(ForStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitForEachStatement( ForEachStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitForEachStatement(ForEachStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitTryCatchStatement( TryCatchStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitTryCatchStatement(TryCatchStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitGotoStatement( GotoStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitGotoStatement(GotoStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitParenthesizedExpression( ParenthesizedExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitParenthesizedExpression(ParenthesizedExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitSynchronizedStatement( SynchronizedStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitSynchronizedStatement(SynchronizedStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitAnonymousObjectCreationExpression( AnonymousObjectCreationExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitAnonymousObjectCreationExpression(AnonymousObjectCreationExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitWildcardType( WildcardType node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitWildcardType(WildcardType node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitMethodGroupExpression( MethodGroupExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitMethodGroupExpression(MethodGroupExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitEnumValueDeclaration( EnumValueDeclaration node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitEnumValueDeclaration(EnumValueDeclaration node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitAssertStatement( AssertStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitAssertStatement(AssertStatement node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitLambdaExpression( LambdaExpression node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitLambdaExpression(LambdaExpression node, Void ignored) { + return recurse(node, ignored); } @Override - public Void visitLocalTypeDeclarationStatement( LocalTypeDeclarationStatement node, Void ignored ) - { - return recurse( node, ignored ); + public Void visitLocalTypeDeclarationStatement(LocalTypeDeclarationStatement node, Void ignored) { + return recurse(node, ignored); } } diff --git a/src/cuchaz/enigma/bytecode/BytecodeIndexIterator.java b/src/cuchaz/enigma/bytecode/BytecodeIndexIterator.java index aadbeb2..fc2bac3 100644 --- a/src/cuchaz/enigma/bytecode/BytecodeIndexIterator.java +++ b/src/cuchaz/enigma/bytecode/BytecodeIndexIterator.java @@ -18,67 +18,53 @@ import javassist.bytecode.CodeAttribute; import javassist.bytecode.CodeIterator; import javassist.bytecode.Opcode; -public class BytecodeIndexIterator implements Iterator -{ - public static class Index - { +public class BytecodeIndexIterator implements Iterator { + + public static class Index { + private CodeIterator m_iter; private int m_pos; private boolean m_isWide; - protected Index( CodeIterator iter, int pos, boolean isWide ) - { + protected Index(CodeIterator iter, int pos, boolean isWide) { m_iter = iter; m_pos = pos; m_isWide = isWide; } - public int getIndex( ) - { - if( m_isWide ) - { - return m_iter.s16bitAt( m_pos ); - } - else - { - return m_iter.byteAt( m_pos ); + public int getIndex() { + if (m_isWide) { + return m_iter.s16bitAt(m_pos); + } else { + return m_iter.byteAt(m_pos); } } - public void setIndex( int val ) - throws BadBytecode - { - if( m_isWide ) - { - m_iter.write16bit( val, m_pos ); - } - else - { - if( val < 256 ) - { + public void setIndex(int val) throws BadBytecode { + if (m_isWide) { + m_iter.write16bit(val, m_pos); + } else { + if (val < 256) { // we can write the byte - m_iter.writeByte( val, m_pos ); - } - else - { + m_iter.writeByte(val, m_pos); + } else { // we need to upgrade this instruction to LDC_W - assert( m_iter.byteAt( m_pos - 1 ) == Opcode.LDC ); - m_iter.insertGap( m_pos - 1, 1 ); - m_iter.writeByte( Opcode.LDC_W, m_pos - 1 ); - m_iter.write16bit( val, m_pos ); + assert (m_iter.byteAt(m_pos - 1) == Opcode.LDC); + m_iter.insertGap(m_pos - 1, 1); + m_iter.writeByte(Opcode.LDC_W, m_pos - 1); + m_iter.write16bit(val, m_pos); m_isWide = true; // move the iterator to the next opcode - m_iter.move( m_pos + 2 ); + m_iter.move(m_pos + 2); } } // sanity check - assert( val == getIndex() ); + assert (val == getIndex()); } - public boolean isValid( Bytecode bytecode ) - { + public boolean isValid(Bytecode bytecode) { return getIndex() >= 0 && getIndex() < bytecode.getConstPool().getSize(); } } @@ -88,9 +74,7 @@ public class BytecodeIndexIterator implements Iterator indices( ) - { - return new Iterable( ) - { + public Iterable indices() { + return new Iterable() { @Override - public Iterator iterator( ) - { + public Iterator iterator() { return BytecodeIndexIterator.this; } }; } - public void saveChangesToBytecode( ) - { - BytecodeTools.setBytecode( m_bytecode, m_attribute.getCode() ); + public void saveChangesToBytecode() { + BytecodeTools.setBytecode(m_bytecode, m_attribute.getCode()); } } diff --git a/src/cuchaz/enigma/bytecode/BytecodeTools.java b/src/cuchaz/enigma/bytecode/BytecodeTools.java index 4407a90..2e456f4 100644 --- a/src/cuchaz/enigma/bytecode/BytecodeTools.java +++ b/src/cuchaz/enigma/bytecode/BytecodeTools.java @@ -34,256 +34,222 @@ import cuchaz.enigma.Util; import cuchaz.enigma.bytecode.BytecodeIndexIterator.Index; import cuchaz.enigma.bytecode.accessors.ConstInfoAccessor; -public class BytecodeTools -{ - public static byte[] writeBytecode( Bytecode bytecode ) - throws IOException - { +public class BytecodeTools { + + public static byte[] writeBytecode(Bytecode bytecode) throws IOException { + ByteArrayOutputStream buf = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream( buf ); - try - { + DataOutputStream out = new DataOutputStream(buf); + + try { // write the constant pool - new ConstPoolEditor( bytecode.getConstPool() ).writePool( out ); + new ConstPoolEditor(bytecode.getConstPool()).writePool(out); // write metadata - out.writeShort( bytecode.getMaxStack() ); - out.writeShort( bytecode.getMaxLocals() ); - out.writeShort( bytecode.getStackDepth() ); + out.writeShort(bytecode.getMaxStack()); + out.writeShort(bytecode.getMaxLocals()); + out.writeShort(bytecode.getStackDepth()); // write the code - out.writeShort( bytecode.getSize() ); - out.write( bytecode.get() ); + out.writeShort(bytecode.getSize()); + out.write(bytecode.get()); // write the exception table int numEntries = bytecode.getExceptionTable().size(); - out.writeShort( numEntries ); - for( int i=0; i attribute.getMaxLocals() ) - { - attribute.setMaxLocals( bytecode.getMaxLocals() ); + if (bytecode.getMaxLocals() > attribute.getMaxLocals()) { + attribute.setMaxLocals(bytecode.getMaxLocals()); } - if( bytecode.getMaxStack() > attribute.getMaxStack() ) - { - attribute.setMaxStack( bytecode.getMaxStack() ); + if (bytecode.getMaxStack() > attribute.getMaxStack()) { + attribute.setMaxStack(bytecode.getMaxStack()); } return bytecode; } - public static Bytecode copyBytecodeToConstPool( ConstPool dest, Bytecode bytecode ) - throws BadBytecode - { + public static Bytecode copyBytecodeToConstPool(ConstPool dest, Bytecode bytecode) throws BadBytecode { + // get the entries this bytecode needs from the const pool Set indices = Sets.newTreeSet(); - ConstPoolEditor editor = new ConstPoolEditor( bytecode.getConstPool() ); - BytecodeIndexIterator iterator = new BytecodeIndexIterator( bytecode ); - for( Index index : iterator.indices() ) - { - assert( index.isValid( bytecode ) ); - InfoType.gatherIndexTree( indices, editor, index.getIndex() ); + ConstPoolEditor editor = new ConstPoolEditor(bytecode.getConstPool()); + BytecodeIndexIterator iterator = new BytecodeIndexIterator(bytecode); + for (Index index : iterator.indices()) { + assert (index.isValid(bytecode)); + InfoType.gatherIndexTree(indices, editor, index.getIndex()); } Map indexMap = Maps.newTreeMap(); ConstPool src = bytecode.getConstPool(); - ConstPoolEditor editorSrc = new ConstPoolEditor( src ); - ConstPoolEditor editorDest = new ConstPoolEditor( dest ); + ConstPoolEditor editorSrc = new ConstPoolEditor(src); + ConstPoolEditor editorDest = new ConstPoolEditor(dest); // copy entries over in order of level so the index mapping is easier - for( InfoType type : InfoType.getSortedByLevel() ) - { - for( int index : indices ) - { - ConstInfoAccessor entry = editorSrc.getItem( index ); + for (InfoType type : InfoType.getSortedByLevel()) { + for (int index : indices) { + ConstInfoAccessor entry = editorSrc.getItem(index); // skip entries that aren't this type - if( entry.getType() != type ) - { + if (entry.getType() != type) { continue; } // make sure the source entry is valid before we copy it - assert( type.subIndicesAreValid( entry, editorSrc ) ); - assert( type.selfIndexIsValid( entry, editorSrc ) ); + assert (type.subIndicesAreValid(entry, editorSrc)); + assert (type.selfIndexIsValid(entry, editorSrc)); // make a copy of the entry so we can modify it safely - ConstInfoAccessor entryCopy = editorSrc.getItem( index ).copy(); - assert( type.subIndicesAreValid( entryCopy, editorSrc ) ); - assert( type.selfIndexIsValid( entryCopy, editorSrc ) ); + ConstInfoAccessor entryCopy = editorSrc.getItem(index).copy(); + assert (type.subIndicesAreValid(entryCopy, editorSrc)); + assert (type.selfIndexIsValid(entryCopy, editorSrc)); // remap the indices - type.remapIndices( indexMap, entryCopy ); - assert( type.subIndicesAreValid( entryCopy, editorDest ) ); + type.remapIndices(indexMap, entryCopy); + assert (type.subIndicesAreValid(entryCopy, editorDest)); // put the copy in the destination pool - int newIndex = editorDest.addItem( entryCopy.getItem() ); - entryCopy.setIndex( newIndex ); - assert( type.selfIndexIsValid( entryCopy, editorDest ) ) : type + ", self: " + entryCopy + " dest: " + editorDest.getItem( entryCopy.getIndex() ); + int newIndex = editorDest.addItem(entryCopy.getItem()); + entryCopy.setIndex(newIndex); + assert (type.selfIndexIsValid(entryCopy, editorDest)) : type + ", self: " + entryCopy + " dest: " + editorDest.getItem(entryCopy.getIndex()); // make sure the source entry is unchanged - assert( type.subIndicesAreValid( entry, editorSrc ) ); - assert( type.selfIndexIsValid( entry, editorSrc ) ); + assert (type.subIndicesAreValid(entry, editorSrc)); + assert (type.selfIndexIsValid(entry, editorSrc)); // add the index mapping so we can update the bytecode later - if( indexMap.containsKey( index ) ) - { - throw new Error( "Entry at index " + index + " already copied!" ); + if (indexMap.containsKey(index)) { + throw new Error("Entry at index " + index + " already copied!"); } - indexMap.put( index, newIndex ); + indexMap.put(index, newIndex); } } // make a new bytecode - Bytecode newBytecode = new Bytecode( dest, bytecode.getMaxStack(), bytecode.getMaxLocals() ); - bytecode.setStackDepth( bytecode.getStackDepth() ); - setBytecode( newBytecode, bytecode.get() ); - setExceptionTable( newBytecode, bytecode.getExceptionTable() ); + Bytecode newBytecode = new Bytecode(dest, bytecode.getMaxStack(), bytecode.getMaxLocals()); + bytecode.setStackDepth(bytecode.getStackDepth()); + setBytecode(newBytecode, bytecode.get()); + setExceptionTable(newBytecode, bytecode.getExceptionTable()); // apply the mappings to the bytecode - BytecodeIndexIterator iter = new BytecodeIndexIterator( newBytecode ); - for( Index index : iter.indices() ) - { + BytecodeIndexIterator iter = new BytecodeIndexIterator(newBytecode); + for (Index index : iter.indices()) { int oldIndex = index.getIndex(); - Integer newIndex = indexMap.get( oldIndex ); - if( newIndex != null ) - { + Integer newIndex = indexMap.get(oldIndex); + if (newIndex != null) { // make sure this mapping makes sense - InfoType typeSrc = editorSrc.getItem( oldIndex ).getType(); - InfoType typeDest = editorDest.getItem( newIndex ).getType(); - assert( typeSrc == typeDest ); + InfoType typeSrc = editorSrc.getItem(oldIndex).getType(); + InfoType typeDest = editorDest.getItem(newIndex).getType(); + assert (typeSrc == typeDest); // apply the mapping - index.setIndex( newIndex ); + index.setIndex(newIndex); } } iter.saveChangesToBytecode(); // make sure all the indices are valid - iter = new BytecodeIndexIterator( newBytecode ); - for( Index index : iter.indices() ) - { - assert( index.isValid( newBytecode ) ); + iter = new BytecodeIndexIterator(newBytecode); + for (Index index : iter.indices()) { + assert (index.isValid(newBytecode)); } return newBytecode; } - public static void setBytecode( Bytecode dest, byte[] src ) - { - if( src.length > dest.getSize() ) - { - dest.addGap( src.length - dest.getSize() ); + public static void setBytecode(Bytecode dest, byte[] src) { + if (src.length > dest.getSize()) { + dest.addGap(src.length - dest.getSize()); } - assert( dest.getSize() == src.length ); - for( int i=0; i=0; i-- ) - { - dest.getExceptionTable().remove( i ); + for (int i = size - 1; i >= 0; i--) { + dest.getExceptionTable().remove(i); } // copy the exception table - for( int i=0; i getParameterTypes( String signature ) - { + public static List getParameterTypes(String signature) { List types = Lists.newArrayList(); - for( int i=0; i 0 ) - { + while (arrayDim-- > 0) { type = "[" + type; } - types.add( type ); + types.add(type); } return types; } diff --git a/src/cuchaz/enigma/bytecode/CheckCastIterator.java b/src/cuchaz/enigma/bytecode/CheckCastIterator.java index 7ed5d7f..b6efbd4 100644 --- a/src/cuchaz/enigma/bytecode/CheckCastIterator.java +++ b/src/cuchaz/enigma/bytecode/CheckCastIterator.java @@ -22,15 +22,14 @@ import cuchaz.enigma.bytecode.CheckCastIterator.CheckCast; import cuchaz.enigma.mapping.ClassEntry; import cuchaz.enigma.mapping.MethodEntry; -public class CheckCastIterator implements Iterator -{ - public static class CheckCast - { +public class CheckCastIterator implements Iterator { + + public static class CheckCast { + public String className; public MethodEntry prevMethodEntry; - public CheckCast( String className, MethodEntry prevMethodEntry ) - { + public CheckCast(String className, MethodEntry prevMethodEntry) { this.className = className; this.prevMethodEntry = prevMethodEntry; } @@ -41,9 +40,7 @@ public class CheckCastIterator implements Iterator private CodeIterator m_iter; private CheckCast m_next; - public CheckCastIterator( CodeAttribute codeAttribute ) - throws BadBytecode - { + public CheckCastIterator(CodeAttribute codeAttribute) throws BadBytecode { m_constants = codeAttribute.getConstPool(); m_attribute = codeAttribute; m_iter = m_attribute.iterator(); @@ -52,52 +49,38 @@ public class CheckCastIterator implements Iterator } @Override - public boolean hasNext( ) - { + public boolean hasNext() { return m_next != null; } - + @Override - public CheckCast next( ) - { + public CheckCast next() { CheckCast out = m_next; - try - { + try { m_next = getNext(); - } - catch( BadBytecode ex ) - { - throw new Error( ex ); + } catch (BadBytecode ex) { + throw new Error(ex); } return out; } - + @Override - public void remove( ) - { + public void remove() { throw new UnsupportedOperationException(); } - private CheckCast getNext( ) - throws BadBytecode - { + private CheckCast getNext() throws BadBytecode { int prevPos = 0; - while( m_iter.hasNext() ) - { + while (m_iter.hasNext()) { int pos = m_iter.next(); - int opcode = m_iter.byteAt( pos ); - switch( opcode ) - { + int opcode = m_iter.byteAt(pos); + switch (opcode) { case Opcode.CHECKCAST: // get the type of this op code (next two bytes are a classinfo index) - MethodEntry prevMethodEntry = getMethodEntry( prevPos ); - if( prevMethodEntry != null ) - { - return new CheckCast( - m_constants.getClassInfo( m_iter.s16bitAt( pos + 1 ) ), - prevMethodEntry - ); + MethodEntry prevMethodEntry = getMethodEntry(prevPos); + if (prevMethodEntry != null) { + return new CheckCast(m_constants.getClassInfo(m_iter.s16bitAt(pos + 1)), prevMethodEntry); } break; } @@ -106,43 +89,36 @@ public class CheckCastIterator implements Iterator return null; } - private MethodEntry getMethodEntry( int pos ) - { - switch( m_iter.byteAt( pos ) ) - { + private MethodEntry getMethodEntry(int pos) { + switch (m_iter.byteAt(pos)) { case Opcode.INVOKEVIRTUAL: case Opcode.INVOKESTATIC: case Opcode.INVOKEDYNAMIC: - case Opcode.INVOKESPECIAL: - { - int index = m_iter.s16bitAt( pos + 1 ); + case Opcode.INVOKESPECIAL: { + int index = m_iter.s16bitAt(pos + 1); return new MethodEntry( - new ClassEntry( Descriptor.toJvmName( m_constants.getMethodrefClassName( index ) ) ), - m_constants.getMethodrefName( index ), - m_constants.getMethodrefType( index ) + new ClassEntry(Descriptor.toJvmName(m_constants.getMethodrefClassName(index))), + m_constants.getMethodrefName(index), + m_constants.getMethodrefType(index) ); } - case Opcode.INVOKEINTERFACE: - { - int index = m_iter.s16bitAt( pos + 1 ); + case Opcode.INVOKEINTERFACE: { + int index = m_iter.s16bitAt(pos + 1); return new MethodEntry( - new ClassEntry( Descriptor.toJvmName( m_constants.getInterfaceMethodrefClassName( index ) ) ), - m_constants.getInterfaceMethodrefName( index ), - m_constants.getInterfaceMethodrefType( index ) + new ClassEntry(Descriptor.toJvmName(m_constants.getInterfaceMethodrefClassName(index))), + m_constants.getInterfaceMethodrefName(index), + m_constants.getInterfaceMethodrefType(index) ); } } return null; } - - public Iterable casts( ) - { - return new Iterable( ) - { + + public Iterable casts() { + return new Iterable() { @Override - public Iterator iterator( ) - { + public Iterator iterator() { return CheckCastIterator.this; } }; diff --git a/src/cuchaz/enigma/bytecode/ClassRenamer.java b/src/cuchaz/enigma/bytecode/ClassRenamer.java index 849a323..f8e63d1 100644 --- a/src/cuchaz/enigma/bytecode/ClassRenamer.java +++ b/src/cuchaz/enigma/bytecode/ClassRenamer.java @@ -27,55 +27,43 @@ import cuchaz.enigma.mapping.ClassEntry; import cuchaz.enigma.mapping.SignatureUpdater; import cuchaz.enigma.mapping.SignatureUpdater.ClassNameUpdater; -public class ClassRenamer -{ - public static void renameClasses( CtClass c, Map map ) - { +public class ClassRenamer { + + public static void renameClasses(CtClass c, Map map) { + // build the map used by javassist ClassMap nameMap = new ClassMap(); - for( Map.Entry entry : map.entrySet() ) - { - nameMap.put( entry.getKey().getName(), entry.getValue().getName() ); + for (Map.Entry entry : map.entrySet()) { + nameMap.put(entry.getKey().getName(), entry.getValue().getName()); } - c.replaceClassName( nameMap ); + c.replaceClassName(nameMap); // replace simple names in the InnerClasses attribute too ConstPool constants = c.getClassFile().getConstPool(); - InnerClassesAttribute attr = (InnerClassesAttribute)c.getClassFile().getAttribute( InnerClassesAttribute.tag ); - if( attr != null ) - { - for( int i=0; i ATTR: %s,%s,%s", - classEntry, - attr.outerClass( i ), - attr.innerClass( i ), - attr.innerName( i ) - ) ); + System.out.println(String.format("\tDEOBF: %s-> ATTR: %s,%s,%s", classEntry, attr.outerClass(i), attr.innerClass(i), attr.innerName(i))); */ } } } - public static Set getAllClassEntries( final CtClass c ) - { + public static Set getAllClassEntries(final CtClass c) { + // get the classes that javassist knows about final Set entries = Sets.newHashSet(); - ClassMap map = new ClassMap( ) - { + ClassMap map = new ClassMap() { @Override - public Object get( Object obj ) - { - if( obj instanceof String ) - { + public Object get(Object obj) { + if (obj instanceof String) { String str = (String)obj; // javassist throws a lot of weird things at this map @@ -83,69 +71,60 @@ public class ClassRenamer // I'm opting to filter out the weirdness for now // skip anything with generic arguments - if( str.indexOf( '<' ) >= 0 || str.indexOf( '>' ) >= 0 || str.indexOf( ';' ) >= 0 ) - { + if (str.indexOf('<') >= 0 || str.indexOf('>') >= 0 || str.indexOf(';') >= 0) { return null; } // convert path/to/class.inner to path/to/class$inner - str = str.replace( '.', '$' ); + str = str.replace('.', '$'); // remember everything else - entries.add( new ClassEntry( str ) ); + entries.add(new ClassEntry(str)); } return null; } + private static final long serialVersionUID = -202160293602070641L; }; - c.replaceClassName( map ); + c.replaceClassName(map); return entries; } - public static void moveAllClassesOutOfDefaultPackage( CtClass c, String newPackageName ) - { + public static void moveAllClassesOutOfDefaultPackage(CtClass c, String newPackageName) { + // rename all classes Map map = Maps.newHashMap(); - for( ClassEntry classEntry : ClassRenamer.getAllClassEntries( c ) ) - { - if( classEntry.isInDefaultPackage() ) - { - map.put( classEntry, new ClassEntry( newPackageName + "/" + classEntry.getName() ) ); + for (ClassEntry classEntry : ClassRenamer.getAllClassEntries(c)) { + if (classEntry.isInDefaultPackage()) { + map.put(classEntry, new ClassEntry(newPackageName + "/" + classEntry.getName())); } } - ClassRenamer.renameClasses( c, map ); + ClassRenamer.renameClasses(c, map); // TEMP - for( ClassEntry classEntry : ClassRenamer.getAllClassEntries( c ) ) - { - if( classEntry.isInDefaultPackage() ) - { - throw new Error( "!!! " + classEntry ); + for (ClassEntry classEntry : ClassRenamer.getAllClassEntries(c)) { + if (classEntry.isInDefaultPackage()) { + throw new Error("!!! " + classEntry); } } // TEMP - for( CtBehavior behavior : c.getDeclaredBehaviors() ) - { - if( behavior.getSignature() == null ) - { + for (CtBehavior behavior : c.getDeclaredBehaviors()) { + if (behavior.getSignature() == null) { continue; } - SignatureUpdater.update( behavior.getSignature(), new ClassNameUpdater( ) - { + SignatureUpdater.update(behavior.getSignature(), new ClassNameUpdater() { @Override - public String update( String className ) - { - ClassEntry classEntry = new ClassEntry( className ); - if( classEntry.isInDefaultPackage() ) - { - throw new Error( "!!! " + className ); + public String update(String className) { + ClassEntry classEntry = new ClassEntry(className); + if (classEntry.isInDefaultPackage()) { + throw new Error("!!! " + className); } return className; } - } ); + }); } } } diff --git a/src/cuchaz/enigma/bytecode/ClassTranslator.java b/src/cuchaz/enigma/bytecode/ClassTranslator.java index 181fadb..bc12405 100644 --- a/src/cuchaz/enigma/bytecode/ClassTranslator.java +++ b/src/cuchaz/enigma/bytecode/ClassTranslator.java @@ -28,116 +28,102 @@ import cuchaz.enigma.mapping.FieldEntry; import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.Translator; -public class ClassTranslator -{ +public class ClassTranslator { + private Translator m_translator; - public ClassTranslator( Translator translator ) - { + public ClassTranslator(Translator translator) { m_translator = translator; } - public void translate( CtClass c ) - { + public void translate(CtClass c) { // NOTE: the order of these translations is very important // translate all the field and method references in the code by editing the constant pool ConstPool constants = c.getClassFile().getConstPool(); - ConstPoolEditor editor = new ConstPoolEditor( constants ); - for( int i=1; i map = Maps.newHashMap(); - for( ClassEntry obfClassEntry : ClassRenamer.getAllClassEntries( c ) ) - { - ClassEntry deobfClassEntry = m_translator.translateEntry( obfClassEntry ); - if( !obfClassEntry.equals( deobfClassEntry ) ) - { - map.put( obfClassEntry, deobfClassEntry ); + for (ClassEntry obfClassEntry : ClassRenamer.getAllClassEntries(c)) { + ClassEntry deobfClassEntry = m_translator.translateEntry(obfClassEntry); + if (!obfClassEntry.equals(deobfClassEntry)) { + map.put(obfClassEntry, deobfClassEntry); } } - ClassRenamer.renameClasses( c, map ); + ClassRenamer.renameClasses(c, map); } } diff --git a/src/cuchaz/enigma/bytecode/ConstPoolEditor.java b/src/cuchaz/enigma/bytecode/ConstPoolEditor.java index aa6149c..2dec3b7 100644 --- a/src/cuchaz/enigma/bytecode/ConstPoolEditor.java +++ b/src/cuchaz/enigma/bytecode/ConstPoolEditor.java @@ -23,8 +23,8 @@ import cuchaz.enigma.bytecode.accessors.ClassInfoAccessor; import cuchaz.enigma.bytecode.accessors.ConstInfoAccessor; import cuchaz.enigma.bytecode.accessors.MemberRefInfoAccessor; -public class ConstPoolEditor -{ +public class ConstPoolEditor { + private static Method m_getItem; private static Method m_addItem; private static Method m_addItem0; @@ -36,264 +36,213 @@ public class ConstPoolEditor private static Method m_methodWritePool; private static Constructor m_constructorPool; - static - { - try - { - m_getItem = ConstPool.class.getDeclaredMethod( "getItem", int.class ); - m_getItem.setAccessible( true ); + static { + try { + m_getItem = ConstPool.class.getDeclaredMethod("getItem", int.class); + m_getItem.setAccessible(true); - m_addItem = ConstPool.class.getDeclaredMethod( "addItem", Class.forName( "javassist.bytecode.ConstInfo" ) ); - m_addItem.setAccessible( true ); + m_addItem = ConstPool.class.getDeclaredMethod("addItem", Class.forName("javassist.bytecode.ConstInfo")); + m_addItem.setAccessible(true); - m_addItem0 = ConstPool.class.getDeclaredMethod( "addItem0", Class.forName( "javassist.bytecode.ConstInfo" ) ); - m_addItem0.setAccessible( true ); + m_addItem0 = ConstPool.class.getDeclaredMethod("addItem0", Class.forName("javassist.bytecode.ConstInfo")); + m_addItem0.setAccessible(true); - m_items = ConstPool.class.getDeclaredField( "items" ); - m_items.setAccessible( true ); + m_items = ConstPool.class.getDeclaredField("items"); + m_items.setAccessible(true); - m_cache = ConstPool.class.getDeclaredField( "itemsCache" ); - m_cache.setAccessible( true ); + m_cache = ConstPool.class.getDeclaredField("itemsCache"); + m_cache.setAccessible(true); - m_numItems = ConstPool.class.getDeclaredField( "numOfItems" ); - m_numItems.setAccessible( true ); + m_numItems = ConstPool.class.getDeclaredField("numOfItems"); + m_numItems.setAccessible(true); - m_objects = Class.forName( "javassist.bytecode.LongVector" ).getDeclaredField( "objects" ); - m_objects.setAccessible( true ); + m_objects = Class.forName("javassist.bytecode.LongVector").getDeclaredField("objects"); + m_objects.setAccessible(true); - m_elements = Class.forName( "javassist.bytecode.LongVector" ).getDeclaredField( "elements" ); - m_elements.setAccessible( true ); + m_elements = Class.forName("javassist.bytecode.LongVector").getDeclaredField("elements"); + m_elements.setAccessible(true); - m_methodWritePool = ConstPool.class.getDeclaredMethod( "write", DataOutputStream.class ); - m_methodWritePool.setAccessible( true ); + m_methodWritePool = ConstPool.class.getDeclaredMethod("write", DataOutputStream.class); + m_methodWritePool.setAccessible(true); - m_constructorPool = ConstPool.class.getDeclaredConstructor( DataInputStream.class ); - m_constructorPool.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + m_constructorPool = ConstPool.class.getDeclaredConstructor(DataInputStream.class); + m_constructorPool.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } private ConstPool m_pool; - public ConstPoolEditor( ConstPool pool ) - { + public ConstPoolEditor(ConstPool pool) { m_pool = pool; } - public void writePool( DataOutputStream out ) - { - try - { - m_methodWritePool.invoke( m_pool, out ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void writePool(DataOutputStream out) { + try { + m_methodWritePool.invoke(m_pool, out); + } catch (Exception ex) { + throw new Error(ex); } } - public static ConstPool readPool( DataInputStream in ) - { - try - { - return m_constructorPool.newInstance( in ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public static ConstPool readPool(DataInputStream in) { + try { + return m_constructorPool.newInstance(in); + } catch (Exception ex) { + throw new Error(ex); } } - public String getMemberrefClassname( int memberrefIndex ) - { - return Descriptor.toJvmName( m_pool.getClassInfo( m_pool.getMemberClass( memberrefIndex ) ) ); + public String getMemberrefClassname(int memberrefIndex) { + return Descriptor.toJvmName(m_pool.getClassInfo(m_pool.getMemberClass(memberrefIndex))); } - public String getMemberrefName( int memberrefIndex ) - { - return m_pool.getUtf8Info( m_pool.getNameAndTypeName( m_pool.getMemberNameAndType( memberrefIndex ) ) ); + public String getMemberrefName(int memberrefIndex) { + return m_pool.getUtf8Info(m_pool.getNameAndTypeName(m_pool.getMemberNameAndType(memberrefIndex))); } - public String getMemberrefType( int memberrefIndex ) - { - return m_pool.getUtf8Info( m_pool.getNameAndTypeDescriptor( m_pool.getMemberNameAndType( memberrefIndex ) ) ); + public String getMemberrefType(int memberrefIndex) { + return m_pool.getUtf8Info(m_pool.getNameAndTypeDescriptor(m_pool.getMemberNameAndType(memberrefIndex))); } - public ConstInfoAccessor getItem( int index ) - { - try - { - Object entry = m_getItem.invoke( m_pool, index ); - if( entry == null ) - { + public ConstInfoAccessor getItem(int index) { + try { + Object entry = m_getItem.invoke(m_pool, index); + if (entry == null) { return null; } - return new ConstInfoAccessor( entry ); - } - catch( Exception ex ) - { - throw new Error( ex ); + return new ConstInfoAccessor(entry); + } catch (Exception ex) { + throw new Error(ex); } } - public int addItem( Object item ) - { - try - { - return (Integer)m_addItem.invoke( m_pool, item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int addItem(Object item) { + try { + return (Integer)m_addItem.invoke(m_pool, item); + } catch (Exception ex) { + throw new Error(ex); } } - public int addItemForceNew( Object item ) - { - try - { - return (Integer)m_addItem0.invoke( m_pool, item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int addItemForceNew(Object item) { + try { + return (Integer)m_addItem0.invoke(m_pool, item); + } catch (Exception ex) { + throw new Error(ex); } } - @SuppressWarnings( "rawtypes" ) - public void removeLastItem( ) - { - try - { + + @SuppressWarnings("rawtypes") + public void removeLastItem() { + try { // remove the item from the cache HashMap cache = getCache(); - if( cache != null ) - { - Object item = getItem( m_pool.getSize() - 1 ); - cache.remove( item ); + if (cache != null) { + Object item = getItem(m_pool.getSize() - 1); + cache.remove(item); } // remove the actual item // based off of LongVector.addElement() - Object items = m_items.get( m_pool ); - Object[][] objects = (Object[][])m_objects.get( items ); - int numElements = (Integer)m_elements.get( items ) - 1; + Object items = m_items.get(m_pool); + Object[][] objects = (Object[][])m_objects.get(items); + int numElements = (Integer)m_elements.get(items) - 1; int nth = numElements >> 7; - int offset = numElements & (128 - 1); - objects[nth][offset] = null; + int offset = numElements & (128 - 1); + objects[nth][offset] = null; // decrement the number of items - m_elements.set( items, numElements ); - m_numItems.set( m_pool, (Integer)m_numItems.get( m_pool ) - 1 ); - } - catch( Exception ex ) - { - throw new Error( ex ); + m_elements.set(items, numElements); + m_numItems.set(m_pool, (Integer)m_numItems.get(m_pool) - 1); + } catch (Exception ex) { + throw new Error(ex); } } - @SuppressWarnings( "rawtypes" ) - /* TEMP */public HashMap getCache( ) - { - try - { - return (HashMap)m_cache.get( m_pool ); - } - catch( Exception ex ) - { - throw new Error( ex ); + @SuppressWarnings("rawtypes") + public HashMap getCache() { + try { + return (HashMap)m_cache.get(m_pool); + } catch (Exception ex) { + throw new Error(ex); } } - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public void changeMemberrefNameAndType( int memberrefIndex, String newName, String newType ) - { + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void changeMemberrefNameAndType(int memberrefIndex, String newName, String newType) { // NOTE: when changing values, we always need to copy-on-write - try - { + try { // get the memberref item - Object item = getItem( memberrefIndex ).getItem(); + Object item = getItem(memberrefIndex).getItem(); // update the cache HashMap cache = getCache(); - if( cache != null ) - { - cache.remove( item ); + if (cache != null) { + cache.remove(item); } - new MemberRefInfoAccessor( item ).setNameAndTypeIndex( m_pool.addNameAndTypeInfo( newName, newType ) ); + new MemberRefInfoAccessor(item).setNameAndTypeIndex(m_pool.addNameAndTypeInfo(newName, newType)); // update the cache - if( cache != null ) - { - cache.put( item, item ); + if (cache != null) { + cache.put(item, item); } - } - catch( Exception ex ) - { - throw new Error( ex ); + } catch (Exception ex) { + throw new Error(ex); } // make sure the change worked - assert( newName.equals( getMemberrefName( memberrefIndex ) ) ); - assert( newType.equals( getMemberrefType( memberrefIndex ) ) ); + assert (newName.equals(getMemberrefName(memberrefIndex))); + assert (newType.equals(getMemberrefType(memberrefIndex))); } - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public void changeClassName( int classNameIndex, String newName ) - { + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void changeClassName(int classNameIndex, String newName) { // NOTE: when changing values, we always need to copy-on-write - try - { + try { // get the class item - Object item = getItem( classNameIndex ).getItem(); + Object item = getItem(classNameIndex).getItem(); // update the cache HashMap cache = getCache(); - if( cache != null ) - { - cache.remove( item ); + if (cache != null) { + cache.remove(item); } // add the new name and repoint the name-and-type to it - new ClassInfoAccessor( item ).setNameIndex( m_pool.addUtf8Info( newName ) ); + new ClassInfoAccessor(item).setNameIndex(m_pool.addUtf8Info(newName)); // update the cache - if( cache != null ) - { - cache.put( item, item ); + if (cache != null) { + cache.put(item, item); } - } - catch( Exception ex ) - { - throw new Error( ex ); + } catch (Exception ex) { + throw new Error(ex); } } - public static ConstPool newConstPool( ) - { + public static ConstPool newConstPool() { // const pool expects the name of a class to initialize itself // but we want an empty pool // so give it a bogus name, and then clear the entries afterwards - ConstPool pool = new ConstPool( "a" ); + ConstPool pool = new ConstPool("a"); - ConstPoolEditor editor = new ConstPoolEditor( pool ); + ConstPoolEditor editor = new ConstPoolEditor(pool); int size = pool.getSize(); - for( int i=0; i indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - ClassInfoAccessor accessor = new ClassInfoAccessor( entry.getItem() ); - gatherIndexTree( indices, editor, accessor.getNameIndex() ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + ClassInfoAccessor accessor = new ClassInfoAccessor(entry.getItem()); + gatherIndexTree(indices, editor, accessor.getNameIndex()); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - ClassInfoAccessor accessor = new ClassInfoAccessor( entry.getItem() ); - accessor.setNameIndex( remapIndex( map, accessor.getNameIndex() ) ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + ClassInfoAccessor accessor = new ClassInfoAccessor(entry.getItem()); + accessor.setNameIndex(remapIndex(map, accessor.getNameIndex())); } @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - ClassInfoAccessor accessor = new ClassInfoAccessor( entry.getItem() ); - ConstInfoAccessor nameEntry = pool.getItem( accessor.getNameIndex() ); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + ClassInfoAccessor accessor = new ClassInfoAccessor(entry.getItem()); + ConstInfoAccessor nameEntry = pool.getItem(accessor.getNameIndex()); return nameEntry != null && nameEntry.getTag() == Utf8Info.getTag(); } }, - StringInfo( 8, 1 ) - { + StringInfo( 8, 1 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - StringInfoAccessor accessor = new StringInfoAccessor( entry.getItem() ); - gatherIndexTree( indices, editor, accessor.getStringIndex() ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + StringInfoAccessor accessor = new StringInfoAccessor(entry.getItem()); + gatherIndexTree(indices, editor, accessor.getStringIndex()); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - StringInfoAccessor accessor = new StringInfoAccessor( entry.getItem() ); - accessor.setStringIndex( remapIndex( map, accessor.getStringIndex() ) ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + StringInfoAccessor accessor = new StringInfoAccessor(entry.getItem()); + accessor.setStringIndex(remapIndex(map, accessor.getStringIndex())); } @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - StringInfoAccessor accessor = new StringInfoAccessor( entry.getItem() ); - ConstInfoAccessor stringEntry = pool.getItem( accessor.getStringIndex() ); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + StringInfoAccessor accessor = new StringInfoAccessor(entry.getItem()); + ConstInfoAccessor stringEntry = pool.getItem(accessor.getStringIndex()); return stringEntry != null && stringEntry.getTag() == Utf8Info.getTag(); } }, - FieldRefInfo( 9, 2 ) - { + FieldRefInfo( 9, 2 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - MemberRefInfoAccessor accessor = new MemberRefInfoAccessor( entry.getItem() ); - gatherIndexTree( indices, editor, accessor.getClassIndex() ); - gatherIndexTree( indices, editor, accessor.getNameAndTypeIndex() ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + MemberRefInfoAccessor accessor = new MemberRefInfoAccessor(entry.getItem()); + gatherIndexTree(indices, editor, accessor.getClassIndex()); + gatherIndexTree(indices, editor, accessor.getNameAndTypeIndex()); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - MemberRefInfoAccessor accessor = new MemberRefInfoAccessor( entry.getItem() ); - accessor.setClassIndex( remapIndex( map, accessor.getClassIndex() ) ); - accessor.setNameAndTypeIndex( remapIndex( map, accessor.getNameAndTypeIndex() ) ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + MemberRefInfoAccessor accessor = new MemberRefInfoAccessor(entry.getItem()); + accessor.setClassIndex(remapIndex(map, accessor.getClassIndex())); + accessor.setNameAndTypeIndex(remapIndex(map, accessor.getNameAndTypeIndex())); } - + @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - MemberRefInfoAccessor accessor = new MemberRefInfoAccessor( entry.getItem() ); - ConstInfoAccessor classEntry = pool.getItem( accessor.getClassIndex() ); - ConstInfoAccessor nameAndTypeEntry = pool.getItem( accessor.getNameAndTypeIndex() ); - return classEntry != null && classEntry.getTag() == ClassInfo.getTag() - && nameAndTypeEntry != null && nameAndTypeEntry.getTag() == NameAndTypeInfo.getTag(); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + MemberRefInfoAccessor accessor = new MemberRefInfoAccessor(entry.getItem()); + ConstInfoAccessor classEntry = pool.getItem(accessor.getClassIndex()); + ConstInfoAccessor nameAndTypeEntry = pool.getItem(accessor.getNameAndTypeIndex()); + return classEntry != null && classEntry.getTag() == ClassInfo.getTag() && nameAndTypeEntry != null && nameAndTypeEntry.getTag() == NameAndTypeInfo.getTag(); } }, - MethodRefInfo( 10, 2 ) // same as FieldRefInfo - { + // same as FieldRefInfo + MethodRefInfo( 10, 2 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - FieldRefInfo.gatherIndexTree( indices, editor, entry ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + FieldRefInfo.gatherIndexTree(indices, editor, entry); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - FieldRefInfo.remapIndices( map, entry ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + FieldRefInfo.remapIndices(map, entry); } - + @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - return FieldRefInfo.subIndicesAreValid( entry, pool ); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + return FieldRefInfo.subIndicesAreValid(entry, pool); } }, - InterfaceMethodRefInfo( 11, 2 ) // same as FieldRefInfo - { + // same as FieldRefInfo + InterfaceMethodRefInfo( 11, 2 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - FieldRefInfo.gatherIndexTree( indices, editor, entry ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + FieldRefInfo.gatherIndexTree(indices, editor, entry); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - FieldRefInfo.remapIndices( map, entry ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + FieldRefInfo.remapIndices(map, entry); } - + @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - return FieldRefInfo.subIndicesAreValid( entry, pool ); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + return FieldRefInfo.subIndicesAreValid(entry, pool); } }, - NameAndTypeInfo( 12, 1 ) - { + NameAndTypeInfo( 12, 1 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - NameAndTypeInfoAccessor accessor = new NameAndTypeInfoAccessor( entry.getItem() ); - gatherIndexTree( indices, editor, accessor.getNameIndex() ); - gatherIndexTree( indices, editor, accessor.getTypeIndex() ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + NameAndTypeInfoAccessor accessor = new NameAndTypeInfoAccessor(entry.getItem()); + gatherIndexTree(indices, editor, accessor.getNameIndex()); + gatherIndexTree(indices, editor, accessor.getTypeIndex()); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - NameAndTypeInfoAccessor accessor = new NameAndTypeInfoAccessor( entry.getItem() ); - accessor.setNameIndex( remapIndex( map, accessor.getNameIndex() ) ); - accessor.setTypeIndex( remapIndex( map, accessor.getTypeIndex() ) ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + NameAndTypeInfoAccessor accessor = new NameAndTypeInfoAccessor(entry.getItem()); + accessor.setNameIndex(remapIndex(map, accessor.getNameIndex())); + accessor.setTypeIndex(remapIndex(map, accessor.getTypeIndex())); } @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - NameAndTypeInfoAccessor accessor = new NameAndTypeInfoAccessor( entry.getItem() ); - ConstInfoAccessor nameEntry = pool.getItem( accessor.getNameIndex() ); - ConstInfoAccessor typeEntry = pool.getItem( accessor.getTypeIndex() ); - return nameEntry != null && nameEntry.getTag() == Utf8Info.getTag() - && typeEntry != null && typeEntry.getTag() == Utf8Info.getTag(); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + NameAndTypeInfoAccessor accessor = new NameAndTypeInfoAccessor(entry.getItem()); + ConstInfoAccessor nameEntry = pool.getItem(accessor.getNameIndex()); + ConstInfoAccessor typeEntry = pool.getItem(accessor.getTypeIndex()); + return nameEntry != null && nameEntry.getTag() == Utf8Info.getTag() && typeEntry != null && typeEntry.getTag() == Utf8Info.getTag(); } }, - MethodHandleInfo( 15, 3 ) - { + MethodHandleInfo( 15, 3 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - MethodHandleInfoAccessor accessor = new MethodHandleInfoAccessor( entry.getItem() ); - gatherIndexTree( indices, editor, accessor.getTypeIndex() ); - gatherIndexTree( indices, editor, accessor.getMethodRefIndex() ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + MethodHandleInfoAccessor accessor = new MethodHandleInfoAccessor(entry.getItem()); + gatherIndexTree(indices, editor, accessor.getTypeIndex()); + gatherIndexTree(indices, editor, accessor.getMethodRefIndex()); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - MethodHandleInfoAccessor accessor = new MethodHandleInfoAccessor( entry.getItem() ); - accessor.setTypeIndex( remapIndex( map, accessor.getTypeIndex() ) ); - accessor.setMethodRefIndex( remapIndex( map, accessor.getMethodRefIndex() ) ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + MethodHandleInfoAccessor accessor = new MethodHandleInfoAccessor(entry.getItem()); + accessor.setTypeIndex(remapIndex(map, accessor.getTypeIndex())); + accessor.setMethodRefIndex(remapIndex(map, accessor.getMethodRefIndex())); } - + @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - MethodHandleInfoAccessor accessor = new MethodHandleInfoAccessor( entry.getItem() ); - ConstInfoAccessor typeEntry = pool.getItem( accessor.getTypeIndex() ); - ConstInfoAccessor methodRefEntry = pool.getItem( accessor.getMethodRefIndex() ); - return typeEntry != null && typeEntry.getTag() == Utf8Info.getTag() - && methodRefEntry != null && methodRefEntry.getTag() == MethodRefInfo.getTag(); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + MethodHandleInfoAccessor accessor = new MethodHandleInfoAccessor(entry.getItem()); + ConstInfoAccessor typeEntry = pool.getItem(accessor.getTypeIndex()); + ConstInfoAccessor methodRefEntry = pool.getItem(accessor.getMethodRefIndex()); + return typeEntry != null && typeEntry.getTag() == Utf8Info.getTag() && methodRefEntry != null && methodRefEntry.getTag() == MethodRefInfo.getTag(); } }, - MethodTypeInfo( 16, 1 ) - { + MethodTypeInfo( 16, 1 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - MethodTypeInfoAccessor accessor = new MethodTypeInfoAccessor( entry.getItem() ); - gatherIndexTree( indices, editor, accessor.getTypeIndex() ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + MethodTypeInfoAccessor accessor = new MethodTypeInfoAccessor(entry.getItem()); + gatherIndexTree(indices, editor, accessor.getTypeIndex()); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - MethodTypeInfoAccessor accessor = new MethodTypeInfoAccessor( entry.getItem() ); - accessor.setTypeIndex( remapIndex( map, accessor.getTypeIndex() ) ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + MethodTypeInfoAccessor accessor = new MethodTypeInfoAccessor(entry.getItem()); + accessor.setTypeIndex(remapIndex(map, accessor.getTypeIndex())); } - + @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - MethodTypeInfoAccessor accessor = new MethodTypeInfoAccessor( entry.getItem() ); - ConstInfoAccessor typeEntry = pool.getItem( accessor.getTypeIndex() ); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + MethodTypeInfoAccessor accessor = new MethodTypeInfoAccessor(entry.getItem()); + ConstInfoAccessor typeEntry = pool.getItem(accessor.getTypeIndex()); return typeEntry != null && typeEntry.getTag() == Utf8Info.getTag(); } }, - InvokeDynamicInfo( 18, 2 ) - { + InvokeDynamicInfo( 18, 2 ) { + @Override - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { - InvokeDynamicInfoAccessor accessor = new InvokeDynamicInfoAccessor( entry.getItem() ); - gatherIndexTree( indices, editor, accessor.getBootstrapIndex() ); - gatherIndexTree( indices, editor, accessor.getNameAndTypeIndex() ); + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { + InvokeDynamicInfoAccessor accessor = new InvokeDynamicInfoAccessor(entry.getItem()); + gatherIndexTree(indices, editor, accessor.getBootstrapIndex()); + gatherIndexTree(indices, editor, accessor.getNameAndTypeIndex()); } @Override - public void remapIndices( Map map, ConstInfoAccessor entry ) - { - InvokeDynamicInfoAccessor accessor = new InvokeDynamicInfoAccessor( entry.getItem() ); - accessor.setBootstrapIndex( remapIndex( map, accessor.getBootstrapIndex() ) ); - accessor.setNameAndTypeIndex( remapIndex( map, accessor.getNameAndTypeIndex() ) ); + public void remapIndices(Map map, ConstInfoAccessor entry) { + InvokeDynamicInfoAccessor accessor = new InvokeDynamicInfoAccessor(entry.getItem()); + accessor.setBootstrapIndex(remapIndex(map, accessor.getBootstrapIndex())); + accessor.setNameAndTypeIndex(remapIndex(map, accessor.getNameAndTypeIndex())); } - + @Override - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - InvokeDynamicInfoAccessor accessor = new InvokeDynamicInfoAccessor( entry.getItem() ); - ConstInfoAccessor bootstrapEntry = pool.getItem( accessor.getBootstrapIndex() ); - ConstInfoAccessor nameAndTypeEntry = pool.getItem( accessor.getNameAndTypeIndex() ); - return bootstrapEntry != null && bootstrapEntry.getTag() == Utf8Info.getTag() - && nameAndTypeEntry != null && nameAndTypeEntry.getTag() == NameAndTypeInfo.getTag(); + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + InvokeDynamicInfoAccessor accessor = new InvokeDynamicInfoAccessor(entry.getItem()); + ConstInfoAccessor bootstrapEntry = pool.getItem(accessor.getBootstrapIndex()); + ConstInfoAccessor nameAndTypeEntry = pool.getItem(accessor.getNameAndTypeIndex()); + return bootstrapEntry != null && bootstrapEntry.getTag() == Utf8Info.getTag() && nameAndTypeEntry != null && nameAndTypeEntry.getTag() == NameAndTypeInfo.getTag(); } }; private static Map m_types; - static - { + static { m_types = Maps.newTreeMap(); - for( InfoType type : values() ) - { - m_types.put( type.getTag(), type ); + for (InfoType type : values()) { + m_types.put(type.getTag(), type); } } private int m_tag; private int m_level; - private InfoType( int tag, int level ) - { + private InfoType(int tag, int level) { m_tag = tag; m_level = level; } - public int getTag( ) - { + public int getTag() { return m_tag; } - public int getLevel( ) - { + public int getLevel() { return m_level; } - public void gatherIndexTree( Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry ) - { + public void gatherIndexTree(Collection indices, ConstPoolEditor editor, ConstInfoAccessor entry) { // by default, do nothing } - public void remapIndices( Map map, ConstInfoAccessor entry ) - { + public void remapIndices(Map map, ConstInfoAccessor entry) { // by default, do nothing } - public boolean subIndicesAreValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { + public boolean subIndicesAreValid(ConstInfoAccessor entry, ConstPoolEditor pool) { // by default, everything is good return true; } - public boolean selfIndexIsValid( ConstInfoAccessor entry, ConstPoolEditor pool ) - { - ConstInfoAccessor entryCheck = pool.getItem( entry.getIndex() ); - if( entryCheck == null ) - { + public boolean selfIndexIsValid(ConstInfoAccessor entry, ConstPoolEditor pool) { + ConstInfoAccessor entryCheck = pool.getItem(entry.getIndex()); + if (entryCheck == null) { return false; } - return entryCheck.getItem().equals( entry.getItem() ); + return entryCheck.getItem().equals(entry.getItem()); } - public static InfoType getByTag( int tag ) - { - return m_types.get( tag ); + public static InfoType getByTag(int tag) { + return m_types.get(tag); } - public static List getByLevel( int level ) - { + public static List getByLevel(int level) { List types = Lists.newArrayList(); - for( InfoType type : values() ) - { - if( type.getLevel() == level ) - { - types.add( type ); + for (InfoType type : values()) { + if (type.getLevel() == level) { + types.add(type); } } return types; } - public static List getSortedByLevel( ) - { + public static List getSortedByLevel() { List types = Lists.newArrayList(); - types.addAll( getByLevel( 0 ) ); - types.addAll( getByLevel( 1 ) ); - types.addAll( getByLevel( 2 ) ); - types.addAll( getByLevel( 3 ) ); + types.addAll(getByLevel(0)); + types.addAll(getByLevel(1)); + types.addAll(getByLevel(2)); + types.addAll(getByLevel(3)); return types; } - public static void gatherIndexTree( Collection indices, ConstPoolEditor editor, int index ) - { + public static void gatherIndexTree(Collection indices, ConstPoolEditor editor, int index) { // add own index - indices.add( index ); + indices.add(index); // recurse - ConstInfoAccessor entry = editor.getItem( index ); - entry.getType().gatherIndexTree( indices, editor, entry ); + ConstInfoAccessor entry = editor.getItem(index); + entry.getType().gatherIndexTree(indices, editor, entry); } - private static int remapIndex( Map map, int index ) - { - Integer newIndex = map.get( index ); - if( newIndex == null ) - { + private static int remapIndex(Map map, int index) { + Integer newIndex = map.get(index); + if (newIndex == null) { newIndex = index; } return newIndex; diff --git a/src/cuchaz/enigma/bytecode/InnerClassWriter.java b/src/cuchaz/enigma/bytecode/InnerClassWriter.java index 5e59307..f52c31a 100644 --- a/src/cuchaz/enigma/bytecode/InnerClassWriter.java +++ b/src/cuchaz/enigma/bytecode/InnerClassWriter.java @@ -23,105 +23,80 @@ import cuchaz.enigma.analysis.JarIndex; import cuchaz.enigma.mapping.BehaviorEntry; import cuchaz.enigma.mapping.ClassEntry; -public class InnerClassWriter -{ +public class InnerClassWriter { + private JarIndex m_jarIndex; - public InnerClassWriter( JarIndex jarIndex ) - { + public InnerClassWriter(JarIndex jarIndex) { m_jarIndex = jarIndex; } - public void write( CtClass c ) - { + public void write(CtClass c) { + // is this an inner or outer class? - String obfInnerClassName = new ClassEntry( Descriptor.toJvmName( c.getName() ) ).getSimpleName(); - String obfOuterClassName = m_jarIndex.getOuterClass( obfInnerClassName ); - if( obfOuterClassName == null ) - { + String obfInnerClassName = new ClassEntry(Descriptor.toJvmName(c.getName())).getSimpleName(); + String obfOuterClassName = m_jarIndex.getOuterClass(obfInnerClassName); + if (obfOuterClassName == null) { // this is an outer class - obfOuterClassName = Descriptor.toJvmName( c.getName() ); - } - else - { + obfOuterClassName = Descriptor.toJvmName(c.getName()); + } else { // this is an inner class, rename it to outer$inner - ClassEntry obfClassEntry = new ClassEntry( obfOuterClassName + "$" + obfInnerClassName ); - c.setName( obfClassEntry.getName() ); + ClassEntry obfClassEntry = new ClassEntry(obfOuterClassName + "$" + obfInnerClassName); + c.setName(obfClassEntry.getName()); - BehaviorEntry caller = m_jarIndex.getAnonymousClassCaller( obfInnerClassName ); - if( caller != null ) - { + BehaviorEntry caller = m_jarIndex.getAnonymousClassCaller(obfInnerClassName); + if (caller != null) { // write the enclosing method attribute - if( caller.getName().equals( "" ) ) - { - c.getClassFile().addAttribute( new EnclosingMethodAttribute( - c.getClassFile().getConstPool(), - caller.getClassName() - ) ); - } - else - { - c.getClassFile().addAttribute( new EnclosingMethodAttribute( - c.getClassFile().getConstPool(), - caller.getClassName(), - caller.getName(), - caller.getSignature() - ) ); + if (caller.getName().equals("")) { + c.getClassFile().addAttribute(new EnclosingMethodAttribute(c.getClassFile().getConstPool(), caller.getClassName())); + } else { + c.getClassFile().addAttribute(new EnclosingMethodAttribute(c.getClassFile().getConstPool(), caller.getClassName(), caller.getName(), caller.getSignature())); } } } // write the inner classes if needed - Collection obfInnerClassNames = m_jarIndex.getInnerClasses( obfOuterClassName ); - if( obfInnerClassNames != null && !obfInnerClassNames.isEmpty() ) - { - writeInnerClasses( c, obfOuterClassName, obfInnerClassNames ); + Collection obfInnerClassNames = m_jarIndex.getInnerClasses(obfOuterClassName); + if (obfInnerClassNames != null && !obfInnerClassNames.isEmpty()) { + writeInnerClasses(c, obfOuterClassName, obfInnerClassNames); } } - private void writeInnerClasses( CtClass c, String obfOuterClassName, Collection obfInnerClassNames ) - { - InnerClassesAttribute attr = new InnerClassesAttribute( c.getClassFile().getConstPool() ); - c.getClassFile().addAttribute( attr ); - for( String obfInnerClassName : obfInnerClassNames ) - { + private void writeInnerClasses(CtClass c, String obfOuterClassName, Collection obfInnerClassNames) { + InnerClassesAttribute attr = new InnerClassesAttribute(c.getClassFile().getConstPool()); + c.getClassFile().addAttribute(attr); + for (String obfInnerClassName : obfInnerClassNames) { // get the new inner class name - ClassEntry obfClassEntry = new ClassEntry( obfOuterClassName + "$" + obfInnerClassName ); + ClassEntry obfClassEntry = new ClassEntry(obfOuterClassName + "$" + obfInnerClassName); // here's what the JVM spec says about the InnerClasses attribute - // append( inner, outer of inner if inner is member of outer 0 ow, name after $ if inner not anonymous 0 ow, flags ); + // append( inner, outer of inner if inner is member of outer 0 ow, name after $ if inner not anonymous 0 ow, flags ); // update the attribute with this inner class ConstPool constPool = c.getClassFile().getConstPool(); - int innerClassIndex = constPool.addClassInfo( obfClassEntry.getName() ); + int innerClassIndex = constPool.addClassInfo(obfClassEntry.getName()); int outerClassIndex = 0; int innerClassSimpleNameIndex = 0; - if( !m_jarIndex.isAnonymousClass( obfInnerClassName ) ) - { - outerClassIndex = constPool.addClassInfo( obfClassEntry.getOuterClassName() ); - innerClassSimpleNameIndex = constPool.addUtf8Info( obfClassEntry.getInnerClassName() ); + if (!m_jarIndex.isAnonymousClass(obfInnerClassName)) { + outerClassIndex = constPool.addClassInfo(obfClassEntry.getOuterClassName()); + innerClassSimpleNameIndex = constPool.addUtf8Info(obfClassEntry.getInnerClassName()); } - attr.append( - innerClassIndex, - outerClassIndex, - innerClassSimpleNameIndex, - c.getClassFile().getAccessFlags() & ~AccessFlag.SUPER - ); + attr.append(innerClassIndex, outerClassIndex, innerClassSimpleNameIndex, c.getClassFile().getAccessFlags() & ~AccessFlag.SUPER); - /* DEBUG - System.out.println( String.format( "\tOBF: %s -> ATTR: %s,%s,%s (replace %s with %s)", + /* DEBUG + System.out.println(String.format("\tOBF: %s -> ATTR: %s,%s,%s (replace %s with %s)", obfClassEntry, - attr.outerClass( attr.tableLength() - 1 ), - attr.innerClass( attr.tableLength() - 1 ), - attr.innerName( attr.tableLength() - 1 ), + attr.outerClass(attr.tableLength() - 1), + attr.innerClass(attr.tableLength() - 1), + attr.innerName(attr.tableLength() - 1), Constants.NonePackage + "/" + obfInnerClassName, obfClassEntry.getName() - ) ); + )); */ // make sure the outer class references only the new inner class names - c.replaceClassName( Constants.NonePackage + "/" + obfInnerClassName, obfClassEntry.getName() ); + c.replaceClassName(Constants.NonePackage + "/" + obfInnerClassName, obfClassEntry.getName()); } } } diff --git a/src/cuchaz/enigma/bytecode/MethodParameterWriter.java b/src/cuchaz/enigma/bytecode/MethodParameterWriter.java index adea7ea..5a11cd8 100644 --- a/src/cuchaz/enigma/bytecode/MethodParameterWriter.java +++ b/src/cuchaz/enigma/bytecode/MethodParameterWriter.java @@ -25,51 +25,42 @@ import cuchaz.enigma.mapping.ConstructorEntry; import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.Translator; -public class MethodParameterWriter -{ +public class MethodParameterWriter { + private Translator m_translator; - public MethodParameterWriter( Translator translator ) - { + public MethodParameterWriter(Translator translator) { m_translator = translator; } - public void writeMethodArguments( CtClass c ) - { + public void writeMethodArguments(CtClass c) { + // Procyon will read method arguments from the "MethodParameters" attribute, so write those - ClassEntry classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) ); - for( CtBehavior behavior : c.getDeclaredBehaviors() ) - { - int numParams = Descriptor.numOfParameters( behavior.getMethodInfo().getDescriptor() ); - if( numParams <= 0 ) - { + ClassEntry classEntry = new ClassEntry(Descriptor.toJvmName(c.getName())); + for (CtBehavior behavior : c.getDeclaredBehaviors()) { + int numParams = Descriptor.numOfParameters(behavior.getMethodInfo().getDescriptor()); + if (numParams <= 0) { continue; } // get the behavior entry BehaviorEntry behaviorEntry; - if( behavior instanceof CtMethod ) - { - behaviorEntry = new MethodEntry( classEntry, behavior.getMethodInfo().getName(), behavior.getSignature() ); - } - else if( behavior instanceof CtConstructor ) - { - behaviorEntry = new ConstructorEntry( classEntry, behavior.getSignature() ); - } - else - { - throw new Error( "Unsupported behavior type: " + behavior.getClass().getName() ); + if (behavior instanceof CtMethod) { + behaviorEntry = new MethodEntry(classEntry, behavior.getMethodInfo().getName(), behavior.getSignature()); + } else if (behavior instanceof CtConstructor) { + behaviorEntry = new ConstructorEntry(classEntry, behavior.getSignature()); + } else { + throw new Error("Unsupported behavior type: " + behavior.getClass().getName()); } // get the list of parameter names - List names = new ArrayList( numParams ); - for( int i=0; i names = new ArrayList(numParams); + for (int i = 0; i < numParams; i++) { + names.add(m_translator.translate(new ArgumentEntry(behaviorEntry, i, ""))); } // save the mappings to the class - MethodParametersAttribute.updateClass( behavior.getMethodInfo(), names ); + MethodParametersAttribute.updateClass(behavior.getMethodInfo(), names); } } } diff --git a/src/cuchaz/enigma/bytecode/MethodParametersAttribute.java b/src/cuchaz/enigma/bytecode/MethodParametersAttribute.java index baf1ac1..bf95956 100644 --- a/src/cuchaz/enigma/bytecode/MethodParametersAttribute.java +++ b/src/cuchaz/enigma/bytecode/MethodParametersAttribute.java @@ -20,45 +20,38 @@ import javassist.bytecode.AttributeInfo; import javassist.bytecode.ConstPool; import javassist.bytecode.MethodInfo; -public class MethodParametersAttribute extends AttributeInfo -{ - private MethodParametersAttribute( ConstPool pool, List parameterNameIndices ) - { - super( pool, "MethodParameters", writeStruct( parameterNameIndices ) ); +public class MethodParametersAttribute extends AttributeInfo { + + private MethodParametersAttribute(ConstPool pool, List parameterNameIndices) { + super(pool, "MethodParameters", writeStruct(parameterNameIndices)); } - public static void updateClass( MethodInfo info, List names ) - { + public static void updateClass(MethodInfo info, List names) { // add the names to the class const pool ConstPool constPool = info.getConstPool(); List parameterNameIndices = new ArrayList(); - for( String name : names ) - { - if( name != null ) - { - parameterNameIndices.add( constPool.addUtf8Info( name ) ); - } - else - { - parameterNameIndices.add( 0 ); + for (String name : names) { + if (name != null) { + parameterNameIndices.add(constPool.addUtf8Info(name)); + } else { + parameterNameIndices.add(0); } } // add the attribute to the method - info.addAttribute( new MethodParametersAttribute( constPool, parameterNameIndices ) ); + info.addAttribute(new MethodParametersAttribute(constPool, parameterNameIndices)); } - private static byte[] writeStruct( List parameterNameIndices ) - { + private static byte[] writeStruct(List parameterNameIndices) { // JVM 8 Spec says the struct looks like this: // http://cr.openjdk.java.net/~mr/se/8/java-se-8-fr-spec-01/java-se-8-jvms-fr-diffs.pdf // uint8 num_params // for each param: - // uint16 name_index -> points to UTF8 entry in constant pool, or 0 for no entry - // uint16 access_flags -> don't care, just set to 0 + // uint16 name_index -> points to UTF8 entry in constant pool, or 0 for no entry + // uint16 access_flags -> don't care, just set to 0 ByteArrayOutputStream buf = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream( buf ); + DataOutputStream out = new DataOutputStream(buf); // NOTE: java hates unsigned integers, so we have to be careful here // the writeShort(), writeByte() methods will read 16,8 low-order bits from the int argument @@ -66,31 +59,27 @@ public class MethodParametersAttribute extends AttributeInfo // if the int is out of range, the byte stream won't look the way we want and weird things will happen final int SIZEOF_UINT8 = 1; final int SIZEOF_UINT16 = 2; - final int MAX_UINT8 = ( 1 << 8 ) - 1; - final int MAX_UINT16 = ( 1 << 16 ) - 1; + final int MAX_UINT8 = (1 << 8) - 1; + final int MAX_UINT16 = (1 << 16) - 1; - try - { - assert( parameterNameIndices.size() >= 0 && parameterNameIndices.size() <= MAX_UINT8 ); - out.writeByte( parameterNameIndices.size() ); + try { + assert (parameterNameIndices.size() >= 0 && parameterNameIndices.size() <= MAX_UINT8); + out.writeByte(parameterNameIndices.size()); - for( Integer index : parameterNameIndices ) - { - assert( index >= 0 && index <= MAX_UINT16 ); - out.writeShort( index ); + for (Integer index : parameterNameIndices) { + assert (index >= 0 && index <= MAX_UINT16); + out.writeShort(index); // just write 0 for the access flags - out.writeShort( 0 ); + out.writeShort(0); } out.close(); byte[] data = buf.toByteArray(); - assert( data.length == SIZEOF_UINT8 + parameterNameIndices.size()*( SIZEOF_UINT16 + SIZEOF_UINT16 ) ); + assert (data.length == SIZEOF_UINT8 + parameterNameIndices.size() * (SIZEOF_UINT16 + SIZEOF_UINT16)); return data; - } - catch( IOException ex ) - { - throw new Error( ex ); + } catch (IOException ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/ClassInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/ClassInfoAccessor.java index 41e1d04..d76f056 100644 --- a/src/cuchaz/enigma/bytecode/accessors/ClassInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/ClassInfoAccessor.java @@ -12,58 +12,44 @@ package cuchaz.enigma.bytecode.accessors; import java.lang.reflect.Field; -public class ClassInfoAccessor -{ +public class ClassInfoAccessor { + private static Class m_class; private static Field m_nameIndex; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.ClassInfo" ); - m_nameIndex = m_class.getDeclaredField( "name" ); - m_nameIndex.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.ClassInfo"); + m_nameIndex = m_class.getDeclaredField("name"); + m_nameIndex.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } private Object m_item; - public ClassInfoAccessor( Object item ) - { + public ClassInfoAccessor(Object item) { m_item = item; } - public int getNameIndex( ) - { - try - { - return (Integer)m_nameIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getNameIndex() { + try { + return (Integer)m_nameIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setNameIndex( int val ) - { - try - { - m_nameIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setNameIndex(int val) { + try { + m_nameIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/ConstInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/ConstInfoAccessor.java index 3c3d3fa..d00c102 100644 --- a/src/cuchaz/enigma/bytecode/accessors/ConstInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/ConstInfoAccessor.java @@ -22,44 +22,35 @@ import java.lang.reflect.Method; import cuchaz.enigma.bytecode.InfoType; -public class ConstInfoAccessor -{ +public class ConstInfoAccessor { + private static Class m_class; private static Field m_index; private static Method m_getTag; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.ConstInfo" ); - m_index = m_class.getDeclaredField( "index" ); - m_index.setAccessible( true ); - m_getTag = m_class.getMethod( "getTag" ); - m_getTag.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.ConstInfo"); + m_index = m_class.getDeclaredField("index"); + m_index.setAccessible(true); + m_getTag = m_class.getMethod("getTag"); + m_getTag.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } private Object m_item; - public ConstInfoAccessor( Object item ) - { - if( item == null ) - { - throw new IllegalArgumentException( "item cannot be null!" ); + public ConstInfoAccessor(Object item) { + if (item == null) { + throw new IllegalArgumentException("item cannot be null!"); } m_item = item; } - public ConstInfoAccessor( DataInputStream in ) - throws IOException - { - try - { + public ConstInfoAccessor(DataInputStream in) throws IOException { + try { // read the entry String className = in.readUTF(); int oldIndex = in.readInt(); @@ -68,132 +59,98 @@ public class ConstInfoAccessor // so we have to read it here in.readByte(); - Constructor constructor = Class.forName( className ).getConstructor( DataInputStream.class, int.class ); - constructor.setAccessible( true ); - m_item = constructor.newInstance( in, oldIndex ); - } - catch( IOException ex ) - { + Constructor constructor = Class.forName(className).getConstructor(DataInputStream.class, int.class); + constructor.setAccessible(true); + m_item = constructor.newInstance(in, oldIndex); + } catch (IOException ex) { throw ex; - } - catch( Exception ex ) - { - throw new Error( ex ); + } catch (Exception ex) { + throw new Error(ex); } } - public Object getItem( ) - { + public Object getItem() { return m_item; } - public int getIndex( ) - { - try - { - return (Integer)m_index.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getIndex() { + try { + return (Integer)m_index.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setIndex( int val ) - { - try - { - m_index.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setIndex(int val) { + try { + m_index.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } - public int getTag( ) - { - try - { - return (Integer)m_getTag.invoke( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getTag() { + try { + return (Integer)m_getTag.invoke(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public ConstInfoAccessor copy( ) - { - return new ConstInfoAccessor( copyItem() ); + public ConstInfoAccessor copy() { + return new ConstInfoAccessor(copyItem()); } - public Object copyItem( ) - { + public Object copyItem() { // I don't know of a simpler way to copy one of these silly things... - try - { + try { // serialize the item ByteArrayOutputStream buf = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream( buf ); - write( out ); + DataOutputStream out = new DataOutputStream(buf); + write(out); // deserialize the item - DataInputStream in = new DataInputStream( new ByteArrayInputStream( buf.toByteArray() ) ); - Object item = new ConstInfoAccessor( in ).getItem(); + DataInputStream in = new DataInputStream(new ByteArrayInputStream(buf.toByteArray())); + Object item = new ConstInfoAccessor(in).getItem(); in.close(); return item; - } - catch( Exception ex ) - { - throw new Error( ex ); + } catch (Exception ex) { + throw new Error(ex); } } - public void write( DataOutputStream out ) - throws IOException - { - try - { - out.writeUTF( m_item.getClass().getName() ); - out.writeInt( getIndex() ); + public void write(DataOutputStream out) throws IOException { + try { + out.writeUTF(m_item.getClass().getName()); + out.writeInt(getIndex()); - Method method = m_item.getClass().getMethod( "write", DataOutputStream.class ); - method.setAccessible( true ); - method.invoke( m_item, out ); - } - catch( IOException ex ) - { + Method method = m_item.getClass().getMethod("write", DataOutputStream.class); + method.setAccessible(true); + method.invoke(m_item, out); + } catch (IOException ex) { throw ex; - } - catch( Exception ex ) - { - throw new Error( ex ); + } catch (Exception ex) { + throw new Error(ex); } } @Override - public String toString( ) - { - try - { + public String toString() { + try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); - PrintWriter out = new PrintWriter( buf ); - Method print = m_item.getClass().getMethod( "print", PrintWriter.class ); - print.setAccessible( true ); - print.invoke( m_item, out ); + PrintWriter out = new PrintWriter(buf); + Method print = m_item.getClass().getMethod("print", PrintWriter.class); + print.setAccessible(true); + print.invoke(m_item, out); out.close(); - return buf.toString().replace( "\n", "" ); - } - catch( Exception ex ) - { - throw new Error( ex ); + return buf.toString().replace("\n", ""); + } catch (Exception ex) { + throw new Error(ex); } } - public InfoType getType( ) - { - return InfoType.getByTag( getTag() ); + public InfoType getType() { + return InfoType.getByTag(getTag()); } } diff --git a/src/cuchaz/enigma/bytecode/accessors/InvokeDynamicInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/InvokeDynamicInfoAccessor.java index 169306a..0d780ea 100644 --- a/src/cuchaz/enigma/bytecode/accessors/InvokeDynamicInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/InvokeDynamicInfoAccessor.java @@ -12,85 +12,63 @@ package cuchaz.enigma.bytecode.accessors; import java.lang.reflect.Field; -public class InvokeDynamicInfoAccessor -{ +public class InvokeDynamicInfoAccessor { + private static Class m_class; private static Field m_bootstrapIndex; private static Field m_nameAndTypeIndex; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.InvokeDynamicInfo" ); - m_bootstrapIndex = m_class.getDeclaredField( "bootstrap" ); - m_bootstrapIndex.setAccessible( true ); - m_nameAndTypeIndex = m_class.getDeclaredField( "nameAndType" ); - m_nameAndTypeIndex.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.InvokeDynamicInfo"); + m_bootstrapIndex = m_class.getDeclaredField("bootstrap"); + m_bootstrapIndex.setAccessible(true); + m_nameAndTypeIndex = m_class.getDeclaredField("nameAndType"); + m_nameAndTypeIndex.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } private Object m_item; - public InvokeDynamicInfoAccessor( Object item ) - { + public InvokeDynamicInfoAccessor(Object item) { m_item = item; } - public int getBootstrapIndex( ) - { - try - { - return (Integer)m_bootstrapIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getBootstrapIndex() { + try { + return (Integer)m_bootstrapIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setBootstrapIndex( int val ) - { - try - { - m_bootstrapIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setBootstrapIndex(int val) { + try { + m_bootstrapIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } - public int getNameAndTypeIndex( ) - { - try - { - return (Integer)m_nameAndTypeIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getNameAndTypeIndex() { + try { + return (Integer)m_nameAndTypeIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setNameAndTypeIndex( int val ) - { - try - { - m_nameAndTypeIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setNameAndTypeIndex(int val) { + try { + m_nameAndTypeIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/MemberRefInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/MemberRefInfoAccessor.java index 2ee3aff..9fe945f 100644 --- a/src/cuchaz/enigma/bytecode/accessors/MemberRefInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/MemberRefInfoAccessor.java @@ -12,85 +12,63 @@ package cuchaz.enigma.bytecode.accessors; import java.lang.reflect.Field; -public class MemberRefInfoAccessor -{ +public class MemberRefInfoAccessor { + private static Class m_class; private static Field m_classIndex; private static Field m_nameAndTypeIndex; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.MemberrefInfo" ); - m_classIndex = m_class.getDeclaredField( "classIndex" ); - m_classIndex.setAccessible( true ); - m_nameAndTypeIndex = m_class.getDeclaredField( "nameAndTypeIndex" ); - m_nameAndTypeIndex.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.MemberrefInfo"); + m_classIndex = m_class.getDeclaredField("classIndex"); + m_classIndex.setAccessible(true); + m_nameAndTypeIndex = m_class.getDeclaredField("nameAndTypeIndex"); + m_nameAndTypeIndex.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } private Object m_item; - public MemberRefInfoAccessor( Object item ) - { + public MemberRefInfoAccessor(Object item) { m_item = item; } - public int getClassIndex( ) - { - try - { - return (Integer)m_classIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getClassIndex() { + try { + return (Integer)m_classIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setClassIndex( int val ) - { - try - { - m_classIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setClassIndex(int val) { + try { + m_classIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } - public int getNameAndTypeIndex( ) - { - try - { - return (Integer)m_nameAndTypeIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getNameAndTypeIndex() { + try { + return (Integer)m_nameAndTypeIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setNameAndTypeIndex( int val ) - { - try - { - m_nameAndTypeIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setNameAndTypeIndex(int val) { + try { + m_nameAndTypeIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/MethodHandleInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/MethodHandleInfoAccessor.java index 27b7aee..4c95b22 100644 --- a/src/cuchaz/enigma/bytecode/accessors/MethodHandleInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/MethodHandleInfoAccessor.java @@ -12,85 +12,63 @@ package cuchaz.enigma.bytecode.accessors; import java.lang.reflect.Field; -public class MethodHandleInfoAccessor -{ +public class MethodHandleInfoAccessor { + private static Class m_class; private static Field m_kindIndex; private static Field m_indexIndex; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.MethodHandleInfo" ); - m_kindIndex = m_class.getDeclaredField( "refKind" ); - m_kindIndex.setAccessible( true ); - m_indexIndex = m_class.getDeclaredField( "refIndex" ); - m_indexIndex.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.MethodHandleInfo"); + m_kindIndex = m_class.getDeclaredField("refKind"); + m_kindIndex.setAccessible(true); + m_indexIndex = m_class.getDeclaredField("refIndex"); + m_indexIndex.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } private Object m_item; - public MethodHandleInfoAccessor( Object item ) - { + public MethodHandleInfoAccessor(Object item) { m_item = item; } - public int getTypeIndex( ) - { - try - { - return (Integer)m_kindIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getTypeIndex() { + try { + return (Integer)m_kindIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setTypeIndex( int val ) - { - try - { - m_kindIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setTypeIndex(int val) { + try { + m_kindIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } - public int getMethodRefIndex( ) - { - try - { - return (Integer)m_indexIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getMethodRefIndex() { + try { + return (Integer)m_indexIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setMethodRefIndex( int val ) - { - try - { - m_indexIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setMethodRefIndex(int val) { + try { + m_indexIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/MethodTypeInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/MethodTypeInfoAccessor.java index 4cba6a2..e151117 100644 --- a/src/cuchaz/enigma/bytecode/accessors/MethodTypeInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/MethodTypeInfoAccessor.java @@ -12,58 +12,44 @@ package cuchaz.enigma.bytecode.accessors; import java.lang.reflect.Field; -public class MethodTypeInfoAccessor -{ +public class MethodTypeInfoAccessor { + private static Class m_class; private static Field m_descriptorIndex; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.MethodTypeInfo" ); - m_descriptorIndex = m_class.getDeclaredField( "descriptor" ); - m_descriptorIndex.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.MethodTypeInfo"); + m_descriptorIndex = m_class.getDeclaredField("descriptor"); + m_descriptorIndex.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } private Object m_item; - public MethodTypeInfoAccessor( Object item ) - { + public MethodTypeInfoAccessor(Object item) { m_item = item; } - public int getTypeIndex( ) - { - try - { - return (Integer)m_descriptorIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getTypeIndex() { + try { + return (Integer)m_descriptorIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setTypeIndex( int val ) - { - try - { - m_descriptorIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setTypeIndex(int val) { + try { + m_descriptorIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/NameAndTypeInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/NameAndTypeInfoAccessor.java index 03b4de3..6e82f3e 100644 --- a/src/cuchaz/enigma/bytecode/accessors/NameAndTypeInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/NameAndTypeInfoAccessor.java @@ -12,85 +12,63 @@ package cuchaz.enigma.bytecode.accessors; import java.lang.reflect.Field; -public class NameAndTypeInfoAccessor -{ +public class NameAndTypeInfoAccessor { + private static Class m_class; private static Field m_nameIndex; private static Field m_typeIndex; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.NameAndTypeInfo" ); - m_nameIndex = m_class.getDeclaredField( "memberName" ); - m_nameIndex.setAccessible( true ); - m_typeIndex = m_class.getDeclaredField( "typeDescriptor" ); - m_typeIndex.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.NameAndTypeInfo"); + m_nameIndex = m_class.getDeclaredField("memberName"); + m_nameIndex.setAccessible(true); + m_typeIndex = m_class.getDeclaredField("typeDescriptor"); + m_typeIndex.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } private Object m_item; - public NameAndTypeInfoAccessor( Object item ) - { + public NameAndTypeInfoAccessor(Object item) { m_item = item; } - public int getNameIndex( ) - { - try - { - return (Integer)m_nameIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getNameIndex() { + try { + return (Integer)m_nameIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setNameIndex( int val ) - { - try - { - m_nameIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setNameIndex(int val) { + try { + m_nameIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } - public int getTypeIndex( ) - { - try - { - return (Integer)m_typeIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getTypeIndex() { + try { + return (Integer)m_typeIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setTypeIndex( int val ) - { - try - { - m_typeIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setTypeIndex(int val) { + try { + m_typeIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/StringInfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/StringInfoAccessor.java index 5cdfce4..6665ffe 100644 --- a/src/cuchaz/enigma/bytecode/accessors/StringInfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/StringInfoAccessor.java @@ -12,58 +12,44 @@ package cuchaz.enigma.bytecode.accessors; import java.lang.reflect.Field; -public class StringInfoAccessor -{ +public class StringInfoAccessor { + private static Class m_class; private static Field m_stringIndex; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.StringInfo" ); - m_stringIndex = m_class.getDeclaredField( "string" ); - m_stringIndex.setAccessible( true ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.StringInfo"); + m_stringIndex = m_class.getDeclaredField("string"); + m_stringIndex.setAccessible(true); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } private Object m_item; - public StringInfoAccessor( Object item ) - { + public StringInfoAccessor(Object item) { m_item = item; } - public int getStringIndex( ) - { - try - { - return (Integer)m_stringIndex.get( m_item ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public int getStringIndex() { + try { + return (Integer)m_stringIndex.get(m_item); + } catch (Exception ex) { + throw new Error(ex); } } - public void setStringIndex( int val ) - { - try - { - m_stringIndex.set( m_item, val ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void setStringIndex(int val) { + try { + m_stringIndex.set(m_item, val); + } catch (Exception ex) { + throw new Error(ex); } } } diff --git a/src/cuchaz/enigma/bytecode/accessors/Utf8InfoAccessor.java b/src/cuchaz/enigma/bytecode/accessors/Utf8InfoAccessor.java index 1cadd83..2abf60b 100644 --- a/src/cuchaz/enigma/bytecode/accessors/Utf8InfoAccessor.java +++ b/src/cuchaz/enigma/bytecode/accessors/Utf8InfoAccessor.java @@ -10,24 +10,19 @@ ******************************************************************************/ package cuchaz.enigma.bytecode.accessors; -public class Utf8InfoAccessor -{ +public class Utf8InfoAccessor { + private static Class m_class; - static - { - try - { - m_class = Class.forName( "javassist.bytecode.Utf8Info" ); - } - catch( Exception ex ) - { - throw new Error( ex ); + static { + try { + m_class = Class.forName("javassist.bytecode.Utf8Info"); + } catch (Exception ex) { + throw new Error(ex); } } - public static boolean isType( ConstInfoAccessor accessor ) - { - return m_class.isAssignableFrom( accessor.getItem().getClass() ); + public static boolean isType(ConstInfoAccessor accessor) { + return m_class.isAssignableFrom(accessor.getItem().getClass()); } } diff --git a/src/cuchaz/enigma/convert/ClassIdentity.java b/src/cuchaz/enigma/convert/ClassIdentity.java index 1de345f..7340403 100644 --- a/src/cuchaz/enigma/convert/ClassIdentity.java +++ b/src/cuchaz/enigma/convert/ClassIdentity.java @@ -57,8 +57,8 @@ import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.SignatureUpdater; import cuchaz.enigma.mapping.SignatureUpdater.ClassNameUpdater; -public class ClassIdentity -{ +public class ClassIdentity { + private ClassEntry m_classEntry; private SidedClassNamer m_namer; private Multiset m_fields; @@ -70,419 +70,339 @@ public class ClassIdentity private Multiset m_implementations; private Multiset m_references; - public ClassIdentity( CtClass c, SidedClassNamer namer, JarIndex index, boolean useReferences ) - { + public ClassIdentity(CtClass c, SidedClassNamer namer, JarIndex index, boolean useReferences) { m_namer = namer; // stuff from the bytecode - m_classEntry = new ClassEntry( Descriptor.toJvmName( c.getName() ) ); + m_classEntry = new ClassEntry(Descriptor.toJvmName(c.getName())); m_fields = HashMultiset.create(); - for( CtField field : c.getDeclaredFields() ) - { - m_fields.add( scrubSignature( field.getSignature() ) ); + for (CtField field : c.getDeclaredFields()) { + m_fields.add(scrubSignature(field.getSignature())); } m_methods = HashMultiset.create(); - for( CtMethod method : c.getDeclaredMethods() ) - { - m_methods.add( scrubSignature( method.getSignature() ) + "0x" + getBehaviorSignature( method ) ); + for (CtMethod method : c.getDeclaredMethods()) { + m_methods.add(scrubSignature(method.getSignature()) + "0x" + getBehaviorSignature(method)); } m_constructors = HashMultiset.create(); - for( CtConstructor constructor : c.getDeclaredConstructors() ) - { - m_constructors.add( scrubSignature( constructor.getSignature() ) + "0x" + getBehaviorSignature( constructor ) ); + for (CtConstructor constructor : c.getDeclaredConstructors()) { + m_constructors.add(scrubSignature(constructor.getSignature()) + "0x" + getBehaviorSignature(constructor)); } m_staticInitializer = ""; - if( c.getClassInitializer() != null ) - { - m_staticInitializer = getBehaviorSignature( c.getClassInitializer() ); + if (c.getClassInitializer() != null) { + m_staticInitializer = getBehaviorSignature(c.getClassInitializer()); } m_extends = ""; - if( c.getClassFile().getSuperclass() != null ) - { - m_extends = scrubClassName( c.getClassFile().getSuperclass() ); + if (c.getClassFile().getSuperclass() != null) { + m_extends = scrubClassName(c.getClassFile().getSuperclass()); } m_implements = HashMultiset.create(); - for( String interfaceName : c.getClassFile().getInterfaces() ) - { - m_implements.add( scrubClassName( interfaceName ) ); + for (String interfaceName : c.getClassFile().getInterfaces()) { + m_implements.add(scrubClassName(interfaceName)); } // stuff from the jar index m_implementations = HashMultiset.create(); - ClassImplementationsTreeNode implementationsNode = index.getClassImplementations( null, m_classEntry ); - if( implementationsNode != null ) - { - @SuppressWarnings( "unchecked" ) + ClassImplementationsTreeNode implementationsNode = index.getClassImplementations(null, m_classEntry); + if (implementationsNode != null) { + @SuppressWarnings("unchecked") Enumeration implementations = implementationsNode.children(); - while( implementations.hasMoreElements() ) - { + while (implementations.hasMoreElements()) { ClassImplementationsTreeNode node = implementations.nextElement(); - m_implementations.add( scrubClassName( node.getClassEntry().getName() ) ); + m_implementations.add(scrubClassName(node.getClassEntry().getName())); } } m_references = HashMultiset.create(); - if( useReferences ) - { - for( CtField field : c.getDeclaredFields() ) - { - FieldEntry fieldEntry = new FieldEntry( m_classEntry, field.getName() ); - for( EntryReference reference : index.getFieldReferences( fieldEntry ) ) - { - addReference( reference ); + if (useReferences) { + for (CtField field : c.getDeclaredFields()) { + FieldEntry fieldEntry = new FieldEntry(m_classEntry, field.getName()); + for (EntryReference reference : index.getFieldReferences(fieldEntry)) { + addReference(reference); } } - for( CtMethod method : c.getDeclaredMethods() ) - { - MethodEntry methodEntry = new MethodEntry( m_classEntry, method.getName(), method.getSignature() ); - for( EntryReference reference : index.getBehaviorReferences( methodEntry ) ) - { - addReference( reference ); + for (CtMethod method : c.getDeclaredMethods()) { + MethodEntry methodEntry = new MethodEntry(m_classEntry, method.getName(), method.getSignature()); + for (EntryReference reference : index.getBehaviorReferences(methodEntry)) { + addReference(reference); } } - for( CtConstructor constructor : c.getDeclaredConstructors() ) - { - ConstructorEntry constructorEntry = new ConstructorEntry( m_classEntry, constructor.getSignature() ); - for( EntryReference reference : index.getBehaviorReferences( constructorEntry ) ) - { - addReference( reference ); + for (CtConstructor constructor : c.getDeclaredConstructors()) { + ConstructorEntry constructorEntry = new ConstructorEntry(m_classEntry, constructor.getSignature()); + for (EntryReference reference : index.getBehaviorReferences(constructorEntry)) { + addReference(reference); } } } } - private void addReference( EntryReference reference ) - { - if( reference.context.getSignature() != null ) - { - m_references.add( String.format( "%s_%s", - scrubClassName( reference.context.getClassName() ), - scrubSignature( reference.context.getSignature() ) - ) ); - } - else - { - m_references.add( String.format( "%s_", - scrubClassName( reference.context.getClassName() ) - ) ); + private void addReference(EntryReference reference) { + if (reference.context.getSignature() != null) { + m_references.add(String.format("%s_%s", scrubClassName(reference.context.getClassName()), scrubSignature(reference.context.getSignature()))); + } else { + m_references.add(String.format("%s_", scrubClassName(reference.context.getClassName()))); } } - - public ClassEntry getClassEntry( ) - { + + public ClassEntry getClassEntry() { return m_classEntry; } @Override - public String toString( ) - { + public String toString() { StringBuilder buf = new StringBuilder(); - buf.append( "class: " ); - buf.append( m_classEntry.getName() ); - buf.append( " " ); - buf.append( hashCode() ); - buf.append( "\n" ); - for( String field : m_fields ) - { - buf.append( "\tfield " ); - buf.append( field ); - buf.append( "\n" ); + buf.append("class: "); + buf.append(m_classEntry.getName()); + buf.append(" "); + buf.append(hashCode()); + buf.append("\n"); + for (String field : m_fields) { + buf.append("\tfield "); + buf.append(field); + buf.append("\n"); } - for( String method : m_methods ) - { - buf.append( "\tmethod " ); - buf.append( method ); - buf.append( "\n" ); + for (String method : m_methods) { + buf.append("\tmethod "); + buf.append(method); + buf.append("\n"); } - for( String constructor : m_constructors ) - { - buf.append( "\tconstructor " ); - buf.append( constructor ); - buf.append( "\n" ); + for (String constructor : m_constructors) { + buf.append("\tconstructor "); + buf.append(constructor); + buf.append("\n"); } - if( m_staticInitializer.length() > 0 ) - { - buf.append( "\tinitializer " ); - buf.append( m_staticInitializer ); - buf.append( "\n" ); + if (m_staticInitializer.length() > 0) { + buf.append("\tinitializer "); + buf.append(m_staticInitializer); + buf.append("\n"); } - if( m_extends.length() > 0 ) - { - buf.append( "\textends " ); - buf.append( m_extends ); - buf.append( "\n" ); + if (m_extends.length() > 0) { + buf.append("\textends "); + buf.append(m_extends); + buf.append("\n"); } - for( String interfaceName : m_implements ) - { - buf.append( "\timplements " ); - buf.append( interfaceName ); - buf.append( "\n" ); + for (String interfaceName : m_implements) { + buf.append("\timplements "); + buf.append(interfaceName); + buf.append("\n"); } - for( String implementation : m_implementations ) - { - buf.append( "\timplemented by " ); - buf.append( implementation ); - buf.append( "\n" ); + for (String implementation : m_implementations) { + buf.append("\timplemented by "); + buf.append(implementation); + buf.append("\n"); } - for( String reference : m_references ) - { - buf.append( "\treference " ); - buf.append( reference ); - buf.append( "\n" ); + for (String reference : m_references) { + buf.append("\treference "); + buf.append(reference); + buf.append("\n"); } return buf.toString(); } - private String scrubClassName( String className ) - { - return scrubSignature( "L" + Descriptor.toJvmName( className ) + ";" ); + private String scrubClassName(String className) { + return scrubSignature("L" + Descriptor.toJvmName(className) + ";"); } - private String scrubSignature( String signature ) - { - return SignatureUpdater.update( signature, new ClassNameUpdater( ) - { + private String scrubSignature(String signature) { + return SignatureUpdater.update(signature, new ClassNameUpdater() { private Map m_classNames = Maps.newHashMap(); @Override - public String update( String className ) - { + public String update(String className) { // classes not in the none package can be passed through - ClassEntry classEntry = new ClassEntry( className ); - if( !classEntry.getPackageName().equals( Constants.NonePackage ) ) - { + ClassEntry classEntry = new ClassEntry(className); + if (!classEntry.getPackageName().equals(Constants.NonePackage)) { return className; } // is this class ourself? - if( className.equals( m_classEntry.getName() ) ) - { + if (className.equals(m_classEntry.getName())) { return "CSelf"; } // try the namer - if( m_namer != null ) - { - String newName = m_namer.getName( className ); - if( newName != null ) - { + if (m_namer != null) { + String newName = m_namer.getName(className); + if (newName != null) { return newName; } } // otherwise, use local naming - if( !m_classNames.containsKey( className ) ) - { - m_classNames.put( className, getNewClassName() ); + if (!m_classNames.containsKey(className)) { + m_classNames.put(className, getNewClassName()); } - return m_classNames.get( className ); + return m_classNames.get(className); } - - private String getNewClassName( ) - { - return String.format( "C%03d", m_classNames.size() ); + + private String getNewClassName() { + return String.format("C%03d", m_classNames.size()); } - } ); + }); } - private boolean isClassMatchedUniquely( String className ) - { - return m_namer != null && m_namer.getName( Descriptor.toJvmName( className ) ) != null; + private boolean isClassMatchedUniquely(String className) { + return m_namer != null && m_namer.getName(Descriptor.toJvmName(className)) != null; } - private String getBehaviorSignature( CtBehavior behavior ) - { - try - { + private String getBehaviorSignature(CtBehavior behavior) { + try { // does this method have an implementation? - if( behavior.getMethodInfo().getCodeAttribute() == null ) - { + if (behavior.getMethodInfo().getCodeAttribute() == null) { return "(none)"; } // compute the hash from the opcodes ConstPool constants = behavior.getMethodInfo().getConstPool(); - final MessageDigest digest = MessageDigest.getInstance( "MD5" ); + final MessageDigest digest = MessageDigest.getInstance("MD5"); CodeIterator iter = behavior.getMethodInfo().getCodeAttribute().iterator(); - while( iter.hasNext() ) - { + while (iter.hasNext()) { int pos = iter.next(); // update the hash with the opcode - int opcode = iter.byteAt( pos ); - digest.update( (byte)opcode ); + int opcode = iter.byteAt(pos); + digest.update((byte)opcode); - switch( opcode ) - { - case Opcode.LDC: - { - int constIndex = iter.byteAt( pos + 1 ); - updateHashWithConstant( digest, constants, constIndex ); + switch (opcode) { + case Opcode.LDC: { + int constIndex = iter.byteAt(pos + 1); + updateHashWithConstant(digest, constants, constIndex); } break; case Opcode.LDC_W: - case Opcode.LDC2_W: - { - int constIndex = ( iter.byteAt( pos + 1 ) << 8 ) | iter.byteAt( pos + 2 ); - updateHashWithConstant( digest, constants, constIndex ); + case Opcode.LDC2_W: { + int constIndex = (iter.byteAt(pos + 1) << 8) | iter.byteAt(pos + 2); + updateHashWithConstant(digest, constants, constIndex); } break; } } // update hash with method and field accesses - behavior.instrument( new ExprEditor( ) - { + behavior.instrument(new ExprEditor() { @Override - public void edit( MethodCall call ) - { - updateHashWithString( digest, scrubClassName( call.getClassName() ) ); - updateHashWithString( digest, scrubSignature( call.getSignature() ) ); - if( isClassMatchedUniquely( call.getClassName() ) ) - { - updateHashWithString( digest, call.getMethodName() ); + public void edit(MethodCall call) { + updateHashWithString(digest, scrubClassName(call.getClassName())); + updateHashWithString(digest, scrubSignature(call.getSignature())); + if (isClassMatchedUniquely(call.getClassName())) { + updateHashWithString(digest, call.getMethodName()); } } @Override - public void edit( FieldAccess access ) - { - updateHashWithString( digest, scrubClassName( access.getClassName() ) ); - updateHashWithString( digest, scrubSignature( access.getSignature() ) ); - if( isClassMatchedUniquely( access.getClassName() ) ) - { - updateHashWithString( digest, access.getFieldName() ); + public void edit(FieldAccess access) { + updateHashWithString(digest, scrubClassName(access.getClassName())); + updateHashWithString(digest, scrubSignature(access.getSignature())); + if (isClassMatchedUniquely(access.getClassName())) { + updateHashWithString(digest, access.getFieldName()); } } @Override - public void edit( ConstructorCall call ) - { - updateHashWithString( digest, scrubClassName( call.getClassName() ) ); - updateHashWithString( digest, scrubSignature( call.getSignature() ) ); + public void edit(ConstructorCall call) { + updateHashWithString(digest, scrubClassName(call.getClassName())); + updateHashWithString(digest, scrubSignature(call.getSignature())); } @Override - public void edit( NewExpr expr ) - { - updateHashWithString( digest, scrubClassName( expr.getClassName() ) ); + public void edit(NewExpr expr) { + updateHashWithString(digest, scrubClassName(expr.getClassName())); } - } ); + }); // convert the hash to a hex string - return toHex( digest.digest() ); - } - catch( BadBytecode | NoSuchAlgorithmException | CannotCompileException ex ) - { - throw new Error( ex ); + return toHex(digest.digest()); + } catch (BadBytecode | NoSuchAlgorithmException | CannotCompileException ex) { + throw new Error(ex); } } - private void updateHashWithConstant( MessageDigest digest, ConstPool constants, int index ) - { - ConstPoolEditor editor = new ConstPoolEditor( constants ); - ConstInfoAccessor item = editor.getItem( index ); - if( item.getType() == InfoType.StringInfo ) - { - updateHashWithString( digest, constants.getStringInfo( index ) ); + private void updateHashWithConstant(MessageDigest digest, ConstPool constants, int index) { + ConstPoolEditor editor = new ConstPoolEditor(constants); + ConstInfoAccessor item = editor.getItem(index); + if (item.getType() == InfoType.StringInfo) { + updateHashWithString(digest, constants.getStringInfo(index)); } // TODO: other constants } - private void updateHashWithString( MessageDigest digest, String val ) - { - try - { - digest.update( val.getBytes( "UTF8" ) ); - } - catch( UnsupportedEncodingException ex ) - { - throw new Error( ex ); + private void updateHashWithString(MessageDigest digest, String val) { + try { + digest.update(val.getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + throw new Error(ex); } } - private String toHex( byte[] bytes ) - { + private String toHex(byte[] bytes) { // function taken from: // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java final char[] hexArray = "0123456789ABCDEF".toCharArray(); char[] hexChars = new char[bytes.length * 2]; - for( int j = 0; j < bytes.length; j++ ) - { + for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } - return new String( hexChars ); + return new String(hexChars); } - + @Override - public boolean equals( Object other ) - { - if( other instanceof ClassIdentity ) - { - return equals( (ClassIdentity)other ); + public boolean equals(Object other) { + if (other instanceof ClassIdentity) { + return equals((ClassIdentity)other); } return false; } - public boolean equals( ClassIdentity other ) - { - return m_fields.equals( other.m_fields ) - && m_methods.equals( other.m_methods ) - && m_constructors.equals( other.m_constructors ) - && m_staticInitializer.equals( other.m_staticInitializer ) - && m_extends.equals( other.m_extends ) - && m_implements.equals( other.m_implements ) - && m_implementations.equals( other.m_implementations ) - && m_references.equals( other.m_references ); + public boolean equals(ClassIdentity other) { + return m_fields.equals(other.m_fields) + && m_methods.equals(other.m_methods) + && m_constructors.equals(other.m_constructors) + && m_staticInitializer.equals(other.m_staticInitializer) + && m_extends.equals(other.m_extends) + && m_implements.equals(other.m_implements) + && m_implementations.equals(other.m_implementations) + && m_references.equals(other.m_references); } @Override - public int hashCode( ) - { + public int hashCode() { List objs = Lists.newArrayList(); - objs.addAll( m_fields ); - objs.addAll( m_methods ); - objs.addAll( m_constructors ); - objs.add( m_staticInitializer ); - objs.add( m_extends ); - objs.addAll( m_implements ); - objs.addAll( m_implementations ); - objs.addAll( m_references ); - return Util.combineHashesOrdered( objs ); + objs.addAll(m_fields); + objs.addAll(m_methods); + objs.addAll(m_constructors); + objs.add(m_staticInitializer); + objs.add(m_extends); + objs.addAll(m_implements); + objs.addAll(m_implementations); + objs.addAll(m_references); + return Util.combineHashesOrdered(objs); } - public int getMatchScore( ClassIdentity other ) - { - return getNumMatches( m_fields, other.m_fields ) - + getNumMatches( m_methods, other.m_methods ) - + getNumMatches( m_constructors, other.m_constructors ); + public int getMatchScore(ClassIdentity other) { + return getNumMatches(m_fields, other.m_fields) + + getNumMatches(m_methods, other.m_methods) + + getNumMatches(m_constructors, other.m_constructors); } - public int getMaxMatchScore( ) - { + public int getMaxMatchScore() { return m_fields.size() + m_methods.size() + m_constructors.size(); } - public boolean matches( CtClass c ) - { + public boolean matches(CtClass c) { // just compare declaration counts return m_fields.size() == c.getDeclaredFields().length && m_methods.size() == c.getDeclaredMethods().length && m_constructors.size() == c.getDeclaredConstructors().length; } - private int getNumMatches( Multiset a, Multiset b ) - { + private int getNumMatches(Multiset a, Multiset b) { int numMatches = 0; - for( String val : a ) - { - if( b.contains( val ) ) - { + for (String val : a) { + if (b.contains(val)) { numMatches++; } } diff --git a/src/cuchaz/enigma/convert/ClassMatcher.java b/src/cuchaz/enigma/convert/ClassMatcher.java index 290d90a..fc39ed0 100644 --- a/src/cuchaz/enigma/convert/ClassMatcher.java +++ b/src/cuchaz/enigma/convert/ClassMatcher.java @@ -49,102 +49,92 @@ import cuchaz.enigma.mapping.MappingsWriter; import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.MethodMapping; -public class ClassMatcher -{ - public static void main( String[] args ) - throws IOException, MappingParseException - { +public class ClassMatcher { + + public static void main(String[] args) throws IOException, MappingParseException { // TEMP - JarFile sourceJar = new JarFile( new File( "input/1.8-pre3.jar" ) ); - JarFile destJar = new JarFile( new File( "input/1.8.jar" ) ); - File inMappingsFile = new File( "../Enigma Mappings/1.8-pre3.mappings" ); - File outMappingsFile = new File( "../Enigma Mappings/1.8.mappings" ); + JarFile sourceJar = new JarFile(new File("input/1.8-pre3.jar")); + JarFile destJar = new JarFile(new File("input/1.8.jar")); + File inMappingsFile = new File("../Enigma Mappings/1.8-pre3.mappings"); + File outMappingsFile = new File("../Enigma Mappings/1.8.mappings"); // define a matching to use when the automated system cannot find a match Map fallbackMatching = Maps.newHashMap(); - fallbackMatching.put( "none/ayb", "none/ayf" ); - fallbackMatching.put( "none/ayd", "none/ayd" ); - fallbackMatching.put( "none/bgk", "unknown/bgk" ); + fallbackMatching.put("none/ayb", "none/ayf"); + fallbackMatching.put("none/ayd", "none/ayd"); + fallbackMatching.put("none/bgk", "unknown/bgk"); // do the conversion - Mappings mappings = new MappingsReader().read( new FileReader( inMappingsFile ) ); - convertMappings( sourceJar, destJar, mappings, fallbackMatching ); + Mappings mappings = new MappingsReader().read(new FileReader(inMappingsFile)); + convertMappings(sourceJar, destJar, mappings, fallbackMatching); // write out the converted mappings - FileWriter writer = new FileWriter( outMappingsFile ); - new MappingsWriter().write( writer, mappings ); + FileWriter writer = new FileWriter(outMappingsFile); + new MappingsWriter().write(writer, mappings); writer.close(); - System.out.println( "Wrote converted mappings to:\n\t" + outMappingsFile.getAbsolutePath() ); + System.out.println("Wrote converted mappings to:\n\t" + outMappingsFile.getAbsolutePath()); } - private static void convertMappings( JarFile sourceJar, JarFile destJar, Mappings mappings, Map fallbackMatching ) - { + private static void convertMappings(JarFile sourceJar, JarFile destJar, Mappings mappings, Map fallbackMatching) { // index jars - System.out.println( "Indexing source jar..." ); + System.out.println("Indexing source jar..."); JarIndex sourceIndex = new JarIndex(); - sourceIndex.indexJar( sourceJar, false ); - System.out.println( "Indexing dest jar..." ); + sourceIndex.indexJar(sourceJar, false); + System.out.println("Indexing dest jar..."); JarIndex destIndex = new JarIndex(); - destIndex.indexJar( destJar, false ); - TranslatingTypeLoader sourceLoader = new TranslatingTypeLoader( sourceJar, sourceIndex ); - TranslatingTypeLoader destLoader = new TranslatingTypeLoader( destJar, destIndex ); - + destIndex.indexJar(destJar, false); + TranslatingTypeLoader sourceLoader = new TranslatingTypeLoader(sourceJar, sourceIndex); + TranslatingTypeLoader destLoader = new TranslatingTypeLoader(destJar, destIndex); + // compute the matching - ClassMatching matching = computeMatching( sourceIndex, sourceLoader, destIndex, destLoader ); + ClassMatching matching = computeMatching(sourceIndex, sourceLoader, destIndex, destLoader); Map>> matchingIndex = matching.getIndex(); // get all the obf class names used in the mappings Set usedClassNames = mappings.getAllObfClassNames(); Set allClassNames = Sets.newHashSet(); - for( ClassEntry classEntry : sourceIndex.getObfClassEntries() ) - { - allClassNames.add( classEntry.getName() ); + for (ClassEntry classEntry : sourceIndex.getObfClassEntries()) { + allClassNames.add(classEntry.getName()); } - usedClassNames.retainAll( allClassNames ); - System.out.println( "Used " + usedClassNames.size() + " classes in the mappings" ); + usedClassNames.retainAll(allClassNames); + System.out.println("Used " + usedClassNames.size() + " classes in the mappings"); // probabilistically match the non-uniquely-matched source classes - for( Map.Entry> entry : matchingIndex.values() ) - { + for (Map.Entry> entry : matchingIndex.values()) { ClassIdentity sourceClass = entry.getKey(); List destClasses = entry.getValue(); // skip classes that are uniquely matched - if( destClasses.size() == 1 ) - { + if (destClasses.size() == 1) { continue; } // skip classes that aren't used in the mappings - if( !usedClassNames.contains( sourceClass.getClassEntry().getName() ) ) - { + if (!usedClassNames.contains(sourceClass.getClassEntry().getName())) { continue; } - System.out.println( "No exact match for source class " + sourceClass.getClassEntry() ); + System.out.println("No exact match for source class " + sourceClass.getClassEntry()); // find the closest classes Multimap scoredMatches = ArrayListMultimap.create(); - for( ClassIdentity c : destClasses ) - { - scoredMatches.put( sourceClass.getMatchScore( c ), c ); + for (ClassIdentity c : destClasses) { + scoredMatches.put(sourceClass.getMatchScore(c), c); } - List scores = new ArrayList( scoredMatches.keySet() ); - Collections.sort( scores, Collections.reverseOrder() ); - printScoredMatches( sourceClass.getMaxMatchScore(), scores, scoredMatches ); + List scores = new ArrayList(scoredMatches.keySet()); + Collections.sort(scores, Collections.reverseOrder()); + printScoredMatches(sourceClass.getMaxMatchScore(), scores, scoredMatches); // does the best match have a non-zero score and the same name? - int bestScore = scores.get( 0 ); - Collection bestMatches = scoredMatches.get( bestScore ); - if( bestScore > 0 && bestMatches.size() == 1 ) - { + int bestScore = scores.get(0); + Collection bestMatches = scoredMatches.get(bestScore); + if (bestScore > 0 && bestMatches.size() == 1) { ClassIdentity bestMatch = bestMatches.iterator().next(); - if( bestMatch.getClassEntry().equals( sourceClass.getClassEntry() ) ) - { + if (bestMatch.getClassEntry().equals(sourceClass.getClassEntry())) { // use it - System.out.println( "\tAutomatically choosing likely match: " + bestMatch.getClassEntry().getName() ); + System.out.println("\tAutomatically choosing likely match: " + bestMatch.getClassEntry().getName()); destClasses.clear(); - destClasses.add( bestMatch ); + destClasses.add(bestMatch); } } } @@ -152,63 +142,46 @@ public class ClassMatcher // group the matching into unique and non-unique matches BiMap matchedClassNames = HashBiMap.create(); Set unmatchedSourceClassNames = Sets.newHashSet(); - for( String className : usedClassNames ) - { + for (String className : usedClassNames) { // is there a match for this class? - Map.Entry> entry = matchingIndex.get( className ); + Map.Entry> entry = matchingIndex.get(className); ClassIdentity sourceClass = entry.getKey(); List matches = entry.getValue(); - if( matches.size() == 1 ) - { + if (matches.size() == 1) { // unique match! We're good to go! - matchedClassNames.put( - sourceClass.getClassEntry().getName(), - matches.get( 0 ).getClassEntry().getName() - ); - } - else - { + matchedClassNames.put(sourceClass.getClassEntry().getName(), matches.get(0).getClassEntry().getName()); + } else { // no match, check the fallback matching - String fallbackMatch = fallbackMatching.get( className ); - if( fallbackMatch != null ) - { - matchedClassNames.put( - sourceClass.getClassEntry().getName(), - fallbackMatch - ); - } - else - { - unmatchedSourceClassNames.add( className ); + String fallbackMatch = fallbackMatching.get(className); + if (fallbackMatch != null) { + matchedClassNames.put(sourceClass.getClassEntry().getName(), fallbackMatch); + } else { + unmatchedSourceClassNames.add(className); } } } // report unmatched classes - if( !unmatchedSourceClassNames.isEmpty() ) - { - System.err.println( "ERROR: there were unmatched classes!" ); - for( String className : unmatchedSourceClassNames ) - { - System.err.println( "\t" + className ); + if (!unmatchedSourceClassNames.isEmpty()) { + System.err.println("ERROR: there were unmatched classes!"); + for (String className : unmatchedSourceClassNames) { + System.err.println("\t" + className); } return; } // get the class name changes from the matched class names Map classChanges = Maps.newHashMap(); - for( Map.Entry entry : matchedClassNames.entrySet() ) - { - if( !entry.getKey().equals( entry.getValue() ) ) - { - classChanges.put( entry.getKey(), entry.getValue() ); - System.out.println( String.format( "Class change: %s -> %s", entry.getKey(), entry.getValue() ) ); + for (Map.Entry entry : matchedClassNames.entrySet()) { + if (!entry.getKey().equals(entry.getValue())) { + classChanges.put(entry.getKey(), entry.getValue()); + System.out.println(String.format("Class change: %s -> %s", entry.getKey(), entry.getValue())); /* DEBUG - System.out.println( String.format( "\n%s\n%s", - new ClassIdentity( sourceLoader.loadClass( entry.getKey() ), null, sourceIndex, false, false ), - new ClassIdentity( destLoader.loadClass( entry.getValue() ), null, destIndex, false, false ) - ) ); + System.out.println(String.format("\n%s\n%s", + new ClassIdentity(sourceLoader.loadClass(entry.getKey()), null, sourceIndex, false, false), + new ClassIdentity( destLoader.loadClass(entry.getValue()), null, destIndex, false, false) + )); */ } } @@ -217,52 +190,42 @@ public class ClassMatcher // ie. if we have the mappings a->b, b->c, we have to apply b->c before a->b LinkedHashMap orderedClassChanges = Maps.newLinkedHashMap(); int numChangesLeft = classChanges.size(); - while( !classChanges.isEmpty() ) - { + while (!classChanges.isEmpty()) { Iterator> iter = classChanges.entrySet().iterator(); - while( iter.hasNext() ) - { + while (iter.hasNext()) { Map.Entry entry = iter.next(); - if( classChanges.get( entry.getValue() ) == null ) - { - orderedClassChanges.put( entry.getKey(), entry.getValue() ); + if (classChanges.get(entry.getValue()) == null) { + orderedClassChanges.put(entry.getKey(), entry.getValue()); iter.remove(); } } // did we remove any changes? - if( numChangesLeft - classChanges.size() > 0 ) - { + if (numChangesLeft - classChanges.size() > 0) { // keep going - numChangesLeft = classChanges.size(); - } - else - { + numChangesLeft = classChanges.size(); + } else { // can't sort anymore. There must be a loop break; } } - if( classChanges.size() > 0 ) - { - throw new Error( String.format( "Unable to sort %d/%d class changes!", classChanges.size(), matchedClassNames.size() ) ); + if (classChanges.size() > 0) { + throw new Error(String.format("Unable to sort %d/%d class changes!", classChanges.size(), matchedClassNames.size())); } // convert the mappings in the correct class order - for( Map.Entry entry : orderedClassChanges.entrySet() ) - { - mappings.renameObfClass( entry.getKey(), entry.getValue() ); + for (Map.Entry entry : orderedClassChanges.entrySet()) { + mappings.renameObfClass(entry.getKey(), entry.getValue()); } // check the method matches - System.out.println( "Checking methods..." ); - for( ClassMapping classMapping : mappings.classes() ) - { - ClassEntry classEntry = new ClassEntry( classMapping.getObfName() ); - for( MethodMapping methodMapping : classMapping.methods() ) - { + System.out.println("Checking methods..."); + for (ClassMapping classMapping : mappings.classes()) { + ClassEntry classEntry = new ClassEntry(classMapping.getObfName()); + for (MethodMapping methodMapping : classMapping.methods()) { + // skip constructors - if( methodMapping.getObfName().equals( "" ) ) - { + if (methodMapping.getObfName().equals("")) { continue; } @@ -271,56 +234,51 @@ public class ClassMatcher methodMapping.getObfName(), methodMapping.getObfSignature() ); - if( !destIndex.containsObfBehavior( methodEntry ) ) - { - System.err.println( "WARNING: method doesn't match: " + methodEntry ); + if (!destIndex.containsObfBehavior(methodEntry)) { + System.err.println("WARNING: method doesn't match: " + methodEntry); // show the available methods - System.err.println( "\tAvailable dest methods:" ); - CtClass c = destLoader.loadClass( classMapping.getObfName() ); - for( CtBehavior behavior : c.getDeclaredBehaviors() ) - { + System.err.println("\tAvailable dest methods:"); + CtClass c = destLoader.loadClass(classMapping.getObfName()); + for (CtBehavior behavior : c.getDeclaredBehaviors()) { MethodEntry declaredMethodEntry = new MethodEntry( - new ClassEntry( classMapping.getObfName() ), + new ClassEntry(classMapping.getObfName()), behavior.getName(), behavior.getSignature() ); - System.err.println( "\t\t" + declaredMethodEntry ); + System.err.println("\t\t" + declaredMethodEntry); } - System.err.println( "\tAvailable source methods:" ); - c = sourceLoader.loadClass( matchedClassNames.inverse().get( classMapping.getObfName() ) ); - for( CtBehavior behavior : c.getDeclaredBehaviors() ) - { + System.err.println("\tAvailable source methods:"); + c = sourceLoader.loadClass(matchedClassNames.inverse().get(classMapping.getObfName())); + for (CtBehavior behavior : c.getDeclaredBehaviors()) { MethodEntry declaredMethodEntry = new MethodEntry( - new ClassEntry( classMapping.getObfName() ), + new ClassEntry(classMapping.getObfName()), behavior.getName(), behavior.getSignature() ); - System.err.println( "\t\t" + declaredMethodEntry ); + System.err.println("\t\t" + declaredMethodEntry); } } } } - System.out.println( "Done!" ); + System.out.println("Done!"); } - public static ClassMatching computeMatching( JarIndex sourceIndex, TranslatingTypeLoader sourceLoader, JarIndex destIndex, TranslatingTypeLoader destLoader ) - { - System.out.println( "Matching classes..." ); + public static ClassMatching computeMatching(JarIndex sourceIndex, TranslatingTypeLoader sourceLoader, JarIndex destIndex, TranslatingTypeLoader destLoader) { + + System.out.println("Matching classes..."); + ClassMatching matching = null; - for( boolean useReferences : Arrays.asList( false, true ) ) - { + for (boolean useReferences : Arrays.asList(false, true)) { int numMatches = 0; - do - { + do { SidedClassNamer sourceNamer = null; SidedClassNamer destNamer = null; - if( matching != null ) - { + if (matching != null) { // build a class namer - ClassNamer namer = new ClassNamer( matching.getUniqueMatches() ); + ClassNamer namer = new ClassNamer(matching.getUniqueMatches()); sourceNamer = namer.getSourceNamer(); destNamer = namer.getDestNamer(); @@ -331,158 +289,126 @@ public class ClassMatcher // get the entries left to match Set sourceClassEntries = Sets.newHashSet(); Set destClassEntries = Sets.newHashSet(); - if( matching == null ) - { - sourceClassEntries.addAll( sourceIndex.getObfClassEntries() ); - destClassEntries.addAll( destIndex.getObfClassEntries() ); + if (matching == null) { + sourceClassEntries.addAll(sourceIndex.getObfClassEntries()); + destClassEntries.addAll(destIndex.getObfClassEntries()); matching = new ClassMatching(); - } - else - { - for( Map.Entry,List> entry : matching.getAmbiguousMatches().entrySet() ) - { - for( ClassIdentity c : entry.getKey() ) - { - sourceClassEntries.add( c.getClassEntry() ); - matching.removeSource( c ); + } else { + for (Map.Entry,List> entry : matching.getAmbiguousMatches().entrySet()) { + for (ClassIdentity c : entry.getKey()) { + sourceClassEntries.add(c.getClassEntry()); + matching.removeSource(c); } - for( ClassIdentity c : entry.getValue() ) - { - destClassEntries.add( c.getClassEntry() ); - matching.removeDest( c ); + for (ClassIdentity c : entry.getValue()) { + destClassEntries.add(c.getClassEntry()); + matching.removeDest(c); } } - for( ClassIdentity c : matching.getUnmatchedSourceClasses() ) - { - sourceClassEntries.add( c.getClassEntry() ); - matching.removeSource( c ); + for (ClassIdentity c : matching.getUnmatchedSourceClasses()) { + sourceClassEntries.add(c.getClassEntry()); + matching.removeSource(c); } - for( ClassIdentity c : matching.getUnmatchedDestClasses() ) - { - destClassEntries.add( c.getClassEntry() ); - matching.removeDest( c ); + for (ClassIdentity c : matching.getUnmatchedDestClasses()) { + destClassEntries.add(c.getClassEntry()); + matching.removeDest(c); } } // compute a matching for the classes - for( ClassEntry classEntry : sourceClassEntries ) - { - CtClass c = sourceLoader.loadClass( classEntry.getName() ); - ClassIdentity sourceClass = new ClassIdentity( c, sourceNamer, sourceIndex, useReferences ); - matching.addSource( sourceClass ); + for (ClassEntry classEntry : sourceClassEntries) { + CtClass c = sourceLoader.loadClass(classEntry.getName()); + ClassIdentity sourceClass = new ClassIdentity(c, sourceNamer, sourceIndex, useReferences); + matching.addSource(sourceClass); } - for( ClassEntry classEntry : destClassEntries ) - { - CtClass c = destLoader.loadClass( classEntry.getName() ); - ClassIdentity destClass = new ClassIdentity( c, destNamer, destIndex, useReferences ); - matching.matchDestClass( destClass ); + for (ClassEntry classEntry : destClassEntries) { + CtClass c = destLoader.loadClass(classEntry.getName()); + ClassIdentity destClass = new ClassIdentity(c, destNamer, destIndex, useReferences); + matching.matchDestClass(destClass); } // TEMP - System.out.println( matching ); - } - while( matching.getUniqueMatches().size() - numMatches > 0 ); + System.out.println(matching); + } while (matching.getUniqueMatches().size() - numMatches > 0); } // check the class matches - System.out.println( "Checking class matches..." ); - ClassNamer namer = new ClassNamer( matching.getUniqueMatches() ); + System.out.println("Checking class matches..."); + ClassNamer namer = new ClassNamer(matching.getUniqueMatches()); SidedClassNamer sourceNamer = namer.getSourceNamer(); SidedClassNamer destNamer = namer.getDestNamer(); - for( Map.Entry entry : matching.getUniqueMatches().entrySet() ) - { + for (Map.Entry entry : matching.getUniqueMatches().entrySet()) { + // check source ClassIdentity sourceClass = entry.getKey(); - CtClass sourceC = sourceLoader.loadClass( sourceClass.getClassEntry().getName() ); - assert( sourceC != null ) - : "Unable to load source class " + sourceClass.getClassEntry(); - assert( sourceClass.matches( sourceC ) ) - : "Source " + sourceClass + " doesn't match " + new ClassIdentity( sourceC, sourceNamer, sourceIndex, false ); + CtClass sourceC = sourceLoader.loadClass(sourceClass.getClassEntry().getName()); + assert (sourceC != null) : "Unable to load source class " + sourceClass.getClassEntry(); + assert (sourceClass.matches(sourceC)) : "Source " + sourceClass + " doesn't match " + new ClassIdentity(sourceC, sourceNamer, sourceIndex, false); // check dest ClassIdentity destClass = entry.getValue(); - CtClass destC = destLoader.loadClass( destClass.getClassEntry().getName() ); - assert( destC != null ) - : "Unable to load dest class " + destClass.getClassEntry(); - assert( destClass.matches( destC ) ) - : "Dest " + destClass + " doesn't match " + new ClassIdentity( destC, destNamer, destIndex, false ); + CtClass destC = destLoader.loadClass(destClass.getClassEntry().getName()); + assert (destC != null) : "Unable to load dest class " + destClass.getClassEntry(); + assert (destClass.matches(destC)) : "Dest " + destClass + " doesn't match " + new ClassIdentity(destC, destNamer, destIndex, false); } // warn about the ambiguous matchings - List,List>> ambiguousMatches = new ArrayList,List>>( matching.getAmbiguousMatches().entrySet() ); - Collections.sort( ambiguousMatches, new Comparator,List>>( ) - { + List,List>> ambiguousMatches = new ArrayList,List>>(matching.getAmbiguousMatches().entrySet()); + Collections.sort(ambiguousMatches, new Comparator,List>>() { @Override - public int compare( Map.Entry,List> a, Map.Entry,List> b ) - { - String aName = a.getKey().get( 0 ).getClassEntry().getName(); - String bName = b.getKey().get( 0 ).getClassEntry().getName(); - return aName.compareTo( bName ); + public int compare(Map.Entry,List> a, Map.Entry,List> b) { + String aName = a.getKey().get(0).getClassEntry().getName(); + String bName = b.getKey().get(0).getClassEntry().getName(); + return aName.compareTo(bName); } - } ); - for( Map.Entry,List> entry : ambiguousMatches ) - { - System.out.println( "Ambiguous matching:" ); - System.out.println( "\tSource: " + getClassNames( entry.getKey() ) ); - System.out.println( "\tDest: " + getClassNames( entry.getValue() ) ); + }); + for (Map.Entry,List> entry : ambiguousMatches) { + System.out.println("Ambiguous matching:"); + System.out.println("\tSource: " + getClassNames(entry.getKey())); + System.out.println("\tDest: " + getClassNames(entry.getValue())); } /* DEBUG Map.Entry,List> entry = ambiguousMatches.get( 7 ); - for( ClassIdentity c : entry.getKey() ) - { - System.out.println( c ); + for (ClassIdentity c : entry.getKey()) { + System.out.println(c); } - for( ClassIdentity c : entry.getKey() ) - { - System.out.println( decompile( sourceLoader, c.getClassEntry() ) ); + for(ClassIdentity c : entry.getKey()) { + System.out.println(decompile(sourceLoader, c.getClassEntry())); } */ return matching; } - private static void printScoredMatches( int maxScore, List scores, Multimap scoredMatches ) - { + private static void printScoredMatches(int maxScore, List scores, Multimap scoredMatches) { int numScoredMatchesShown = 0; - for( int score : scores ) - { - for( ClassIdentity scoredMatch : scoredMatches.get( score ) ) - { - System.out.println( String.format( "\tScore: %3d %3.0f%% %s", - score, - 100.0*score/maxScore, - scoredMatch.getClassEntry().getName() - ) ); - - if( numScoredMatchesShown++ > 10 ) - { + for (int score : scores) { + for (ClassIdentity scoredMatch : scoredMatches.get(score)) { + System.out.println(String.format("\tScore: %3d %3.0f%% %s", score, 100.0 * score / maxScore, scoredMatch.getClassEntry().getName())); + if (numScoredMatchesShown++ > 10) { return; } } } } - private static List getClassNames( Collection classes ) - { + private static List getClassNames(Collection classes) { List out = Lists.newArrayList(); - for( ClassIdentity c : classes ) - { - out.add( c.getClassEntry().getName() ); + for (ClassIdentity c : classes) { + out.add(c.getClassEntry().getName()); } - Collections.sort( out ); + Collections.sort(out); return out; } /* DEBUG - private static String decompile( TranslatingTypeLoader loader, ClassEntry classEntry ) - { + private static String decompile(TranslatingTypeLoader loader, ClassEntry classEntry) { PlainTextOutput output = new PlainTextOutput(); DecompilerSettings settings = DecompilerSettings.javaDefaults(); - settings.setForceExplicitImports( true ); - settings.setShowSyntheticMembers( true ); - settings.setTypeLoader( loader ); - Decompiler.decompile( classEntry.getName(), output, settings ); + settings.setForceExplicitImports(true); + settings.setShowSyntheticMembers(true); + settings.setTypeLoader(loader); + Decompiler.decompile(classEntry.getName(), output, settings); return output.toString(); } */ diff --git a/src/cuchaz/enigma/convert/ClassMatching.java b/src/cuchaz/enigma/convert/ClassMatching.java index e45c0e1..53b6f7f 100644 --- a/src/cuchaz/enigma/convert/ClassMatching.java +++ b/src/cuchaz/enigma/convert/ClassMatching.java @@ -24,180 +24,150 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; -public class ClassMatching -{ +public class ClassMatching { + private Multimap m_sourceClasses; private Multimap m_matchedDestClasses; private List m_unmatchedDestClasses; - public ClassMatching( ) - { + public ClassMatching() { m_sourceClasses = ArrayListMultimap.create(); m_matchedDestClasses = ArrayListMultimap.create(); m_unmatchedDestClasses = Lists.newArrayList(); } - - public void addSource( ClassIdentity c ) - { - m_sourceClasses.put( c, c ); + + public void addSource(ClassIdentity c) { + m_sourceClasses.put(c, c); } - public void matchDestClass( ClassIdentity destClass ) - { - Collection matchedSourceClasses = m_sourceClasses.get( destClass ); - if( matchedSourceClasses.isEmpty() ) - { + public void matchDestClass(ClassIdentity destClass) { + Collection matchedSourceClasses = m_sourceClasses.get(destClass); + if (matchedSourceClasses.isEmpty()) { // no match - m_unmatchedDestClasses.add( destClass ); - } - else - { + m_unmatchedDestClasses.add(destClass); + } else { // found a match - m_matchedDestClasses.put( destClass, destClass ); + m_matchedDestClasses.put(destClass, destClass); // DEBUG ClassIdentity sourceClass = matchedSourceClasses.iterator().next(); - assert( sourceClass.hashCode() == destClass.hashCode() ); - assert( sourceClass.equals( destClass ) ); + assert (sourceClass.hashCode() == destClass.hashCode()); + assert (sourceClass.equals(destClass)); } } - public void removeSource( ClassIdentity sourceClass ) - { - m_sourceClasses.remove( sourceClass, sourceClass ); + public void removeSource(ClassIdentity sourceClass) { + m_sourceClasses.remove(sourceClass, sourceClass); } - public void removeDest( ClassIdentity destClass ) - { - m_matchedDestClasses.remove( destClass, destClass ); - m_unmatchedDestClasses.remove( destClass ); + public void removeDest(ClassIdentity destClass) { + m_matchedDestClasses.remove(destClass, destClass); + m_unmatchedDestClasses.remove(destClass); } - public List getSourceClasses( ) - { - return new ArrayList( m_sourceClasses.values() ); + public List getSourceClasses() { + return new ArrayList(m_sourceClasses.values()); } - public List getDestClasses( ) - { + public List getDestClasses() { List classes = Lists.newArrayList(); - classes.addAll( m_matchedDestClasses.values() ); - classes.addAll( m_unmatchedDestClasses ); + classes.addAll(m_matchedDestClasses.values()); + classes.addAll(m_unmatchedDestClasses); return classes; } - public BiMap getUniqueMatches( ) - { + public BiMap getUniqueMatches() { BiMap uniqueMatches = HashBiMap.create(); - for( ClassIdentity sourceClass : m_sourceClasses.keySet() ) - { - Collection matchedSourceClasses = m_sourceClasses.get( sourceClass ); - Collection matchedDestClasses = m_matchedDestClasses.get( sourceClass ); - if( matchedSourceClasses.size() == 1 && matchedDestClasses.size() == 1 ) - { + for (ClassIdentity sourceClass : m_sourceClasses.keySet()) { + Collection matchedSourceClasses = m_sourceClasses.get(sourceClass); + Collection matchedDestClasses = m_matchedDestClasses.get(sourceClass); + if (matchedSourceClasses.size() == 1 && matchedDestClasses.size() == 1) { ClassIdentity matchedSourceClass = matchedSourceClasses.iterator().next(); ClassIdentity matchedDestClass = matchedDestClasses.iterator().next(); - uniqueMatches.put( matchedSourceClass, matchedDestClass ); + uniqueMatches.put(matchedSourceClass, matchedDestClass); } } return uniqueMatches; } - public BiMap,List> getAmbiguousMatches( ) - { + public BiMap,List> getAmbiguousMatches() { BiMap,List> ambiguousMatches = HashBiMap.create(); - for( ClassIdentity sourceClass : m_sourceClasses.keySet() ) - { - Collection matchedSourceClasses = m_sourceClasses.get( sourceClass ); - Collection matchedDestClasses = m_matchedDestClasses.get( sourceClass ); - if( matchedSourceClasses.size() > 1 && matchedDestClasses.size() > 1 ) - { + for (ClassIdentity sourceClass : m_sourceClasses.keySet()) { + Collection matchedSourceClasses = m_sourceClasses.get(sourceClass); + Collection matchedDestClasses = m_matchedDestClasses.get(sourceClass); + if (matchedSourceClasses.size() > 1 && matchedDestClasses.size() > 1) { ambiguousMatches.put( - new ArrayList( matchedSourceClasses ), - new ArrayList( matchedDestClasses ) + new ArrayList(matchedSourceClasses), + new ArrayList(matchedDestClasses) ); } } return ambiguousMatches; } - public int getNumAmbiguousSourceMatches( ) - { + public int getNumAmbiguousSourceMatches() { int num = 0; - for( Map.Entry,List> entry : getAmbiguousMatches().entrySet() ) - { + for (Map.Entry,List> entry : getAmbiguousMatches().entrySet()) { num += entry.getKey().size(); } return num; } - public int getNumAmbiguousDestMatches( ) - { + public int getNumAmbiguousDestMatches() { int num = 0; - for( Map.Entry,List> entry : getAmbiguousMatches().entrySet() ) - { + for (Map.Entry,List> entry : getAmbiguousMatches().entrySet()) { num += entry.getValue().size(); } return num; } - public List getUnmatchedSourceClasses( ) - { + public List getUnmatchedSourceClasses() { List classes = Lists.newArrayList(); - for( ClassIdentity sourceClass : getSourceClasses() ) - { - if( m_matchedDestClasses.get( sourceClass ).isEmpty() ) - { - classes.add( sourceClass ); + for (ClassIdentity sourceClass : getSourceClasses()) { + if (m_matchedDestClasses.get(sourceClass).isEmpty()) { + classes.add(sourceClass); } } return classes; } - public List getUnmatchedDestClasses( ) - { - return new ArrayList( m_unmatchedDestClasses ); + public List getUnmatchedDestClasses() { + return new ArrayList(m_unmatchedDestClasses); } - public Map>> getIndex( ) - { + public Map>> getIndex() { Map>> conversion = Maps.newHashMap(); - for( Map.Entry entry : getUniqueMatches().entrySet() ) - { + for (Map.Entry entry : getUniqueMatches().entrySet()) { conversion.put( entry.getKey().getClassEntry().getName(), - new AbstractMap.SimpleEntry>( entry.getKey(), Arrays.asList( entry.getValue() ) ) + new AbstractMap.SimpleEntry>(entry.getKey(), Arrays.asList(entry.getValue())) ); } - for( Map.Entry,List> entry : getAmbiguousMatches().entrySet() ) - { - for( ClassIdentity sourceClass : entry.getKey() ) - { + for (Map.Entry,List> entry : getAmbiguousMatches().entrySet()) { + for (ClassIdentity sourceClass : entry.getKey()) { conversion.put( sourceClass.getClassEntry().getName(), - new AbstractMap.SimpleEntry>( sourceClass, entry.getValue() ) + new AbstractMap.SimpleEntry>(sourceClass, entry.getValue()) ); } } - for( ClassIdentity sourceClass : getUnmatchedSourceClasses() ) - { + for (ClassIdentity sourceClass : getUnmatchedSourceClasses()) { conversion.put( sourceClass.getClassEntry().getName(), - new AbstractMap.SimpleEntry>( sourceClass, getUnmatchedDestClasses() ) + new AbstractMap.SimpleEntry>(sourceClass, getUnmatchedDestClasses()) ); } return conversion; } @Override - public String toString( ) - { + public String toString() { StringBuilder buf = new StringBuilder(); - buf.append( String.format( "%12s%8s%8s\n", "", "Source", "Dest" ) ); - buf.append( String.format( "%12s%8d%8d\n", "Classes", getSourceClasses().size(), getDestClasses().size() ) ); - buf.append( String.format( "%12s%8d%8d\n", "Unique", getUniqueMatches().size(), getUniqueMatches().size() ) ); - buf.append( String.format( "%12s%8d%8d\n", "Ambiguous", getNumAmbiguousSourceMatches(), getNumAmbiguousDestMatches() ) ); - buf.append( String.format( "%12s%8d%8d\n", "Unmatched", getUnmatchedSourceClasses().size(), getUnmatchedDestClasses().size() ) ); + buf.append(String.format("%12s%8s%8s\n", "", "Source", "Dest")); + buf.append(String.format("%12s%8d%8d\n", "Classes", getSourceClasses().size(), getDestClasses().size())); + buf.append(String.format("%12s%8d%8d\n", "Unique", getUniqueMatches().size(), getUniqueMatches().size())); + buf.append(String.format("%12s%8d%8d\n", "Ambiguous", getNumAmbiguousSourceMatches(), getNumAmbiguousDestMatches())); + buf.append(String.format("%12s%8d%8d\n", "Unmatched", getUnmatchedSourceClasses().size(), getUnmatchedDestClasses().size())); return buf.toString(); } } diff --git a/src/cuchaz/enigma/convert/ClassNamer.java b/src/cuchaz/enigma/convert/ClassNamer.java index a01aec5..1b6e81c 100644 --- a/src/cuchaz/enigma/convert/ClassNamer.java +++ b/src/cuchaz/enigma/convert/ClassNamer.java @@ -15,60 +15,49 @@ import java.util.Map; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; -public class ClassNamer -{ - public interface SidedClassNamer - { - String getName( String name ); +public class ClassNamer { + + public interface SidedClassNamer { + String getName(String name); } private Map m_sourceNames; private Map m_destNames; - public ClassNamer( BiMap mappings ) - { + public ClassNamer(BiMap mappings) { // convert the identity mappings to name maps m_sourceNames = Maps.newHashMap(); m_destNames = Maps.newHashMap(); int i = 0; - for( Map.Entry entry : mappings.entrySet() ) - { - String name = String.format( "M%04d", i++ ); - m_sourceNames.put( entry.getKey().getClassEntry().getName(), name ); - m_destNames.put( entry.getValue().getClassEntry().getName(), name ); + for (Map.Entry entry : mappings.entrySet()) { + String name = String.format("M%04d", i++); + m_sourceNames.put(entry.getKey().getClassEntry().getName(), name); + m_destNames.put(entry.getValue().getClassEntry().getName(), name); } } - public String getSourceName( String name ) - { - return m_sourceNames.get( name ); + public String getSourceName(String name) { + return m_sourceNames.get(name); } - public String getDestName( String name ) - { - return m_destNames.get( name ); + public String getDestName(String name) { + return m_destNames.get(name); } - public SidedClassNamer getSourceNamer( ) - { - return new SidedClassNamer( ) - { + public SidedClassNamer getSourceNamer() { + return new SidedClassNamer() { @Override - public String getName( String name ) - { - return getSourceName( name ); + public String getName(String name) { + return getSourceName(name); } }; } - public SidedClassNamer getDestNamer( ) - { - return new SidedClassNamer( ) - { + public SidedClassNamer getDestNamer() { + return new SidedClassNamer() { @Override - public String getName( String name ) - { - return getDestName( name ); + public String getName(String name) { + return getDestName(name); } }; } diff --git a/src/cuchaz/enigma/gui/AboutDialog.java b/src/cuchaz/enigma/gui/AboutDialog.java index a245956..2476b56 100644 --- a/src/cuchaz/enigma/gui/AboutDialog.java +++ b/src/cuchaz/enigma/gui/AboutDialog.java @@ -27,68 +27,60 @@ import javax.swing.WindowConstants; import cuchaz.enigma.Constants; import cuchaz.enigma.Util; -public class AboutDialog -{ - public static void show( JFrame parent ) - { +public class AboutDialog { + + public static void show(JFrame parent) { // init frame - final JFrame frame = new JFrame( Constants.Name + " - About" ); + final JFrame frame = new JFrame(Constants.Name + " - About"); final Container pane = frame.getContentPane(); - pane.setLayout( new FlowLayout() ); + pane.setLayout(new FlowLayout()); // load the content - try - { - String html = Util.readResourceToString( "/about.html" ); - html = String.format( html, Constants.Name, Constants.Version ); - JLabel label = new JLabel( html ); - label.setHorizontalAlignment( JLabel.CENTER ); - pane.add( label ); - } - catch( IOException ex ) - { - throw new Error( ex ); + try { + String html = Util.readResourceToString("/about.html"); + html = String.format(html, Constants.Name, Constants.Version); + JLabel label = new JLabel(html); + label.setHorizontalAlignment(JLabel.CENTER); + pane.add(label); + } catch (IOException ex) { + throw new Error(ex); } // show the link String html = "%s"; - html = String.format( html, Constants.Url, Constants.Url ); - JButton link = new JButton( html ); - link.addActionListener( new ActionListener( ) - { + html = String.format(html, Constants.Url, Constants.Url); + JButton link = new JButton(html); + link.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - Util.openUrl( Constants.Url ); + public void actionPerformed(ActionEvent event) { + Util.openUrl(Constants.Url); } - } ); - link.setBorderPainted( false ); - link.setOpaque( false ); - link.setBackground( Color.WHITE ); - link.setCursor( new Cursor( Cursor.HAND_CURSOR ) ); - link.setFocusable( false ); + }); + link.setBorderPainted(false); + link.setOpaque(false); + link.setBackground(Color.WHITE); + link.setCursor(new Cursor(Cursor.HAND_CURSOR)); + link.setFocusable(false); JPanel linkPanel = new JPanel(); - linkPanel.add( link ); - pane.add( linkPanel ); + linkPanel.add(link); + pane.add(linkPanel); // show ok button - JButton okButton = new JButton( "Ok" ); - pane.add( okButton ); - okButton.addActionListener( new ActionListener( ) - { + JButton okButton = new JButton("Ok"); + pane.add(okButton); + okButton.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent arg0 ) - { + public void actionPerformed(ActionEvent arg0) { frame.dispose(); } - } ); + }); // show the frame pane.doLayout(); - frame.setSize( 400, 220 ); - frame.setResizable( false ); - frame.setLocationRelativeTo( parent ); - frame.setVisible( true ); - frame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE ); + frame.setSize(400, 220); + frame.setResizable(false); + frame.setLocationRelativeTo(parent); + frame.setVisible(true); + frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } } diff --git a/src/cuchaz/enigma/gui/BoxHighlightPainter.java b/src/cuchaz/enigma/gui/BoxHighlightPainter.java index df63f5a..db7c85b 100644 --- a/src/cuchaz/enigma/gui/BoxHighlightPainter.java +++ b/src/cuchaz/enigma/gui/BoxHighlightPainter.java @@ -19,40 +19,35 @@ import javax.swing.text.BadLocationException; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; -public abstract class BoxHighlightPainter implements Highlighter.HighlightPainter -{ +public abstract class BoxHighlightPainter implements Highlighter.HighlightPainter { + private Color m_fillColor; private Color m_borderColor; - protected BoxHighlightPainter( Color fillColor, Color borderColor ) - { + protected BoxHighlightPainter(Color fillColor, Color borderColor) { m_fillColor = fillColor; m_borderColor = borderColor; } @Override - public void paint( Graphics g, int start, int end, Shape shape, JTextComponent text ) - { - Rectangle bounds = getBounds( text, start, end ); + public void paint(Graphics g, int start, int end, Shape shape, JTextComponent text) { + Rectangle bounds = getBounds(text, start, end); // fill the area - if( m_fillColor != null ) - { - g.setColor( m_fillColor ); - g.fillRoundRect( bounds.x, bounds.y, bounds.width, bounds.height, 4, 4 ); + if (m_fillColor != null) { + g.setColor(m_fillColor); + g.fillRoundRect(bounds.x, bounds.y, bounds.width, bounds.height, 4, 4); } // draw a box around the area - g.setColor( m_borderColor ); - g.drawRoundRect( bounds.x, bounds.y, bounds.width, bounds.height, 4, 4 ); + g.setColor(m_borderColor); + g.drawRoundRect(bounds.x, bounds.y, bounds.width, bounds.height, 4, 4); } - protected static Rectangle getBounds( JTextComponent text, int start, int end ) - { - try - { + protected static Rectangle getBounds(JTextComponent text, int start, int end) { + try { // determine the bounds of the text - Rectangle bounds = text.modelToView( start ).union( text.modelToView( end ) ); + Rectangle bounds = text.modelToView(start).union(text.modelToView(end)); // adjust the box so it looks nice bounds.x -= 2; @@ -61,11 +56,9 @@ public abstract class BoxHighlightPainter implements Highlighter.HighlightPainte bounds.height -= 2; return bounds; - } - catch( BadLocationException ex ) - { + } catch (BadLocationException ex) { // don't care... just return something - return new Rectangle( 0, 0, 0, 0 ); + return new Rectangle(0, 0, 0, 0); } } } diff --git a/src/cuchaz/enigma/gui/BrowserCaret.java b/src/cuchaz/enigma/gui/BrowserCaret.java index f7e608b..acee483 100644 --- a/src/cuchaz/enigma/gui/BrowserCaret.java +++ b/src/cuchaz/enigma/gui/BrowserCaret.java @@ -17,34 +17,29 @@ import javax.swing.text.DefaultCaret; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; -public class BrowserCaret extends DefaultCaret -{ +public class BrowserCaret extends DefaultCaret { + private static final long serialVersionUID = 1158977422507969940L; - private static final Highlighter.HighlightPainter m_selectionPainter = new Highlighter.HighlightPainter( ) - { + private static final Highlighter.HighlightPainter m_selectionPainter = new Highlighter.HighlightPainter() { @Override - public void paint( Graphics g, int p0, int p1, Shape bounds, JTextComponent c ) - { + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { // don't paint anything } }; @Override - public boolean isSelectionVisible( ) - { + public boolean isSelectionVisible() { return false; } - + @Override - public boolean isVisible( ) - { + public boolean isVisible() { return true; } @Override - public Highlighter.HighlightPainter getSelectionPainter( ) - { + public Highlighter.HighlightPainter getSelectionPainter() { return m_selectionPainter; } } diff --git a/src/cuchaz/enigma/gui/ClassListCellRenderer.java b/src/cuchaz/enigma/gui/ClassListCellRenderer.java index d9d6578..d0f01e6 100644 --- a/src/cuchaz/enigma/gui/ClassListCellRenderer.java +++ b/src/cuchaz/enigma/gui/ClassListCellRenderer.java @@ -19,20 +19,18 @@ import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; -public class ClassListCellRenderer implements ListCellRenderer -{ +public class ClassListCellRenderer implements ListCellRenderer { + private DefaultListCellRenderer m_defaultRenderer; - public ClassListCellRenderer( ) - { + public ClassListCellRenderer() { m_defaultRenderer = new DefaultListCellRenderer(); } @Override - public Component getListCellRendererComponent( JList list, String className, int index, boolean isSelected, boolean hasFocus ) - { - JLabel label = (JLabel)m_defaultRenderer.getListCellRendererComponent( list, className, index, isSelected, hasFocus ); - label.setText( Descriptor.toJavaName( className ) ); + public Component getListCellRendererComponent(JList list, String className, int index, boolean isSelected, boolean hasFocus) { + JLabel label = (JLabel)m_defaultRenderer.getListCellRendererComponent(list, className, index, isSelected, hasFocus); + label.setText(Descriptor.toJavaName(className)); return label; } } diff --git a/src/cuchaz/enigma/gui/ClassSelector.java b/src/cuchaz/enigma/gui/ClassSelector.java index 8365def..654bfbe 100644 --- a/src/cuchaz/enigma/gui/ClassSelector.java +++ b/src/cuchaz/enigma/gui/ClassSelector.java @@ -30,39 +30,32 @@ import com.google.common.collect.Multimap; import cuchaz.enigma.mapping.ClassEntry; -public class ClassSelector extends JTree -{ +public class ClassSelector extends JTree { + private static final long serialVersionUID = -7632046902384775977L; - public interface ClassSelectionListener - { - void onSelectClass( ClassEntry classEntry ); + public interface ClassSelectionListener { + void onSelectClass(ClassEntry classEntry); } public static Comparator ObfuscatedClassEntryComparator; public static Comparator DeobfuscatedClassEntryComparator; - static - { - ObfuscatedClassEntryComparator = new Comparator( ) - { + static { + ObfuscatedClassEntryComparator = new Comparator() { @Override - public int compare( ClassEntry a, ClassEntry b ) - { - if( a.getName().length() != b.getName().length() ) - { + public int compare(ClassEntry a, ClassEntry b) { + if (a.getName().length() != b.getName().length()) { return a.getName().length() - b.getName().length(); } - return a.getName().compareTo( b.getName() ); + return a.getName().compareTo(b.getName()); } }; - DeobfuscatedClassEntryComparator = new Comparator( ) - { + DeobfuscatedClassEntryComparator = new Comparator() { @Override - public int compare( ClassEntry a, ClassEntry b ) - { - return a.getName().compareTo( b.getName() ); + public int compare(ClassEntry a, ClassEntry b) { + return a.getName().compareTo(b.getName()); } }; } @@ -70,122 +63,102 @@ public class ClassSelector extends JTree private ClassSelectionListener m_listener; private Comparator m_comparator; - public ClassSelector( Comparator comparator ) - { + public ClassSelector(Comparator comparator) { m_comparator = comparator; // configure the tree control - setRootVisible( false ); - setShowsRootHandles( false ); - setModel( null ); + setRootVisible(false); + setShowsRootHandles(false); + setModel(null); // hook events - addMouseListener( new MouseAdapter() - { + addMouseListener(new MouseAdapter() { @Override - public void mouseClicked( MouseEvent event ) - { - if( m_listener != null && event.getClickCount() == 2 ) - { + public void mouseClicked(MouseEvent event) { + if (m_listener != null && event.getClickCount() == 2) { // get the selected node TreePath path = getSelectionPath(); - if( path != null && path.getLastPathComponent() instanceof ClassSelectorClassNode ) - { + if (path != null && path.getLastPathComponent() instanceof ClassSelectorClassNode) { ClassSelectorClassNode node = (ClassSelectorClassNode)path.getLastPathComponent(); - m_listener.onSelectClass( node.getClassEntry() ); + m_listener.onSelectClass(node.getClassEntry()); } } } - } ); + }); // init defaults m_listener = null; } - public void setListener( ClassSelectionListener val ) - { + public void setListener(ClassSelectionListener val) { m_listener = val; } - public void setClasses( Collection classEntries ) - { - if( classEntries == null ) - { - setModel( null ); + public void setClasses(Collection classEntries) { + if (classEntries == null) { + setModel(null); return; } // build the package names Map packages = Maps.newHashMap(); - for( ClassEntry classEntry : classEntries ) - { - packages.put( classEntry.getPackageName(), null ); + for (ClassEntry classEntry : classEntries) { + packages.put(classEntry.getPackageName(), null); } // sort the packages - List sortedPackageNames = Lists.newArrayList( packages.keySet() ); - Collections.sort( sortedPackageNames, new Comparator( ) - { + List sortedPackageNames = Lists.newArrayList(packages.keySet()); + Collections.sort(sortedPackageNames, new Comparator() { @Override - public int compare( String a, String b ) - { + public int compare(String a, String b) { // I can never keep this rule straight when writing these damn things... // a < b => -1, a == b => 0, a > b => +1 - String[] aparts = a.split( "/" ); - String[] bparts = b.split( "/" ); - for( int i=0; true; i++ ) - { - if( i >= aparts.length ) - { + String[] aparts = a.split("/"); + String[] bparts = b.split("/"); + for (int i = 0; true; i++) { + if (i >= aparts.length) { return -1; - } - else if( i >= bparts.length ) - { + } else if (i >= bparts.length) { return 1; } - int result = aparts[i].compareTo( bparts[i] ); - if( result != 0 ) - { + int result = aparts[i].compareTo(bparts[i]); + if (result != 0) { return result; } } } - } ); + }); // create the root node and the package nodes DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - for( String packageName : sortedPackageNames ) - { - ClassSelectorPackageNode node = new ClassSelectorPackageNode( packageName ); - packages.put( packageName, node ); - root.add( node ); + for (String packageName : sortedPackageNames) { + ClassSelectorPackageNode node = new ClassSelectorPackageNode(packageName); + packages.put(packageName, node); + root.add(node); } // put the classes into packages Multimap packagedClassEntries = ArrayListMultimap.create(); - for( ClassEntry classEntry : classEntries ) - { - packagedClassEntries.put( classEntry.getPackageName(), classEntry ); + for (ClassEntry classEntry : classEntries) { + packagedClassEntries.put(classEntry.getPackageName(), classEntry); } // build the class nodes - for( String packageName : packagedClassEntries.keySet() ) - { + for (String packageName : packagedClassEntries.keySet()) { // sort the class entries - List classEntriesInPackage = Lists.newArrayList( packagedClassEntries.get( packageName ) ); - Collections.sort( classEntriesInPackage, m_comparator ); + List classEntriesInPackage = Lists.newArrayList(packagedClassEntries.get(packageName)); + Collections.sort(classEntriesInPackage, m_comparator); // create the nodes in order - for( ClassEntry classEntry : classEntriesInPackage ) - { - ClassSelectorPackageNode node = packages.get( packageName ); - node.add( new ClassSelectorClassNode( classEntry ) ); + for (ClassEntry classEntry : classEntriesInPackage) { + ClassSelectorPackageNode node = packages.get(packageName); + node.add(new ClassSelectorClassNode(classEntry)); } } // finally, update the tree control - setModel( new DefaultTreeModel( root ) ); + setModel(new DefaultTreeModel(root)); } } diff --git a/src/cuchaz/enigma/gui/ClassSelectorClassNode.java b/src/cuchaz/enigma/gui/ClassSelectorClassNode.java index cffa795..66e931b 100644 --- a/src/cuchaz/enigma/gui/ClassSelectorClassNode.java +++ b/src/cuchaz/enigma/gui/ClassSelectorClassNode.java @@ -14,25 +14,22 @@ import javax.swing.tree.DefaultMutableTreeNode; import cuchaz.enigma.mapping.ClassEntry; -public class ClassSelectorClassNode extends DefaultMutableTreeNode -{ +public class ClassSelectorClassNode extends DefaultMutableTreeNode { + private static final long serialVersionUID = -8956754339813257380L; private ClassEntry m_classEntry; - public ClassSelectorClassNode( ClassEntry classEntry ) - { + public ClassSelectorClassNode(ClassEntry classEntry) { m_classEntry = classEntry; } - public ClassEntry getClassEntry( ) - { + public ClassEntry getClassEntry() { return m_classEntry; } @Override - public String toString( ) - { + public String toString() { return m_classEntry.getSimpleName(); } } diff --git a/src/cuchaz/enigma/gui/ClassSelectorPackageNode.java b/src/cuchaz/enigma/gui/ClassSelectorPackageNode.java index ad88fb4..451d380 100644 --- a/src/cuchaz/enigma/gui/ClassSelectorPackageNode.java +++ b/src/cuchaz/enigma/gui/ClassSelectorPackageNode.java @@ -12,25 +12,22 @@ package cuchaz.enigma.gui; import javax.swing.tree.DefaultMutableTreeNode; -public class ClassSelectorPackageNode extends DefaultMutableTreeNode -{ +public class ClassSelectorPackageNode extends DefaultMutableTreeNode { + private static final long serialVersionUID = -3730868701219548043L; private String m_packageName; - public ClassSelectorPackageNode( String packageName ) - { + public ClassSelectorPackageNode(String packageName) { m_packageName = packageName; } - public String getPackageName( ) - { + public String getPackageName() { return m_packageName; } @Override - public String toString( ) - { + public String toString() { return m_packageName; } } diff --git a/src/cuchaz/enigma/gui/CrashDialog.java b/src/cuchaz/enigma/gui/CrashDialog.java index 0eb9830..360091a 100644 --- a/src/cuchaz/enigma/gui/CrashDialog.java +++ b/src/cuchaz/enigma/gui/CrashDialog.java @@ -29,80 +29,73 @@ import javax.swing.WindowConstants; import cuchaz.enigma.Constants; -public class CrashDialog -{ +public class CrashDialog { + private static CrashDialog m_instance = null; private JFrame m_frame; private JTextArea m_text; - private CrashDialog( JFrame parent ) - { + private CrashDialog(JFrame parent) { // init frame - m_frame = new JFrame( Constants.Name + " - Crash Report" ); + m_frame = new JFrame(Constants.Name + " - Crash Report"); final Container pane = m_frame.getContentPane(); - pane.setLayout( new BorderLayout() ); + pane.setLayout(new BorderLayout()); - JLabel label = new JLabel( Constants.Name + " has crashed! =(" ); - label.setBorder( BorderFactory.createEmptyBorder( 10, 10, 10, 10 ) ); - pane.add( label, BorderLayout.NORTH ); + JLabel label = new JLabel(Constants.Name + " has crashed! =("); + label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + pane.add(label, BorderLayout.NORTH); // report panel m_text = new JTextArea(); - m_text.setTabSize( 2 ); - pane.add( new JScrollPane( m_text ), BorderLayout.CENTER ); + m_text.setTabSize(2); + pane.add(new JScrollPane(m_text), BorderLayout.CENTER); // buttons panel JPanel buttonsPanel = new JPanel(); FlowLayout buttonsLayout = new FlowLayout(); - buttonsLayout.setAlignment( FlowLayout.RIGHT ); - buttonsPanel.setLayout( buttonsLayout ); - buttonsPanel.add( GuiTricks.unboldLabel( new JLabel( "If you choose exit, you will lose any unsaved work." ) ) ); - JButton ignoreButton = new JButton( "Ignore" ); - ignoreButton.addActionListener( new ActionListener( ) - { + buttonsLayout.setAlignment(FlowLayout.RIGHT); + buttonsPanel.setLayout(buttonsLayout); + buttonsPanel.add(GuiTricks.unboldLabel(new JLabel("If you choose exit, you will lose any unsaved work."))); + JButton ignoreButton = new JButton("Ignore"); + ignoreButton.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { // close (hide) the dialog - m_frame.setVisible( false ); + m_frame.setVisible(false); } - } ); - buttonsPanel.add( ignoreButton ); - JButton exitButton = new JButton( "Exit" ); - exitButton.addActionListener( new ActionListener( ) - { + }); + buttonsPanel.add(ignoreButton); + JButton exitButton = new JButton("Exit"); + exitButton.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { // exit enigma - System.exit( 1 ); + System.exit(1); } - } ); - buttonsPanel.add( exitButton ); - pane.add( buttonsPanel, BorderLayout.SOUTH ); + }); + buttonsPanel.add(exitButton); + pane.add(buttonsPanel, BorderLayout.SOUTH); // show the frame - m_frame.setSize( 600, 400 ); - m_frame.setLocationRelativeTo( parent ); - m_frame.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); + m_frame.setSize(600, 400); + m_frame.setLocationRelativeTo(parent); + m_frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); } - public static void init( JFrame parent ) - { - m_instance = new CrashDialog( parent ); + public static void init(JFrame parent) { + m_instance = new CrashDialog(parent); } - public static void show( Throwable ex ) - { + public static void show(Throwable ex) { // get the error report StringWriter buf = new StringWriter(); - ex.printStackTrace( new PrintWriter( buf ) ); + ex.printStackTrace(new PrintWriter(buf)); String report = buf.toString(); // show it! - m_instance.m_text.setText( report ); + m_instance.m_text.setText(report); m_instance.m_frame.doLayout(); - m_instance.m_frame.setVisible( true ); + m_instance.m_frame.setVisible(true); } } diff --git a/src/cuchaz/enigma/gui/DeobfuscatedHighlightPainter.java b/src/cuchaz/enigma/gui/DeobfuscatedHighlightPainter.java index 6a42884..26a3163 100644 --- a/src/cuchaz/enigma/gui/DeobfuscatedHighlightPainter.java +++ b/src/cuchaz/enigma/gui/DeobfuscatedHighlightPainter.java @@ -12,11 +12,10 @@ package cuchaz.enigma.gui; import java.awt.Color; -public class DeobfuscatedHighlightPainter extends BoxHighlightPainter -{ - public DeobfuscatedHighlightPainter( ) - { +public class DeobfuscatedHighlightPainter extends BoxHighlightPainter { + + public DeobfuscatedHighlightPainter() { // green ish - super( new Color( 220, 255, 220 ), new Color( 80, 160, 80 ) ); + super(new Color(220, 255, 220), new Color(80, 160, 80)); } } diff --git a/src/cuchaz/enigma/gui/Gui.java b/src/cuchaz/enigma/gui/Gui.java index faa9b7b..86ba93b 100644 --- a/src/cuchaz/enigma/gui/Gui.java +++ b/src/cuchaz/enigma/gui/Gui.java @@ -88,8 +88,8 @@ import cuchaz.enigma.mapping.IllegalNameException; import cuchaz.enigma.mapping.MappingParseException; import cuchaz.enigma.mapping.MethodEntry; -public class Gui -{ +public class Gui { + private GuiController m_controller; // controls @@ -133,81 +133,74 @@ public class Gui private JFileChooser m_exportSourceFileChooser; private JFileChooser m_exportJarFileChooser; - public Gui( ) - { + public Gui() { + // init frame - m_frame = new JFrame( Constants.Name ); + m_frame = new JFrame(Constants.Name); final Container pane = m_frame.getContentPane(); - pane.setLayout( new BorderLayout() ); + pane.setLayout(new BorderLayout()); - if( Boolean.parseBoolean( System.getProperty( "enigma.catchExceptions", "true" ) ) ) - { + if (Boolean.parseBoolean(System.getProperty("enigma.catchExceptions", "true"))) { // install a global exception handler to the event thread - CrashDialog.init( m_frame ); - Thread.setDefaultUncaughtExceptionHandler( new UncaughtExceptionHandler( ) - { + CrashDialog.init(m_frame); + Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override - public void uncaughtException( Thread thread, Throwable ex ) - { - ex.printStackTrace( System.err ); - CrashDialog.show( ex ); + public void uncaughtException(Thread thread, Throwable ex) { + ex.printStackTrace(System.err); + CrashDialog.show(ex); } - } ); + }); } - m_controller = new GuiController( this ); + m_controller = new GuiController(this); // init file choosers m_jarFileChooser = new JFileChooser(); m_mappingsFileChooser = new JFileChooser(); m_exportSourceFileChooser = new JFileChooser(); - m_exportSourceFileChooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY ); + m_exportSourceFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); m_exportJarFileChooser = new JFileChooser(); // init obfuscated classes list - m_obfClasses = new ClassSelector( ClassSelector.ObfuscatedClassEntryComparator ); - m_obfClasses.setListener( new ClassSelectionListener( ) - { + m_obfClasses = new ClassSelector(ClassSelector.ObfuscatedClassEntryComparator); + m_obfClasses.setListener(new ClassSelectionListener() { @Override - public void onSelectClass( ClassEntry classEntry ) - { - navigateTo( classEntry ); + public void onSelectClass(ClassEntry classEntry) { + navigateTo(classEntry); } - } ); - JScrollPane obfScroller = new JScrollPane( m_obfClasses ); + }); + JScrollPane obfScroller = new JScrollPane(m_obfClasses); JPanel obfPanel = new JPanel(); - obfPanel.setLayout( new BorderLayout() ); - obfPanel.add( new JLabel( "Obfuscated Classes" ), BorderLayout.NORTH ); - obfPanel.add( obfScroller, BorderLayout.CENTER ); + obfPanel.setLayout(new BorderLayout()); + obfPanel.add(new JLabel("Obfuscated Classes"), BorderLayout.NORTH); + obfPanel.add(obfScroller, BorderLayout.CENTER); // init deobfuscated classes list - m_deobfClasses = new ClassSelector( ClassSelector.DeobfuscatedClassEntryComparator ); - m_deobfClasses.setListener( new ClassSelectionListener( ) - { + m_deobfClasses = new ClassSelector(ClassSelector.DeobfuscatedClassEntryComparator); + m_deobfClasses.setListener(new ClassSelectionListener() { @Override - public void onSelectClass( ClassEntry classEntry ) - { - navigateTo( classEntry ); + public void onSelectClass(ClassEntry classEntry) { + navigateTo(classEntry); } - } ); - JScrollPane deobfScroller = new JScrollPane( m_deobfClasses ); + }); + JScrollPane deobfScroller = new JScrollPane(m_deobfClasses); JPanel deobfPanel = new JPanel(); - deobfPanel.setLayout( new BorderLayout() ); - deobfPanel.add( new JLabel( "De-obfuscated Classes" ), BorderLayout.NORTH ); - deobfPanel.add( deobfScroller, BorderLayout.CENTER ); + deobfPanel.setLayout(new BorderLayout()); + deobfPanel.add(new JLabel("De-obfuscated Classes"), BorderLayout.NORTH); + deobfPanel.add(deobfScroller, BorderLayout.CENTER); // set up classes panel (don't add the splitter yet) - m_splitClasses = new JSplitPane( JSplitPane.VERTICAL_SPLIT, true, obfPanel, deobfPanel ); - m_splitClasses.setResizeWeight( 0.3 ); + m_splitClasses = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, obfPanel, deobfPanel); + m_splitClasses.setResizeWeight(0.3); m_classesPanel = new JPanel(); - m_classesPanel.setLayout( new BorderLayout() ); - m_classesPanel.setPreferredSize( new Dimension( 250, 0 ) ); + m_classesPanel.setLayout(new BorderLayout()); + m_classesPanel.setPreferredSize(new Dimension(250, 0)); // init info panel m_infoPanel = new JPanel(); - m_infoPanel.setLayout( new GridLayout( 4, 1, 0, 0 ) ); - m_infoPanel.setPreferredSize( new Dimension( 0, 100 ) ); - m_infoPanel.setBorder( BorderFactory.createTitledBorder( "Identifier Info" ) ); + m_infoPanel.setLayout(new GridLayout(4, 1, 0, 0)); + m_infoPanel.setPreferredSize(new Dimension(0, 100)); + m_infoPanel.setBorder(BorderFactory.createTitledBorder("Identifier Info")); clearReference(); // init editor @@ -217,25 +210,20 @@ public class Gui m_otherHighlightPainter = new OtherHighlightPainter(); m_selectionHighlightPainter = new SelectionHighlightPainter(); m_editor = new JEditorPane(); - m_editor.setEditable( false ); - m_editor.setCaret( new BrowserCaret() ); - JScrollPane sourceScroller = new JScrollPane( m_editor ); - m_editor.setContentType( "text/java" ); - m_editor.addCaretListener( new CaretListener( ) - { + m_editor.setEditable(false); + m_editor.setCaret(new BrowserCaret()); + JScrollPane sourceScroller = new JScrollPane(m_editor); + m_editor.setContentType("text/java"); + m_editor.addCaretListener(new CaretListener() { @Override - public void caretUpdate( CaretEvent event ) - { - onCaretMove( event.getDot() ); + public void caretUpdate(CaretEvent event) { + onCaretMove(event.getDot()); } - } ); - m_editor.addKeyListener( new KeyAdapter( ) - { + }); + m_editor.addKeyListener(new KeyAdapter() { @Override - public void keyPressed( KeyEvent event ) - { - switch( event.getKeyCode() ) - { + public void keyPressed(KeyEvent event) { + switch (event.getKeyCode()) { case KeyEvent.VK_R: m_renameMenu.doClick(); break; @@ -265,713 +253,594 @@ public class Gui break; } } - } ); + }); // turn off token highlighting (it's wrong most of the time anyway...) DefaultSyntaxKit kit = (DefaultSyntaxKit)m_editor.getEditorKit(); - kit.toggleComponent( m_editor, "jsyntaxpane.components.TokenMarker" ); + kit.toggleComponent(m_editor, "jsyntaxpane.components.TokenMarker"); // init editor popup menu JPopupMenu popupMenu = new JPopupMenu(); - m_editor.setComponentPopupMenu( popupMenu ); + m_editor.setComponentPopupMenu(popupMenu); { - JMenuItem menu = new JMenuItem( "Rename" ); - menu.addActionListener( new ActionListener( ) - { + JMenuItem menu = new JMenuItem("Rename"); + menu.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { startRename(); } - } ); - menu.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_R, 0 ) ); - menu.setEnabled( false ); - popupMenu.add( menu ); + }); + menu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0)); + menu.setEnabled(false); + popupMenu.add(menu); m_renameMenu = menu; } { - JMenuItem menu = new JMenuItem( "Show Inheritance" ); - menu.addActionListener( new ActionListener( ) - { + JMenuItem menu = new JMenuItem("Show Inheritance"); + menu.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { showInheritance(); } - } ); - menu.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_I, 0 ) ); - menu.setEnabled( false ); - popupMenu.add( menu ); + }); + menu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, 0)); + menu.setEnabled(false); + popupMenu.add(menu); m_showInheritanceMenu = menu; } { - JMenuItem menu = new JMenuItem( "Show Implementations" ); - menu.addActionListener( new ActionListener( ) - { + JMenuItem menu = new JMenuItem("Show Implementations"); + menu.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { showImplementations(); } - } ); - menu.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_M, 0 ) ); - menu.setEnabled( false ); - popupMenu.add( menu ); + }); + menu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, 0)); + menu.setEnabled(false); + popupMenu.add(menu); m_showImplementationsMenu = menu; } { - JMenuItem menu = new JMenuItem( "Show Calls" ); - menu.addActionListener( new ActionListener( ) - { + JMenuItem menu = new JMenuItem("Show Calls"); + menu.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { showCalls(); } - } ); - menu.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_C, 0 ) ); - menu.setEnabled( false ); - popupMenu.add( menu ); + }); + menu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, 0)); + menu.setEnabled(false); + popupMenu.add(menu); m_showCallsMenu = menu; } { - JMenuItem menu = new JMenuItem( "Go to Declaration" ); - menu.addActionListener( new ActionListener( ) - { + JMenuItem menu = new JMenuItem("Go to Declaration"); + menu.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - navigateTo( m_reference.entry ); + public void actionPerformed(ActionEvent event) { + navigateTo(m_reference.entry); } - } ); - menu.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_N, 0 ) ); - menu.setEnabled( false ); - popupMenu.add( menu ); + }); + menu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, 0)); + menu.setEnabled(false); + popupMenu.add(menu); m_openEntryMenu = menu; } { - JMenuItem menu = new JMenuItem( "Go to previous" ); - menu.addActionListener( new ActionListener( ) - { + JMenuItem menu = new JMenuItem("Go to previous"); + menu.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { m_controller.openPreviousReference(); } - } ); - menu.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_P, 0 ) ); - menu.setEnabled( false ); - popupMenu.add( menu ); + }); + menu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0)); + menu.setEnabled(false); + popupMenu.add(menu); m_openPreviousMenu = menu; } { - JMenuItem menu = new JMenuItem( "Mark as deobfuscated" ); - menu.addActionListener( new ActionListener( ) - { + JMenuItem menu = new JMenuItem("Mark as deobfuscated"); + menu.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { toggleMapping(); } - } ); - menu.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_T, 0 ) ); - menu.setEnabled( false ); - popupMenu.add( menu ); + }); + menu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, 0)); + menu.setEnabled(false); + popupMenu.add(menu); m_toggleMappingMenu = menu; } // init inheritance panel m_inheritanceTree = new JTree(); - m_inheritanceTree.setModel( null ); - m_inheritanceTree.addMouseListener( new MouseAdapter( ) - { + m_inheritanceTree.setModel(null); + m_inheritanceTree.addMouseListener(new MouseAdapter() { @Override - public void mouseClicked( MouseEvent event ) - { - if( event.getClickCount() == 2 ) - { + public void mouseClicked(MouseEvent event) { + if (event.getClickCount() == 2) { // get the selected node TreePath path = m_inheritanceTree.getSelectionPath(); - if( path == null ) - { + if (path == null) { return; } Object node = path.getLastPathComponent(); - if( node instanceof ClassInheritanceTreeNode ) - { + if (node instanceof ClassInheritanceTreeNode) { ClassInheritanceTreeNode classNode = (ClassInheritanceTreeNode)node; - navigateTo( new ClassEntry( classNode.getObfClassName() ) ); - } - else if( node instanceof MethodInheritanceTreeNode ) - { + navigateTo(new ClassEntry(classNode.getObfClassName())); + } else if (node instanceof MethodInheritanceTreeNode) { MethodInheritanceTreeNode methodNode = (MethodInheritanceTreeNode)node; - if( methodNode.isImplemented() ) - { - navigateTo( methodNode.getMethodEntry() ); + if (methodNode.isImplemented()) { + navigateTo(methodNode.getMethodEntry()); } } } } - } ); + }); JPanel inheritancePanel = new JPanel(); - inheritancePanel.setLayout( new BorderLayout() ); - inheritancePanel.add( new JScrollPane( m_inheritanceTree ) ); + inheritancePanel.setLayout(new BorderLayout()); + inheritancePanel.add(new JScrollPane(m_inheritanceTree)); // init implementations panel m_implementationsTree = new JTree(); - m_implementationsTree.setModel( null ); - m_implementationsTree.addMouseListener( new MouseAdapter( ) - { + m_implementationsTree.setModel(null); + m_implementationsTree.addMouseListener(new MouseAdapter() { @Override - public void mouseClicked( MouseEvent event ) - { - if( event.getClickCount() == 2 ) - { + public void mouseClicked(MouseEvent event) { + if (event.getClickCount() == 2) { // get the selected node TreePath path = m_implementationsTree.getSelectionPath(); - if( path == null ) - { + if (path == null) { return; } Object node = path.getLastPathComponent(); - if( node instanceof ClassImplementationsTreeNode ) - { + if (node instanceof ClassImplementationsTreeNode) { ClassImplementationsTreeNode classNode = (ClassImplementationsTreeNode)node; - navigateTo( classNode.getClassEntry() ); - } - else if( node instanceof MethodImplementationsTreeNode ) - { + navigateTo(classNode.getClassEntry()); + } else if (node instanceof MethodImplementationsTreeNode) { MethodImplementationsTreeNode methodNode = (MethodImplementationsTreeNode)node; - navigateTo( methodNode.getMethodEntry() ); + navigateTo(methodNode.getMethodEntry()); } } } - } ); + }); JPanel implementationsPanel = new JPanel(); - implementationsPanel.setLayout( new BorderLayout() ); - implementationsPanel.add( new JScrollPane( m_implementationsTree ) ); + implementationsPanel.setLayout(new BorderLayout()); + implementationsPanel.add(new JScrollPane(m_implementationsTree)); // init call panel m_callsTree = new JTree(); - m_callsTree.setModel( null ); - m_callsTree.addMouseListener( new MouseAdapter( ) - { - @SuppressWarnings( "unchecked" ) + m_callsTree.setModel(null); + m_callsTree.addMouseListener(new MouseAdapter() { + @SuppressWarnings("unchecked") @Override - public void mouseClicked( MouseEvent event ) - { - if( event.getClickCount() == 2 ) - { + public void mouseClicked(MouseEvent event) { + if (event.getClickCount() == 2) { // get the selected node TreePath path = m_callsTree.getSelectionPath(); - if( path == null ) - { + if (path == null) { return; } Object node = path.getLastPathComponent(); - if( node instanceof ReferenceTreeNode ) - { + if (node instanceof ReferenceTreeNode) { ReferenceTreeNode referenceNode = ((ReferenceTreeNode)node); - if( referenceNode.getReference() != null ) - { - navigateTo( referenceNode.getReference() ); - } - else - { - navigateTo( referenceNode.getEntry() ); + if (referenceNode.getReference() != null) { + navigateTo(referenceNode.getReference()); + } else { + navigateTo(referenceNode.getEntry()); } } } } - } ); + }); m_tokens = new JList(); - m_tokens.setCellRenderer( new TokenListCellRenderer( m_controller ) ); - m_tokens.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - m_tokens.setLayoutOrientation( JList.VERTICAL ); - m_tokens.addMouseListener( new MouseAdapter() - { + m_tokens.setCellRenderer(new TokenListCellRenderer(m_controller)); + m_tokens.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + m_tokens.setLayoutOrientation(JList.VERTICAL); + m_tokens.addMouseListener(new MouseAdapter() { @Override - public void mouseClicked( MouseEvent event ) - { - if( event.getClickCount() == 2 ) - { + public void mouseClicked(MouseEvent event) { + if (event.getClickCount() == 2) { Token selected = m_tokens.getSelectedValue(); - if( selected != null ) - { - showToken( selected ); + if (selected != null) { + showToken(selected); } } } - } ); - m_tokens.setPreferredSize( new Dimension( 0, 200 ) ); - m_tokens.setMinimumSize( new Dimension( 0, 200 ) ); - JSplitPane callPanel = new JSplitPane( JSplitPane.VERTICAL_SPLIT, true, new JScrollPane( m_callsTree ), new JScrollPane( m_tokens ) ); - callPanel.setResizeWeight( 1 ); // let the top side take all the slack + }); + m_tokens.setPreferredSize(new Dimension(0, 200)); + m_tokens.setMinimumSize(new Dimension(0, 200)); + JSplitPane callPanel = new JSplitPane( + JSplitPane.VERTICAL_SPLIT, + true, + new JScrollPane(m_callsTree), + new JScrollPane(m_tokens) + ); + callPanel.setResizeWeight(1); // let the top side take all the slack callPanel.resetToPreferredSizes(); // layout controls JPanel centerPanel = new JPanel(); - centerPanel.setLayout( new BorderLayout() ); - centerPanel.add( m_infoPanel, BorderLayout.NORTH ); - centerPanel.add( sourceScroller, BorderLayout.CENTER ); + centerPanel.setLayout(new BorderLayout()); + centerPanel.add(m_infoPanel, BorderLayout.NORTH); + centerPanel.add(sourceScroller, BorderLayout.CENTER); m_tabs = new JTabbedPane(); - m_tabs.setPreferredSize( new Dimension( 250, 0 ) ); - m_tabs.addTab( "Inheritance", inheritancePanel ); - m_tabs.addTab( "Implementations", implementationsPanel ); - m_tabs.addTab( "Call Graph", callPanel ); - JSplitPane splitRight = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, true, centerPanel, m_tabs ); - splitRight.setResizeWeight( 1 ); // let the left side take all the slack + m_tabs.setPreferredSize(new Dimension(250, 0)); + m_tabs.addTab("Inheritance", inheritancePanel); + m_tabs.addTab("Implementations", implementationsPanel); + m_tabs.addTab("Call Graph", callPanel); + JSplitPane splitRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, centerPanel, m_tabs); + splitRight.setResizeWeight(1); // let the left side take all the slack splitRight.resetToPreferredSizes(); - JSplitPane splitCenter = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, true, m_classesPanel, splitRight ); - splitCenter.setResizeWeight( 0 ); // let the right side take all the slack - pane.add( splitCenter, BorderLayout.CENTER ); + JSplitPane splitCenter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, m_classesPanel, splitRight); + splitCenter.setResizeWeight(0); // let the right side take all the slack + pane.add(splitCenter, BorderLayout.CENTER); // init menus JMenuBar menuBar = new JMenuBar(); - m_frame.setJMenuBar( menuBar ); + m_frame.setJMenuBar(menuBar); { - JMenu menu = new JMenu( "File" ); - menuBar.add( menu ); + JMenu menu = new JMenu("File"); + menuBar.add(menu); { - JMenuItem item = new JMenuItem( "Open Jar..." ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Open Jar..."); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - if( m_jarFileChooser.showOpenDialog( m_frame ) == JFileChooser.APPROVE_OPTION ) - { + public void actionPerformed(ActionEvent event) { + if (m_jarFileChooser.showOpenDialog(m_frame) == JFileChooser.APPROVE_OPTION) { // load the jar in a separate thread - new Thread( ) - { + new Thread() { @Override - public void run( ) - { - try - { - m_controller.openJar( m_jarFileChooser.getSelectedFile() ); - } - catch( IOException ex ) - { - throw new Error( ex ); + public void run() { + try { + m_controller.openJar(m_jarFileChooser.getSelectedFile()); + } catch (IOException ex) { + throw new Error(ex); } } }.start(); } } - } ); + }); } { - JMenuItem item = new JMenuItem( "Close Jar" ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Close Jar"); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { m_controller.closeJar(); } - } ); + }); m_closeJarMenu = item; } menu.addSeparator(); { - JMenuItem item = new JMenuItem( "Open Mappings..." ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Open Mappings..."); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - if( m_mappingsFileChooser.showOpenDialog( m_frame ) == JFileChooser.APPROVE_OPTION ) - { - try - { - m_controller.openMappings( m_mappingsFileChooser.getSelectedFile() ); - } - catch( IOException ex ) - { - throw new Error( ex ); - } - catch( MappingParseException ex ) - { - JOptionPane.showMessageDialog( m_frame, ex.getMessage() ); + public void actionPerformed(ActionEvent event) { + if (m_mappingsFileChooser.showOpenDialog(m_frame) == JFileChooser.APPROVE_OPTION) { + try { + m_controller.openMappings(m_mappingsFileChooser.getSelectedFile()); + } catch (IOException ex) { + throw new Error(ex); + } catch (MappingParseException ex) { + JOptionPane.showMessageDialog(m_frame, ex.getMessage()); } } } - } ); + }); m_openMappingsMenu = item; } { - JMenuItem item = new JMenuItem( "Save Mappings" ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Save Mappings"); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - try - { - m_controller.saveMappings( m_mappingsFileChooser.getSelectedFile() ); - } - catch( IOException ex ) - { - throw new Error( ex ); + public void actionPerformed(ActionEvent event) { + try { + m_controller.saveMappings(m_mappingsFileChooser.getSelectedFile()); + } catch (IOException ex) { + throw new Error(ex); } } - } ); - item.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK ) ); + }); + item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); m_saveMappingsMenu = item; } { - JMenuItem item = new JMenuItem( "Save Mappings As..." ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Save Mappings As..."); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - if( m_mappingsFileChooser.showSaveDialog( m_frame ) == JFileChooser.APPROVE_OPTION ) - { - try - { - m_controller.saveMappings( m_mappingsFileChooser.getSelectedFile() ); - m_saveMappingsMenu.setEnabled( true ); - } - catch( IOException ex ) - { - throw new Error( ex ); + public void actionPerformed(ActionEvent event) { + if (m_mappingsFileChooser.showSaveDialog(m_frame) == JFileChooser.APPROVE_OPTION) { + try { + m_controller.saveMappings(m_mappingsFileChooser.getSelectedFile()); + m_saveMappingsMenu.setEnabled(true); + } catch (IOException ex) { + throw new Error(ex); } } } - } ); - item.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK ) ); + }); + item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); m_saveMappingsAsMenu = item; } { - JMenuItem item = new JMenuItem( "Close Mappings" ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Close Mappings"); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { m_controller.closeMappings(); } - } ); + }); m_closeMappingsMenu = item; } menu.addSeparator(); { - JMenuItem item = new JMenuItem( "Export Source..." ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Export Source..."); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - if( m_exportSourceFileChooser.showSaveDialog( m_frame ) == JFileChooser.APPROVE_OPTION ) - { - m_controller.exportSource( m_exportSourceFileChooser.getSelectedFile() ); + public void actionPerformed(ActionEvent event) { + if (m_exportSourceFileChooser.showSaveDialog(m_frame) == JFileChooser.APPROVE_OPTION) { + m_controller.exportSource(m_exportSourceFileChooser.getSelectedFile()); } } - } ); + }); m_exportSourceMenu = item; } { - JMenuItem item = new JMenuItem( "Export Jar..." ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Export Jar..."); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - if( m_exportJarFileChooser.showSaveDialog( m_frame ) == JFileChooser.APPROVE_OPTION ) - { - m_controller.exportJar( m_exportJarFileChooser.getSelectedFile() ); + public void actionPerformed(ActionEvent event) { + if (m_exportJarFileChooser.showSaveDialog(m_frame) == JFileChooser.APPROVE_OPTION) { + m_controller.exportJar(m_exportJarFileChooser.getSelectedFile()); } } - } ); + }); m_exportJarMenu = item; } menu.addSeparator(); { - JMenuItem item = new JMenuItem( "Exit" ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("Exit"); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { + public void actionPerformed(ActionEvent event) { close(); } - } ); + }); } } { - JMenu menu = new JMenu( "Help" ); - menuBar.add( menu ); + JMenu menu = new JMenu("Help"); + menuBar.add(menu); { - JMenuItem item = new JMenuItem( "About" ); - menu.add( item ); - item.addActionListener( new ActionListener( ) - { + JMenuItem item = new JMenuItem("About"); + menu.add(item); + item.addActionListener(new ActionListener() { @Override - public void actionPerformed( ActionEvent event ) - { - AboutDialog.show( m_frame ); + public void actionPerformed(ActionEvent event) { + AboutDialog.show(m_frame); } - } ); + }); } } // init state onCloseJar(); - m_frame.addWindowListener( new WindowAdapter( ) - { + m_frame.addWindowListener(new WindowAdapter() { @Override - public void windowClosing( WindowEvent event ) - { + public void windowClosing(WindowEvent event) { close(); } - } ); + }); // show the frame pane.doLayout(); - m_frame.setSize( 1024, 576 ); - m_frame.setMinimumSize( new Dimension( 640, 480 ) ); - m_frame.setVisible( true ); - m_frame.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); + m_frame.setSize(1024, 576); + m_frame.setMinimumSize(new Dimension(640, 480)); + m_frame.setVisible(true); + m_frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); } - public JFrame getFrame( ) - { + public JFrame getFrame() { return m_frame; } - public GuiController getController( ) - { + public GuiController getController() { return m_controller; } - public void onStartOpenJar( ) - { + public void onStartOpenJar() { m_classesPanel.removeAll(); JPanel panel = new JPanel(); - panel.setLayout( new FlowLayout() ); - panel.add( new JLabel( "Loading..." ) ); - m_classesPanel.add( panel ); + panel.setLayout(new FlowLayout()); + panel.add(new JLabel("Loading...")); + m_classesPanel.add(panel); redraw(); } - public void onFinishOpenJar( String jarName ) - { + public void onFinishOpenJar(String jarName) { // update gui - m_frame.setTitle( Constants.Name + " - " + jarName ); + m_frame.setTitle(Constants.Name + " - " + jarName); m_classesPanel.removeAll(); - m_classesPanel.add( m_splitClasses ); - setSource( null ); + m_classesPanel.add(m_splitClasses); + setSource(null); // update menu - m_closeJarMenu.setEnabled( true ); - m_openMappingsMenu.setEnabled( true ); - m_saveMappingsMenu.setEnabled( false ); - m_saveMappingsAsMenu.setEnabled( true ); - m_closeMappingsMenu.setEnabled( true ); - m_exportSourceMenu.setEnabled( true ); - m_exportJarMenu.setEnabled( true ); + m_closeJarMenu.setEnabled(true); + m_openMappingsMenu.setEnabled(true); + m_saveMappingsMenu.setEnabled(false); + m_saveMappingsAsMenu.setEnabled(true); + m_closeMappingsMenu.setEnabled(true); + m_exportSourceMenu.setEnabled(true); + m_exportJarMenu.setEnabled(true); redraw(); } - public void onCloseJar( ) - { + public void onCloseJar() { // update gui - m_frame.setTitle( Constants.Name ); - setObfClasses( null ); - setDeobfClasses( null ); - setSource( null ); + m_frame.setTitle(Constants.Name); + setObfClasses(null); + setDeobfClasses(null); + setSource(null); m_classesPanel.removeAll(); // update menu - m_closeJarMenu.setEnabled( false ); - m_openMappingsMenu.setEnabled( false ); - m_saveMappingsMenu.setEnabled( false ); - m_saveMappingsAsMenu.setEnabled( false ); - m_closeMappingsMenu.setEnabled( false ); - m_exportSourceMenu.setEnabled( false ); - m_exportJarMenu.setEnabled( false ); + m_closeJarMenu.setEnabled(false); + m_openMappingsMenu.setEnabled(false); + m_saveMappingsMenu.setEnabled(false); + m_saveMappingsAsMenu.setEnabled(false); + m_closeMappingsMenu.setEnabled(false); + m_exportSourceMenu.setEnabled(false); + m_exportJarMenu.setEnabled(false); redraw(); } - public void setObfClasses( Collection obfClasses ) - { - m_obfClasses.setClasses( obfClasses ); + public void setObfClasses(Collection obfClasses) { + m_obfClasses.setClasses(obfClasses); } - public void setDeobfClasses( Collection deobfClasses ) - { - m_deobfClasses.setClasses( deobfClasses ); + public void setDeobfClasses(Collection deobfClasses) { + m_deobfClasses.setClasses(deobfClasses); } - public void setMappingsFile( File file ) - { - m_mappingsFileChooser.setSelectedFile( file ); - m_saveMappingsMenu.setEnabled( file != null ); + public void setMappingsFile(File file) { + m_mappingsFileChooser.setSelectedFile(file); + m_saveMappingsMenu.setEnabled(file != null); } - public void setSource( String source ) - { + public void setSource(String source) { m_editor.getHighlighter().removeAllHighlights(); - m_editor.setText( source ); + m_editor.setText(source); } - public void showToken( final Token token ) - { - if( token == null ) - { - throw new IllegalArgumentException( "Token cannot be null!" ); + public void showToken(final Token token) { + if (token == null) { + throw new IllegalArgumentException("Token cannot be null!"); } // set the caret position to the token - m_editor.setCaretPosition( token.start ); + m_editor.setCaretPosition(token.start); m_editor.grabFocus(); - try - { + try { // make sure the token is visible in the scroll window - Rectangle start = m_editor.modelToView( token.start ); - Rectangle end = m_editor.modelToView( token.end ); - final Rectangle show = start.union( end ); - show.grow( start.width*10, start.height*6 ); - SwingUtilities.invokeLater( new Runnable( ) - { + Rectangle start = m_editor.modelToView(token.start); + Rectangle end = m_editor.modelToView(token.end); + final Rectangle show = start.union(end); + show.grow(start.width * 10, start.height * 6); + SwingUtilities.invokeLater(new Runnable() { @Override - public void run( ) - { - m_editor.scrollRectToVisible( show ); + public void run() { + m_editor.scrollRectToVisible(show); } - } ); - } - catch( BadLocationException ex ) - { - throw new Error( ex ); + }); + } catch (BadLocationException ex) { + throw new Error(ex); } // highlight the token momentarily - final Timer timer = new Timer( 200, new ActionListener( ) - { + final Timer timer = new Timer(200, new ActionListener() { private int m_counter = 0; private Object m_highlight = null; @Override - public void actionPerformed( ActionEvent event ) - { - if( m_counter % 2 == 0 ) - { - try - { - m_highlight = m_editor.getHighlighter().addHighlight( token.start, token.end, m_selectionHighlightPainter ); - } - catch( BadLocationException ex ) - { + public void actionPerformed(ActionEvent event) { + if (m_counter % 2 == 0) { + try { + m_highlight = m_editor.getHighlighter().addHighlight(token.start, token.end, m_selectionHighlightPainter); + } catch (BadLocationException ex) { // don't care } - } - else if( m_highlight != null ) - { - m_editor.getHighlighter().removeHighlight( m_highlight ); + } else if (m_highlight != null) { + m_editor.getHighlighter().removeHighlight(m_highlight); } - if( m_counter++ > 6 ) - { + if (m_counter++ > 6) { Timer timer = (Timer)event.getSource(); timer.stop(); } } - } ); + }); timer.start(); redraw(); } - public void showTokens( Collection tokens ) - { - Vector sortedTokens = new Vector( tokens ); - Collections.sort( sortedTokens ); - if( sortedTokens.size() > 1 ) - { + public void showTokens(Collection tokens) { + Vector sortedTokens = new Vector(tokens); + Collections.sort(sortedTokens); + if (sortedTokens.size() > 1) { // sort the tokens and update the tokens panel - m_tokens.setListData( sortedTokens ); - m_tokens.setSelectedIndex( 0 ); - } - else - { - m_tokens.setListData( new Vector() ); + m_tokens.setListData(sortedTokens); + m_tokens.setSelectedIndex(0); + } else { + m_tokens.setListData(new Vector()); } // show the first token - showToken( sortedTokens.get( 0 ) ); + showToken(sortedTokens.get(0)); } - public void setHighlightedTokens( Iterable obfuscatedTokens, Iterable deobfuscatedTokens, Iterable otherTokens ) - { + public void setHighlightedTokens(Iterable obfuscatedTokens, Iterable deobfuscatedTokens, Iterable otherTokens) { + // remove any old highlighters m_editor.getHighlighter().removeAllHighlights(); // color things based on the index - if( obfuscatedTokens != null ) - { - setHighlightedTokens( obfuscatedTokens, m_obfuscatedHighlightPainter ); + if (obfuscatedTokens != null) { + setHighlightedTokens(obfuscatedTokens, m_obfuscatedHighlightPainter); } - if( deobfuscatedTokens != null ) - { - setHighlightedTokens( deobfuscatedTokens, m_deobfuscatedHighlightPainter ); + if (deobfuscatedTokens != null) { + setHighlightedTokens(deobfuscatedTokens, m_deobfuscatedHighlightPainter); } - if( otherTokens != null ) - { - setHighlightedTokens( otherTokens, m_otherHighlightPainter ); + if (otherTokens != null) { + setHighlightedTokens(otherTokens, m_otherHighlightPainter); } redraw(); } - private void setHighlightedTokens( Iterable tokens, Highlighter.HighlightPainter painter ) - { - for( Token token : tokens ) - { - try - { - m_editor.getHighlighter().addHighlight( token.start, token.end, painter ); - } - catch( BadLocationException ex ) - { - throw new IllegalArgumentException( ex ); + private void setHighlightedTokens(Iterable tokens, Highlighter.HighlightPainter painter) { + for (Token token : tokens) { + try { + m_editor.getHighlighter().addHighlight(token.start, token.end, painter); + } catch (BadLocationException ex) { + throw new IllegalArgumentException(ex); } } } - private void clearReference( ) - { + private void clearReference() { m_infoPanel.removeAll(); - JLabel label = new JLabel( "No identifier selected" ); - GuiTricks.unboldLabel( label ); - label.setHorizontalAlignment( JLabel.CENTER ); - m_infoPanel.add( label ); + JLabel label = new JLabel("No identifier selected"); + GuiTricks.unboldLabel(label); + label.setHorizontalAlignment(JLabel.CENTER); + m_infoPanel.add(label); redraw(); } - private void showReference( EntryReference reference ) - { - if( reference == null ) - { + private void showReference(EntryReference reference) { + if (reference == null) { clearReference(); return; } @@ -979,383 +848,300 @@ public class Gui m_reference = reference; m_infoPanel.removeAll(); - if( reference.entry instanceof ClassEntry ) - { - showClassEntry( (ClassEntry)m_reference.entry ); - } - else if( m_reference.entry instanceof FieldEntry ) - { - showFieldEntry( (FieldEntry)m_reference.entry ); - } - else if( m_reference.entry instanceof MethodEntry ) - { - showMethodEntry( (MethodEntry)m_reference.entry ); - } - else if( m_reference.entry instanceof ConstructorEntry ) - { - showConstructorEntry( (ConstructorEntry)m_reference.entry ); - } - else if( m_reference.entry instanceof ArgumentEntry ) - { - showArgumentEntry( (ArgumentEntry)m_reference.entry ); - } - else - { - throw new Error( "Unknown entry type: " + m_reference.entry.getClass().getName() ); + if (reference.entry instanceof ClassEntry) { + showClassEntry((ClassEntry)m_reference.entry); + } else if (m_reference.entry instanceof FieldEntry) { + showFieldEntry((FieldEntry)m_reference.entry); + } else if (m_reference.entry instanceof MethodEntry) { + showMethodEntry((MethodEntry)m_reference.entry); + } else if (m_reference.entry instanceof ConstructorEntry) { + showConstructorEntry((ConstructorEntry)m_reference.entry); + } else if (m_reference.entry instanceof ArgumentEntry) { + showArgumentEntry((ArgumentEntry)m_reference.entry); + } else { + throw new Error("Unknown entry type: " + m_reference.entry.getClass().getName()); } redraw(); } - private void showClassEntry( ClassEntry entry ) - { - addNameValue( m_infoPanel, "Class", entry.getName() ); + private void showClassEntry(ClassEntry entry) { + addNameValue(m_infoPanel, "Class", entry.getName()); } - private void showFieldEntry( FieldEntry entry ) - { - addNameValue( m_infoPanel, "Field", entry.getName() ); - addNameValue( m_infoPanel, "Class", entry.getClassEntry().getName() ); + private void showFieldEntry(FieldEntry entry) { + addNameValue(m_infoPanel, "Field", entry.getName()); + addNameValue(m_infoPanel, "Class", entry.getClassEntry().getName()); } - private void showMethodEntry( MethodEntry entry ) - { - addNameValue( m_infoPanel, "Method", entry.getName() ); - addNameValue( m_infoPanel, "Class", entry.getClassEntry().getName() ); - addNameValue( m_infoPanel, "Signature", entry.getSignature() ); + private void showMethodEntry(MethodEntry entry) { + addNameValue(m_infoPanel, "Method", entry.getName()); + addNameValue(m_infoPanel, "Class", entry.getClassEntry().getName()); + addNameValue(m_infoPanel, "Signature", entry.getSignature()); } - private void showConstructorEntry( ConstructorEntry entry ) - { - addNameValue( m_infoPanel, "Constructor", entry.getClassEntry().getName() ); - addNameValue( m_infoPanel, "Signature", entry.getSignature() ); + private void showConstructorEntry(ConstructorEntry entry) { + addNameValue(m_infoPanel, "Constructor", entry.getClassEntry().getName()); + addNameValue(m_infoPanel, "Signature", entry.getSignature()); } - private void showArgumentEntry( ArgumentEntry entry ) - { - addNameValue( m_infoPanel, "Argument", entry.getName() ); - addNameValue( m_infoPanel, "Class", entry.getClassEntry().getName() ); - addNameValue( m_infoPanel, "Method", entry.getBehaviorEntry().getName() ); - addNameValue( m_infoPanel, "Index", Integer.toString( entry.getIndex() ) ); + private void showArgumentEntry(ArgumentEntry entry) { + addNameValue(m_infoPanel, "Argument", entry.getName()); + addNameValue(m_infoPanel, "Class", entry.getClassEntry().getName()); + addNameValue(m_infoPanel, "Method", entry.getBehaviorEntry().getName()); + addNameValue(m_infoPanel, "Index", Integer.toString(entry.getIndex())); } - private void addNameValue( JPanel container, String name, String value ) - { + private void addNameValue(JPanel container, String name, String value) { JPanel panel = new JPanel(); - panel.setLayout( new FlowLayout( FlowLayout.LEFT, 6, 0 ) ); - container.add( panel ); + panel.setLayout(new FlowLayout(FlowLayout.LEFT, 6, 0)); + container.add(panel); - JLabel label = new JLabel( name + ":", JLabel.RIGHT ); - label.setPreferredSize( new Dimension( 100, label.getPreferredSize().height ) ); - panel.add( label ); + JLabel label = new JLabel(name + ":", JLabel.RIGHT); + label.setPreferredSize(new Dimension(100, label.getPreferredSize().height)); + panel.add(label); - panel.add( GuiTricks.unboldLabel( new JLabel( value, JLabel.LEFT ) ) ); + panel.add(GuiTricks.unboldLabel(new JLabel(value, JLabel.LEFT))); } - private void onCaretMove( int pos ) - { - Token token = m_controller.getToken( pos ); + private void onCaretMove(int pos) { + + Token token = m_controller.getToken(pos); boolean isToken = token != null; - m_reference = m_controller.getDeobfReference( token ); + m_reference = m_controller.getDeobfReference(token); boolean isClassEntry = isToken && m_reference.entry instanceof ClassEntry; boolean isFieldEntry = isToken && m_reference.entry instanceof FieldEntry; boolean isMethodEntry = isToken && m_reference.entry instanceof MethodEntry; boolean isConstructorEntry = isToken && m_reference.entry instanceof ConstructorEntry; - boolean isInJar = isToken && m_controller.entryIsInJar( m_reference.entry ); - boolean isRenameable = isToken && m_controller.referenceIsRenameable( m_reference ); + boolean isInJar = isToken && m_controller.entryIsInJar(m_reference.entry); + boolean isRenameable = isToken && m_controller.referenceIsRenameable(m_reference); - if( isToken ) - { - showReference( m_reference ); - } - else - { + if (isToken) { + showReference(m_reference); + } else { clearReference(); } - m_renameMenu.setEnabled( isRenameable && isToken ); - m_showInheritanceMenu.setEnabled( isClassEntry || isMethodEntry || isConstructorEntry ); - m_showImplementationsMenu.setEnabled( isClassEntry || isMethodEntry ); - m_showCallsMenu.setEnabled( isClassEntry || isFieldEntry || isMethodEntry || isConstructorEntry ); - m_openEntryMenu.setEnabled( isInJar && ( isClassEntry || isFieldEntry || isMethodEntry || isConstructorEntry ) ); - m_openPreviousMenu.setEnabled( m_controller.hasPreviousLocation() ); - m_toggleMappingMenu.setEnabled( isRenameable && isToken ); + m_renameMenu.setEnabled(isRenameable && isToken); + m_showInheritanceMenu.setEnabled(isClassEntry || isMethodEntry || isConstructorEntry); + m_showImplementationsMenu.setEnabled(isClassEntry || isMethodEntry); + m_showCallsMenu.setEnabled(isClassEntry || isFieldEntry || isMethodEntry || isConstructorEntry); + m_openEntryMenu.setEnabled(isInJar && (isClassEntry || isFieldEntry || isMethodEntry || isConstructorEntry)); + m_openPreviousMenu.setEnabled(m_controller.hasPreviousLocation()); + m_toggleMappingMenu.setEnabled(isRenameable && isToken); - if( isToken && m_controller.entryHasDeobfuscatedName( m_reference.entry ) ) - { - m_toggleMappingMenu.setText( "Reset to obfuscated" ); - } - else - { - m_toggleMappingMenu.setText( "Mark as deobfuscated" ); + if (isToken && m_controller.entryHasDeobfuscatedName(m_reference.entry)) { + m_toggleMappingMenu.setText("Reset to obfuscated"); + } else { + m_toggleMappingMenu.setText("Mark as deobfuscated"); } } - private void navigateTo( Entry entry ) - { - if( !m_controller.entryIsInJar( entry ) ) - { + private void navigateTo(Entry entry) { + if (!m_controller.entryIsInJar(entry)) { // entry is not in the jar. Ignore it return; } - if( m_reference != null ) - { - m_controller.savePreviousReference( m_reference ); + if (m_reference != null) { + m_controller.savePreviousReference(m_reference); } - m_controller.openDeclaration( entry ); + m_controller.openDeclaration(entry); } - private void navigateTo( EntryReference reference ) - { - if( !m_controller.entryIsInJar( reference.getLocationClassEntry() ) ) - { + private void navigateTo(EntryReference reference) { + if (!m_controller.entryIsInJar(reference.getLocationClassEntry())) { // reference is not in the jar. Ignore it return; } - if( m_reference != null ) - { - m_controller.savePreviousReference( m_reference ); + if (m_reference != null) { + m_controller.savePreviousReference(m_reference); } - m_controller.openReference( reference ); + m_controller.openReference(reference); } - private void startRename( ) - { + private void startRename() { + // init the text box final JTextField text = new JTextField(); - text.setText( m_reference.getNamableName() ); - text.setPreferredSize( new Dimension( 360, text.getPreferredSize().height ) ); - text.addKeyListener( new KeyAdapter( ) - { + text.setText(m_reference.getNamableName()); + text.setPreferredSize(new Dimension(360, text.getPreferredSize().height)); + text.addKeyListener(new KeyAdapter() { @Override - public void keyPressed( KeyEvent event ) - { - switch( event.getKeyCode() ) - { + public void keyPressed(KeyEvent event) { + switch (event.getKeyCode()) { case KeyEvent.VK_ENTER: - finishRename( text, true ); + finishRename(text, true); break; case KeyEvent.VK_ESCAPE: - finishRename( text, false ); + finishRename(text, false); break; } } - } ); + }); // find the label with the name and replace it with the text box - JPanel panel = (JPanel)m_infoPanel.getComponent( 0 ); - panel.remove( panel.getComponentCount() - 1 ); - panel.add( text ); + JPanel panel = (JPanel)m_infoPanel.getComponent(0); + panel.remove(panel.getComponentCount() - 1); + panel.add(text); text.grabFocus(); text.selectAll(); redraw(); } - private void finishRename( JTextField text, boolean saveName ) - { + private void finishRename(JTextField text, boolean saveName) { String newName = text.getText(); - if( saveName && newName != null && newName.length() > 0 ) - { - try - { - m_controller.rename( m_reference, newName ); - } - catch( IllegalNameException ex ) - { - text.setBorder( BorderFactory.createLineBorder( Color.red, 1 ) ); - text.setToolTipText( ex.getReason() ); - GuiTricks.showToolTipNow( text ); + if (saveName && newName != null && newName.length() > 0) { + try { + m_controller.rename(m_reference, newName); + } catch (IllegalNameException ex) { + text.setBorder(BorderFactory.createLineBorder(Color.red, 1)); + text.setToolTipText(ex.getReason()); + GuiTricks.showToolTipNow(text); } return; } // abort the rename - JPanel panel = (JPanel)m_infoPanel.getComponent( 0 ); - panel.remove( panel.getComponentCount() - 1 ); - panel.add( GuiTricks.unboldLabel( new JLabel( m_reference.getNamableName(), JLabel.LEFT ) ) ); + JPanel panel = (JPanel)m_infoPanel.getComponent(0); + panel.remove(panel.getComponentCount() - 1); + panel.add(GuiTricks.unboldLabel(new JLabel(m_reference.getNamableName(), JLabel.LEFT))); m_editor.grabFocus(); redraw(); } - private void showInheritance( ) - { - if( m_reference == null ) - { + private void showInheritance() { + + if (m_reference == null) { return; } - m_inheritanceTree.setModel( null ); + m_inheritanceTree.setModel(null); - if( m_reference.entry instanceof ClassEntry ) - { + if (m_reference.entry instanceof ClassEntry) { // get the class inheritance - ClassInheritanceTreeNode classNode = m_controller.getClassInheritance( (ClassEntry)m_reference.entry ); + ClassInheritanceTreeNode classNode = m_controller.getClassInheritance((ClassEntry)m_reference.entry); // show the tree at the root - TreePath path = getPathToRoot( classNode ); - m_inheritanceTree.setModel( new DefaultTreeModel( (TreeNode)path.getPathComponent( 0 ) ) ); - m_inheritanceTree.expandPath( path ); - m_inheritanceTree.setSelectionRow( m_inheritanceTree.getRowForPath( path ) ); - } - else if( m_reference.entry instanceof MethodEntry ) - { + TreePath path = getPathToRoot(classNode); + m_inheritanceTree.setModel(new DefaultTreeModel((TreeNode)path.getPathComponent(0))); + m_inheritanceTree.expandPath(path); + m_inheritanceTree.setSelectionRow(m_inheritanceTree.getRowForPath(path)); + } else if (m_reference.entry instanceof MethodEntry) { // get the method inheritance - MethodInheritanceTreeNode classNode = m_controller.getMethodInheritance( (MethodEntry)m_reference.entry ); + MethodInheritanceTreeNode classNode = m_controller.getMethodInheritance((MethodEntry)m_reference.entry); // show the tree at the root - TreePath path = getPathToRoot( classNode ); - m_inheritanceTree.setModel( new DefaultTreeModel( (TreeNode)path.getPathComponent( 0 ) ) ); - m_inheritanceTree.expandPath( path ); - m_inheritanceTree.setSelectionRow( m_inheritanceTree.getRowForPath( path ) ); + TreePath path = getPathToRoot(classNode); + m_inheritanceTree.setModel(new DefaultTreeModel((TreeNode)path.getPathComponent(0))); + m_inheritanceTree.expandPath(path); + m_inheritanceTree.setSelectionRow(m_inheritanceTree.getRowForPath(path)); } - m_tabs.setSelectedIndex( 0 ); + m_tabs.setSelectedIndex(0); redraw(); } - private void showImplementations( ) - { - if( m_reference == null ) - { + private void showImplementations() { + + if (m_reference == null) { return; } - m_implementationsTree.setModel( null ); + m_implementationsTree.setModel(null); - if( m_reference.entry instanceof ClassEntry ) - { + if (m_reference.entry instanceof ClassEntry) { // get the class implementations - ClassImplementationsTreeNode node = m_controller.getClassImplementations( (ClassEntry)m_reference.entry ); - if( node != null ) - { + ClassImplementationsTreeNode node = m_controller.getClassImplementations((ClassEntry)m_reference.entry); + if (node != null) { // show the tree at the root - TreePath path = getPathToRoot( node ); - m_implementationsTree.setModel( new DefaultTreeModel( (TreeNode)path.getPathComponent( 0 ) ) ); - m_implementationsTree.expandPath( path ); - m_implementationsTree.setSelectionRow( m_implementationsTree.getRowForPath( path ) ); + TreePath path = getPathToRoot(node); + m_implementationsTree.setModel(new DefaultTreeModel((TreeNode)path.getPathComponent(0))); + m_implementationsTree.expandPath(path); + m_implementationsTree.setSelectionRow(m_implementationsTree.getRowForPath(path)); } - } - else if( m_reference.entry instanceof MethodEntry ) - { + } else if (m_reference.entry instanceof MethodEntry) { // get the method implementations - MethodImplementationsTreeNode node = m_controller.getMethodImplementations( (MethodEntry)m_reference.entry ); - if( node != null ) - { + MethodImplementationsTreeNode node = m_controller.getMethodImplementations((MethodEntry)m_reference.entry); + if (node != null) { // show the tree at the root - TreePath path = getPathToRoot( node ); - m_implementationsTree.setModel( new DefaultTreeModel( (TreeNode)path.getPathComponent( 0 ) ) ); - m_implementationsTree.expandPath( path ); - m_implementationsTree.setSelectionRow( m_implementationsTree.getRowForPath( path ) ); + TreePath path = getPathToRoot(node); + m_implementationsTree.setModel(new DefaultTreeModel((TreeNode)path.getPathComponent(0))); + m_implementationsTree.expandPath(path); + m_implementationsTree.setSelectionRow(m_implementationsTree.getRowForPath(path)); } } - m_tabs.setSelectedIndex( 1 ); + m_tabs.setSelectedIndex(1); redraw(); } - private void showCalls( ) - { - if( m_reference == null ) - { + private void showCalls() { + + if (m_reference == null) { return; } - if( m_reference.entry instanceof ClassEntry ) - { + if (m_reference.entry instanceof ClassEntry) { // look for calls to the default constructor // TODO: get a list of all the constructors and find calls to all of them - BehaviorReferenceTreeNode node = m_controller.getMethodReferences( new ConstructorEntry( (ClassEntry)m_reference.entry, "()V" ) ); - m_callsTree.setModel( new DefaultTreeModel( node ) ); - } - else if( m_reference.entry instanceof FieldEntry ) - { - FieldReferenceTreeNode node = m_controller.getFieldReferences( (FieldEntry)m_reference.entry ); - m_callsTree.setModel( new DefaultTreeModel( node ) ); - } - else if( m_reference.entry instanceof MethodEntry ) - { - BehaviorReferenceTreeNode node = m_controller.getMethodReferences( (MethodEntry)m_reference.entry ); - m_callsTree.setModel( new DefaultTreeModel( node ) ); - } - else if( m_reference.entry instanceof ConstructorEntry ) - { - BehaviorReferenceTreeNode node = m_controller.getMethodReferences( (ConstructorEntry)m_reference.entry ); - m_callsTree.setModel( new DefaultTreeModel( node ) ); + BehaviorReferenceTreeNode node = m_controller.getMethodReferences(new ConstructorEntry((ClassEntry)m_reference.entry, "()V")); + m_callsTree.setModel(new DefaultTreeModel(node)); + } else if (m_reference.entry instanceof FieldEntry) { + FieldReferenceTreeNode node = m_controller.getFieldReferences((FieldEntry)m_reference.entry); + m_callsTree.setModel(new DefaultTreeModel(node)); + } else if (m_reference.entry instanceof MethodEntry) { + BehaviorReferenceTreeNode node = m_controller.getMethodReferences((MethodEntry)m_reference.entry); + m_callsTree.setModel(new DefaultTreeModel(node)); + } else if (m_reference.entry instanceof ConstructorEntry) { + BehaviorReferenceTreeNode node = m_controller.getMethodReferences((ConstructorEntry)m_reference.entry); + m_callsTree.setModel(new DefaultTreeModel(node)); } - m_tabs.setSelectedIndex( 2 ); + m_tabs.setSelectedIndex(2); redraw(); } - private void toggleMapping() - { - if( m_controller.entryHasDeobfuscatedName( m_reference.entry ) ) - { - m_controller.removeMapping( m_reference ); - } - else - { - m_controller.markAsDeobfuscated( m_reference ); + private void toggleMapping() { + if (m_controller.entryHasDeobfuscatedName(m_reference.entry)) { + m_controller.removeMapping(m_reference); + } else { + m_controller.markAsDeobfuscated(m_reference); } } - private TreePath getPathToRoot( TreeNode node ) - { + private TreePath getPathToRoot(TreeNode node) { List nodes = Lists.newArrayList(); TreeNode n = node; - do - { - nodes.add( n ); + do { + nodes.add(n); n = n.getParent(); - } - while( n != null ); - Collections.reverse( nodes ); - return new TreePath( nodes.toArray() ); + } while (n != null); + Collections.reverse(nodes); + return new TreePath(nodes.toArray()); } - private void close( ) - { - if( !m_controller.isDirty() ) - { + private void close() { + if (!m_controller.isDirty()) { // everything is saved, we can exit safely m_frame.dispose(); - } - else - { + } else { // ask to save before closing - String[] options = { - "Save and exit", - "Discard changes", - "Cancel" - }; - int response = JOptionPane.showOptionDialog( - m_frame, - "Your mappings have not been saved yet. Do you want to save?", - "Save your changes?", - JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, - null, - options, - options[2] - ); - switch( response ) - { + String[] options = { "Save and exit", "Discard changes", "Cancel" }; + int response = JOptionPane.showOptionDialog(m_frame, "Your mappings have not been saved yet. Do you want to save?", "Save your changes?", JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, null, options, options[2]); + switch (response) { case JOptionPane.YES_OPTION: // save and exit - if( m_mappingsFileChooser.getSelectedFile() != null || m_mappingsFileChooser.showSaveDialog( m_frame ) == JFileChooser.APPROVE_OPTION ) - { - try - { - m_controller.saveMappings( m_mappingsFileChooser.getSelectedFile() ); + if (m_mappingsFileChooser.getSelectedFile() != null || m_mappingsFileChooser.showSaveDialog(m_frame) == JFileChooser.APPROVE_OPTION) { + try { + m_controller.saveMappings(m_mappingsFileChooser.getSelectedFile()); m_frame.dispose(); - } - catch( IOException ex ) - { - throw new Error( ex ); + } catch (IOException ex) { + throw new Error(ex); } } break; @@ -1364,14 +1150,13 @@ public class Gui // don't save, exit m_frame.dispose(); break; - + // cancel means do nothing } } } - - private void redraw( ) - { + + private void redraw() { m_frame.validate(); m_frame.repaint(); } diff --git a/src/cuchaz/enigma/gui/GuiController.java b/src/cuchaz/enigma/gui/GuiController.java index 2862ebe..908c16f 100644 --- a/src/cuchaz/enigma/gui/GuiController.java +++ b/src/cuchaz/enigma/gui/GuiController.java @@ -44,8 +44,8 @@ import cuchaz.enigma.mapping.MappingsWriter; import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.TranslationDirection; -public class GuiController -{ +public class GuiController { + private Deobfuscator m_deobfuscator; private Gui m_gui; private SourceIndex m_index; @@ -53,8 +53,7 @@ public class GuiController private boolean m_isDirty; private Deque> m_referenceStack; - public GuiController( Gui gui ) - { + public GuiController(Gui gui) { m_gui = gui; m_deobfuscator = null; m_index = null; @@ -63,358 +62,292 @@ public class GuiController m_referenceStack = Queues.newArrayDeque(); } - public boolean isDirty( ) - { + public boolean isDirty() { return m_isDirty; } - public void openJar( final File file ) - throws IOException - { + public void openJar(final File file) throws IOException { m_gui.onStartOpenJar(); - m_deobfuscator = new Deobfuscator( file ); - m_gui.onFinishOpenJar( m_deobfuscator.getJarName() ); + m_deobfuscator = new Deobfuscator(file); + m_gui.onFinishOpenJar(m_deobfuscator.getJarName()); refreshClasses(); } - public void closeJar( ) - { + public void closeJar() { m_deobfuscator = null; m_gui.onCloseJar(); } - public void openMappings( File file ) - throws IOException, MappingParseException - { - FileReader in = new FileReader( file ); - m_deobfuscator.setMappings( new MappingsReader().read( in ) ); + public void openMappings(File file) throws IOException, MappingParseException { + FileReader in = new FileReader(file); + m_deobfuscator.setMappings(new MappingsReader().read(in)); in.close(); m_isDirty = false; - m_gui.setMappingsFile( file ); + m_gui.setMappingsFile(file); refreshClasses(); refreshCurrentClass(); } - - public void saveMappings( File file ) - throws IOException - { - FileWriter out = new FileWriter( file ); - new MappingsWriter().write( out, m_deobfuscator.getMappings() ); + + public void saveMappings(File file) throws IOException { + FileWriter out = new FileWriter(file); + new MappingsWriter().write(out, m_deobfuscator.getMappings()); out.close(); m_isDirty = false; } - - public void closeMappings( ) - { - m_deobfuscator.setMappings( null ); - m_gui.setMappingsFile( null ); + + public void closeMappings() { + m_deobfuscator.setMappings(null); + m_gui.setMappingsFile(null); refreshClasses(); refreshCurrentClass(); } - public void exportSource( final File dirOut ) - { - ProgressDialog.runInThread( m_gui.getFrame(), new ProgressRunnable( ) - { + public void exportSource(final File dirOut) { + ProgressDialog.runInThread(m_gui.getFrame(), new ProgressRunnable() { @Override - public void run( ProgressListener progress ) - throws Exception - { - m_deobfuscator.writeSources( dirOut, progress ); + public void run(ProgressListener progress) throws Exception { + m_deobfuscator.writeSources(dirOut, progress); } - } ); + }); } - public void exportJar( final File fileOut ) - { - ProgressDialog.runInThread( m_gui.getFrame(), new ProgressRunnable( ) - { + public void exportJar(final File fileOut) { + ProgressDialog.runInThread(m_gui.getFrame(), new ProgressRunnable() { @Override - public void run( ProgressListener progress ) - { - m_deobfuscator.writeJar( fileOut, progress ); + public void run(ProgressListener progress) { + m_deobfuscator.writeJar(fileOut, progress); } - } ); + }); } - public Token getToken( int pos ) - { - if( m_index == null ) - { + public Token getToken(int pos) { + if (m_index == null) { return null; } - return m_index.getReferenceToken( pos ); + return m_index.getReferenceToken(pos); } - public EntryReference getDeobfReference( Token token ) - { - if( m_index == null ) - { + public EntryReference getDeobfReference(Token token) { + if (m_index == null) { return null; } - return m_index.getDeobfReference( token ); + return m_index.getDeobfReference(token); } - public ReadableToken getReadableToken( Token token ) - { - if( m_index == null ) - { + public ReadableToken getReadableToken(Token token) { + if (m_index == null) { return null; } return new ReadableToken( - m_index.getLineNumber( token.start ), - m_index.getColumnNumber( token.start ), - m_index.getColumnNumber( token.end ) + m_index.getLineNumber(token.start), + m_index.getColumnNumber(token.start), + m_index.getColumnNumber(token.end) ); } - public boolean entryHasDeobfuscatedName( Entry deobfEntry ) - { - return m_deobfuscator.hasDeobfuscatedName( m_deobfuscator.obfuscateEntry( deobfEntry ) ); + public boolean entryHasDeobfuscatedName(Entry deobfEntry) { + return m_deobfuscator.hasDeobfuscatedName(m_deobfuscator.obfuscateEntry(deobfEntry)); } - public boolean entryIsInJar( Entry deobfEntry ) - { - return m_deobfuscator.isObfuscatedIdentifier( m_deobfuscator.obfuscateEntry( deobfEntry ) ); + public boolean entryIsInJar(Entry deobfEntry) { + return m_deobfuscator.isObfuscatedIdentifier(m_deobfuscator.obfuscateEntry(deobfEntry)); } - public boolean referenceIsRenameable( EntryReference deobfReference ) - { - return m_deobfuscator.isRenameable( m_deobfuscator.obfuscateReference( deobfReference ) ); + public boolean referenceIsRenameable(EntryReference deobfReference) { + return m_deobfuscator.isRenameable(m_deobfuscator.obfuscateReference(deobfReference)); } - public ClassInheritanceTreeNode getClassInheritance( ClassEntry deobfClassEntry ) - { - ClassEntry obfClassEntry = m_deobfuscator.obfuscateEntry( deobfClassEntry ); + public ClassInheritanceTreeNode getClassInheritance(ClassEntry deobfClassEntry) { + ClassEntry obfClassEntry = m_deobfuscator.obfuscateEntry(deobfClassEntry); ClassInheritanceTreeNode rootNode = m_deobfuscator.getJarIndex().getClassInheritance( - m_deobfuscator.getTranslator( TranslationDirection.Deobfuscating ), + m_deobfuscator.getTranslator(TranslationDirection.Deobfuscating), obfClassEntry ); - return ClassInheritanceTreeNode.findNode( rootNode, obfClassEntry ); + return ClassInheritanceTreeNode.findNode(rootNode, obfClassEntry); } - public ClassImplementationsTreeNode getClassImplementations( ClassEntry deobfClassEntry ) - { - ClassEntry obfClassEntry = m_deobfuscator.obfuscateEntry( deobfClassEntry ); + public ClassImplementationsTreeNode getClassImplementations(ClassEntry deobfClassEntry) { + ClassEntry obfClassEntry = m_deobfuscator.obfuscateEntry(deobfClassEntry); return m_deobfuscator.getJarIndex().getClassImplementations( - m_deobfuscator.getTranslator( TranslationDirection.Deobfuscating ), + m_deobfuscator.getTranslator(TranslationDirection.Deobfuscating), obfClassEntry ); } - public MethodInheritanceTreeNode getMethodInheritance( MethodEntry deobfMethodEntry ) - { - MethodEntry obfMethodEntry = m_deobfuscator.obfuscateEntry( deobfMethodEntry ); + public MethodInheritanceTreeNode getMethodInheritance(MethodEntry deobfMethodEntry) { + MethodEntry obfMethodEntry = m_deobfuscator.obfuscateEntry(deobfMethodEntry); MethodInheritanceTreeNode rootNode = m_deobfuscator.getJarIndex().getMethodInheritance( - m_deobfuscator.getTranslator( TranslationDirection.Deobfuscating ), + m_deobfuscator.getTranslator(TranslationDirection.Deobfuscating), obfMethodEntry ); - return MethodInheritanceTreeNode.findNode( rootNode, obfMethodEntry ); + return MethodInheritanceTreeNode.findNode(rootNode, obfMethodEntry); } - public MethodImplementationsTreeNode getMethodImplementations( MethodEntry deobfMethodEntry ) - { - MethodEntry obfMethodEntry = m_deobfuscator.obfuscateEntry( deobfMethodEntry ); + public MethodImplementationsTreeNode getMethodImplementations(MethodEntry deobfMethodEntry) { + MethodEntry obfMethodEntry = m_deobfuscator.obfuscateEntry(deobfMethodEntry); MethodImplementationsTreeNode rootNode = m_deobfuscator.getJarIndex().getMethodImplementations( - m_deobfuscator.getTranslator( TranslationDirection.Deobfuscating ), + m_deobfuscator.getTranslator(TranslationDirection.Deobfuscating), obfMethodEntry ); - if( rootNode == null ) - { + if (rootNode == null) { return null; } - return MethodImplementationsTreeNode.findNode( rootNode, obfMethodEntry ); + return MethodImplementationsTreeNode.findNode(rootNode, obfMethodEntry); } - public FieldReferenceTreeNode getFieldReferences( FieldEntry deobfFieldEntry ) - { - FieldEntry obfFieldEntry = m_deobfuscator.obfuscateEntry( deobfFieldEntry ); + public FieldReferenceTreeNode getFieldReferences(FieldEntry deobfFieldEntry) { + FieldEntry obfFieldEntry = m_deobfuscator.obfuscateEntry(deobfFieldEntry); FieldReferenceTreeNode rootNode = new FieldReferenceTreeNode( - m_deobfuscator.getTranslator( TranslationDirection.Deobfuscating ), + m_deobfuscator.getTranslator(TranslationDirection.Deobfuscating), obfFieldEntry ); - rootNode.load( m_deobfuscator.getJarIndex(), true ); + rootNode.load(m_deobfuscator.getJarIndex(), true); return rootNode; } - public BehaviorReferenceTreeNode getMethodReferences( BehaviorEntry deobfBehaviorEntry ) - { - BehaviorEntry obfBehaviorEntry = m_deobfuscator.obfuscateEntry( deobfBehaviorEntry ); + public BehaviorReferenceTreeNode getMethodReferences(BehaviorEntry deobfBehaviorEntry) { + BehaviorEntry obfBehaviorEntry = m_deobfuscator.obfuscateEntry(deobfBehaviorEntry); BehaviorReferenceTreeNode rootNode = new BehaviorReferenceTreeNode( - m_deobfuscator.getTranslator( TranslationDirection.Deobfuscating ), + m_deobfuscator.getTranslator(TranslationDirection.Deobfuscating), obfBehaviorEntry ); - rootNode.load( m_deobfuscator.getJarIndex(), true ); + rootNode.load(m_deobfuscator.getJarIndex(), true); return rootNode; } - public void rename( EntryReference deobfReference, String newName ) - { - EntryReference obfReference = m_deobfuscator.obfuscateReference( deobfReference ); - m_deobfuscator.rename( obfReference.getNameableEntry(), newName ); + public void rename(EntryReference deobfReference, String newName) { + EntryReference obfReference = m_deobfuscator.obfuscateReference(deobfReference); + m_deobfuscator.rename(obfReference.getNameableEntry(), newName); m_isDirty = true; refreshClasses(); - refreshCurrentClass( obfReference ); + refreshCurrentClass(obfReference); } - public void removeMapping( EntryReference deobfReference ) - { - EntryReference obfReference = m_deobfuscator.obfuscateReference( deobfReference ); - m_deobfuscator.removeMapping( obfReference.getNameableEntry() ); + public void removeMapping(EntryReference deobfReference) { + EntryReference obfReference = m_deobfuscator.obfuscateReference(deobfReference); + m_deobfuscator.removeMapping(obfReference.getNameableEntry()); m_isDirty = true; refreshClasses(); - refreshCurrentClass( obfReference ); + refreshCurrentClass(obfReference); } - public void markAsDeobfuscated( EntryReference deobfReference ) - { - EntryReference obfReference = m_deobfuscator.obfuscateReference( deobfReference ); - m_deobfuscator.markAsDeobfuscated( obfReference.getNameableEntry() ); + public void markAsDeobfuscated(EntryReference deobfReference) { + EntryReference obfReference = m_deobfuscator.obfuscateReference(deobfReference); + m_deobfuscator.markAsDeobfuscated(obfReference.getNameableEntry()); m_isDirty = true; refreshClasses(); - refreshCurrentClass( obfReference ); + refreshCurrentClass(obfReference); } - public void openDeclaration( Entry deobfEntry ) - { - if( deobfEntry == null ) - { - throw new IllegalArgumentException( "Entry cannot be null!" ); + public void openDeclaration(Entry deobfEntry) { + if (deobfEntry == null) { + throw new IllegalArgumentException("Entry cannot be null!"); } - openReference( new EntryReference( deobfEntry, deobfEntry.getName() ) ); + openReference(new EntryReference(deobfEntry, deobfEntry.getName())); } - public void openReference( EntryReference deobfReference ) - { - if( deobfReference == null ) - { - throw new IllegalArgumentException( "Reference cannot be null!" ); + public void openReference(EntryReference deobfReference) { + if (deobfReference == null) { + throw new IllegalArgumentException("Reference cannot be null!"); } // get the reference target class - EntryReference obfReference = m_deobfuscator.obfuscateReference( deobfReference ); + EntryReference obfReference = m_deobfuscator.obfuscateReference(deobfReference); ClassEntry obfClassEntry = obfReference.getLocationClassEntry().getOuterClassEntry(); - if( !m_deobfuscator.isObfuscatedIdentifier( obfClassEntry ) ) - { - throw new IllegalArgumentException( "Obfuscated class " + obfClassEntry + " was not found in the jar!" ); + if (!m_deobfuscator.isObfuscatedIdentifier(obfClassEntry)) { + throw new IllegalArgumentException("Obfuscated class " + obfClassEntry + " was not found in the jar!"); } - if( m_currentObfClass == null || !m_currentObfClass.equals( obfClassEntry ) ) - { + if (m_currentObfClass == null || !m_currentObfClass.equals(obfClassEntry)) { // deobfuscate the class, then navigate to the reference m_currentObfClass = obfClassEntry; - deobfuscate( m_currentObfClass, obfReference ); - } - else - { - showReference( obfReference ); + deobfuscate(m_currentObfClass, obfReference); + } else { + showReference(obfReference); } } - private void showReference( EntryReference obfReference ) - { - EntryReference deobfReference = m_deobfuscator.deobfuscateReference( obfReference ); - Collection tokens = m_index.getReferenceTokens( deobfReference ); - if( tokens.isEmpty() ) - { + private void showReference(EntryReference obfReference) { + EntryReference deobfReference = m_deobfuscator.deobfuscateReference(obfReference); + Collection tokens = m_index.getReferenceTokens(deobfReference); + if (tokens.isEmpty()) { // DEBUG - System.err.println( String.format( "WARNING: no tokens found for %s in %s", deobfReference, m_currentObfClass ) ); - } - else - { - m_gui.showTokens( tokens ); + System.err.println(String.format("WARNING: no tokens found for %s in %s", deobfReference, m_currentObfClass)); + } else { + m_gui.showTokens(tokens); } } - public void savePreviousReference( EntryReference deobfReference ) - { - m_referenceStack.push( m_deobfuscator.obfuscateReference( deobfReference ) ); + public void savePreviousReference(EntryReference deobfReference) { + m_referenceStack.push(m_deobfuscator.obfuscateReference(deobfReference)); } - public void openPreviousReference( ) - { - if( hasPreviousLocation() ) - { - openReference( m_deobfuscator.deobfuscateReference( m_referenceStack.pop() ) ); + public void openPreviousReference() { + if (hasPreviousLocation()) { + openReference(m_deobfuscator.deobfuscateReference(m_referenceStack.pop())); } } - public boolean hasPreviousLocation( ) - { + public boolean hasPreviousLocation() { return !m_referenceStack.isEmpty(); } - private void refreshClasses( ) - { + private void refreshClasses() { List obfClasses = Lists.newArrayList(); List deobfClasses = Lists.newArrayList(); - m_deobfuscator.getSeparatedClasses( obfClasses, deobfClasses ); - m_gui.setObfClasses( obfClasses ); - m_gui.setDeobfClasses( deobfClasses ); + m_deobfuscator.getSeparatedClasses(obfClasses, deobfClasses); + m_gui.setObfClasses(obfClasses); + m_gui.setDeobfClasses(deobfClasses); } - private void refreshCurrentClass( ) - { - refreshCurrentClass( null ); + private void refreshCurrentClass() { + refreshCurrentClass(null); } - private void refreshCurrentClass( EntryReference obfReference ) - { - if( m_currentObfClass != null ) - { - deobfuscate( m_currentObfClass, obfReference ); + private void refreshCurrentClass(EntryReference obfReference) { + if (m_currentObfClass != null) { + deobfuscate(m_currentObfClass, obfReference); } } - private void deobfuscate( final ClassEntry classEntry, final EntryReference obfReference ) - { - m_gui.setSource( "(deobfuscating...)" ); + private void deobfuscate(final ClassEntry classEntry, final EntryReference obfReference) { + + m_gui.setSource("(deobfuscating...)"); // run the deobfuscator in a separate thread so we don't block the GUI event queue - new Thread( ) - { + new Thread() { @Override - public void run( ) - { + public void run() { // decompile,deobfuscate the bytecode - CompilationUnit sourceTree = m_deobfuscator.getSourceTree( classEntry.getClassName() ); - if( sourceTree == null ) - { + CompilationUnit sourceTree = m_deobfuscator.getSourceTree(classEntry.getClassName()); + if (sourceTree == null) { // decompilation of this class is not supported m_gui.setSource("Unable to find class: " + classEntry); return; } - String source = m_deobfuscator.getSource( sourceTree ); - m_index = m_deobfuscator.getSourceIndex( sourceTree, source ); - m_gui.setSource( m_index.getSource() ); - if( obfReference != null ) - { - showReference( obfReference ); + String source = m_deobfuscator.getSource(sourceTree); + m_index = m_deobfuscator.getSourceIndex(sourceTree, source); + m_gui.setSource(m_index.getSource()); + if (obfReference != null) { + showReference(obfReference); } // set the highlighted tokens List obfuscatedTokens = Lists.newArrayList(); List deobfuscatedTokens = Lists.newArrayList(); List otherTokens = Lists.newArrayList(); - for( Token token : m_index.referenceTokens() ) - { - EntryReference reference = m_index.getDeobfReference( token ); - if( referenceIsRenameable( reference ) ) - { - if( entryHasDeobfuscatedName( reference.getNameableEntry() ) ) - { - deobfuscatedTokens.add( token ); + for (Token token : m_index.referenceTokens()) { + EntryReference reference = m_index.getDeobfReference(token); + if (referenceIsRenameable(reference)) { + if (entryHasDeobfuscatedName(reference.getNameableEntry())) { + deobfuscatedTokens.add(token); + } else { + obfuscatedTokens.add(token); } - else - { - obfuscatedTokens.add( token ); - } - } - else - { - otherTokens.add( token ); + } else { + otherTokens.add(token); } } - m_gui.setHighlightedTokens( obfuscatedTokens, deobfuscatedTokens, otherTokens ); + m_gui.setHighlightedTokens(obfuscatedTokens, deobfuscatedTokens, otherTokens); } }.start(); } diff --git a/src/cuchaz/enigma/gui/GuiTricks.java b/src/cuchaz/enigma/gui/GuiTricks.java index 9b889ef..df9e221 100644 --- a/src/cuchaz/enigma/gui/GuiTricks.java +++ b/src/cuchaz/enigma/gui/GuiTricks.java @@ -17,27 +17,20 @@ import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.ToolTipManager; -public class GuiTricks -{ - public static JLabel unboldLabel( JLabel label ) - { +public class GuiTricks { + + public static JLabel unboldLabel(JLabel label) { Font font = label.getFont(); - label.setFont( font.deriveFont( font.getStyle() & ~Font.BOLD ) ); + label.setFont(font.deriveFont(font.getStyle() & ~Font.BOLD)); return label; } - public static void showToolTipNow( JComponent component ) - { + public static void showToolTipNow(JComponent component) { // HACKHACK: trick the tooltip manager into showing the tooltip right now ToolTipManager manager = ToolTipManager.sharedInstance(); int oldDelay = manager.getInitialDelay(); - manager.setInitialDelay( 0 ); - manager.mouseMoved( new MouseEvent( - component, - MouseEvent.MOUSE_MOVED, - System.currentTimeMillis(), - 0, 0, 0, 0, false - ) ); - manager.setInitialDelay( oldDelay ); + manager.setInitialDelay(0); + manager.mouseMoved(new MouseEvent(component, MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), 0, 0, 0, 0, false)); + manager.setInitialDelay(oldDelay); } } diff --git a/src/cuchaz/enigma/gui/ObfuscatedHighlightPainter.java b/src/cuchaz/enigma/gui/ObfuscatedHighlightPainter.java index 724be34..177835f 100644 --- a/src/cuchaz/enigma/gui/ObfuscatedHighlightPainter.java +++ b/src/cuchaz/enigma/gui/ObfuscatedHighlightPainter.java @@ -12,11 +12,10 @@ package cuchaz.enigma.gui; import java.awt.Color; -public class ObfuscatedHighlightPainter extends BoxHighlightPainter -{ - public ObfuscatedHighlightPainter( ) - { +public class ObfuscatedHighlightPainter extends BoxHighlightPainter { + + public ObfuscatedHighlightPainter() { // red ish - super( new Color( 255, 220, 220 ), new Color( 160, 80, 80 ) ); + super(new Color(255, 220, 220), new Color(160, 80, 80)); } } diff --git a/src/cuchaz/enigma/gui/OtherHighlightPainter.java b/src/cuchaz/enigma/gui/OtherHighlightPainter.java index 78de732..4e9c870 100644 --- a/src/cuchaz/enigma/gui/OtherHighlightPainter.java +++ b/src/cuchaz/enigma/gui/OtherHighlightPainter.java @@ -12,11 +12,10 @@ package cuchaz.enigma.gui; import java.awt.Color; -public class OtherHighlightPainter extends BoxHighlightPainter -{ - public OtherHighlightPainter( ) - { +public class OtherHighlightPainter extends BoxHighlightPainter { + + public OtherHighlightPainter() { // grey - super( null, new Color( 180, 180, 180 ) ); + super(null, new Color(180, 180, 180)); } } diff --git a/src/cuchaz/enigma/gui/ProgressDialog.java b/src/cuchaz/enigma/gui/ProgressDialog.java index 7f95431..b864fdb 100644 --- a/src/cuchaz/enigma/gui/ProgressDialog.java +++ b/src/cuchaz/enigma/gui/ProgressDialog.java @@ -25,89 +25,79 @@ import javax.swing.WindowConstants; import cuchaz.enigma.Constants; import cuchaz.enigma.Deobfuscator.ProgressListener; -public class ProgressDialog implements ProgressListener, AutoCloseable -{ +public class ProgressDialog implements ProgressListener, AutoCloseable { + private JFrame m_frame; private JLabel m_title; private JLabel m_text; private JProgressBar m_progress; - public ProgressDialog( JFrame parent ) - { + public ProgressDialog(JFrame parent) { + // init frame - m_frame = new JFrame( Constants.Name + " - Operation in progress" ); + m_frame = new JFrame(Constants.Name + " - Operation in progress"); final Container pane = m_frame.getContentPane(); FlowLayout layout = new FlowLayout(); - layout.setAlignment( FlowLayout.LEFT ); - pane.setLayout( layout ); + layout.setAlignment(FlowLayout.LEFT); + pane.setLayout(layout); m_title = new JLabel(); - pane.add( m_title ); + pane.add(m_title); // set up the progress bar JPanel panel = new JPanel(); - pane.add( panel ); - panel.setLayout( new BorderLayout() ); - m_text = GuiTricks.unboldLabel( new JLabel() ); + pane.add(panel); + panel.setLayout(new BorderLayout()); + m_text = GuiTricks.unboldLabel(new JLabel()); m_progress = new JProgressBar(); - m_text.setBorder( BorderFactory.createEmptyBorder( 0, 0, 10, 0 ) ); - panel.add( m_text, BorderLayout.NORTH ); - panel.add( m_progress, BorderLayout.CENTER ); - panel.setPreferredSize( new Dimension( 360, 50 ) ); + m_text.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); + panel.add(m_text, BorderLayout.NORTH); + panel.add(m_progress, BorderLayout.CENTER); + panel.setPreferredSize(new Dimension(360, 50)); // show the frame pane.doLayout(); - m_frame.setSize( 400, 120 ); - m_frame.setResizable( false ); - m_frame.setLocationRelativeTo( parent ); - m_frame.setVisible( true ); - m_frame.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); + m_frame.setSize(400, 120); + m_frame.setResizable(false); + m_frame.setLocationRelativeTo(parent); + m_frame.setVisible(true); + m_frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); } - public void close( ) - { + public void close() { m_frame.dispose(); } - + @Override - public void init( int totalWork, String title ) - { - m_title.setText( title ); - m_progress.setMinimum( 0 ); - m_progress.setMaximum( totalWork ); - m_progress.setValue( 0 ); + public void init(int totalWork, String title) { + m_title.setText(title); + m_progress.setMinimum(0); + m_progress.setMaximum(totalWork); + m_progress.setValue(0); } - + @Override - public void onProgress( int numDone, String message ) - { - m_text.setText( message ); - m_progress.setValue( numDone ); + public void onProgress(int numDone, String message) { + m_text.setText(message); + m_progress.setValue(numDone); // update the frame m_frame.validate(); m_frame.repaint(); } - public static interface ProgressRunnable - { - void run( ProgressListener listener ) throws Exception; + public static interface ProgressRunnable { + void run(ProgressListener listener) throws Exception; } - public static void runInThread( final JFrame parent, final ProgressRunnable runnable ) - { - new Thread( ) - { + public static void runInThread(final JFrame parent, final ProgressRunnable runnable) { + new Thread() { @Override - public void run( ) - { - try( ProgressDialog progress = new ProgressDialog( parent ) ) - { - runnable.run( progress ); - } - catch( Exception ex ) - { - throw new Error( ex ); + public void run() { + try (ProgressDialog progress = new ProgressDialog(parent)) { + runnable.run(progress); + } catch (Exception ex) { + throw new Error(ex); } } }.start(); diff --git a/src/cuchaz/enigma/gui/ReadableToken.java b/src/cuchaz/enigma/gui/ReadableToken.java index 3f43045..66bcbc2 100644 --- a/src/cuchaz/enigma/gui/ReadableToken.java +++ b/src/cuchaz/enigma/gui/ReadableToken.java @@ -10,29 +10,27 @@ ******************************************************************************/ package cuchaz.enigma.gui; -public class ReadableToken -{ +public class ReadableToken { + public int line; public int startColumn; public int endColumn; - public ReadableToken( int line, int startColumn, int endColumn ) - { + public ReadableToken(int line, int startColumn, int endColumn) { this.line = line; this.startColumn = startColumn; this.endColumn = endColumn; } @Override - public String toString( ) - { + public String toString() { StringBuilder buf = new StringBuilder(); - buf.append( "line " ); - buf.append( line ); - buf.append( " columns " ); - buf.append( startColumn ); - buf.append( "-" ); - buf.append( endColumn ); + buf.append("line "); + buf.append(line); + buf.append(" columns "); + buf.append(startColumn); + buf.append("-"); + buf.append(endColumn); return buf.toString(); } } diff --git a/src/cuchaz/enigma/gui/RenameListener.java b/src/cuchaz/enigma/gui/RenameListener.java index 7d45505..abeda0c 100644 --- a/src/cuchaz/enigma/gui/RenameListener.java +++ b/src/cuchaz/enigma/gui/RenameListener.java @@ -12,7 +12,6 @@ package cuchaz.enigma.gui; import cuchaz.enigma.mapping.Entry; -public interface RenameListener -{ - void rename( Entry obfEntry, String newName ); +public interface RenameListener { + void rename(Entry obfEntry, String newName); } diff --git a/src/cuchaz/enigma/gui/SelectionHighlightPainter.java b/src/cuchaz/enigma/gui/SelectionHighlightPainter.java index 35f9451..5e189d2 100644 --- a/src/cuchaz/enigma/gui/SelectionHighlightPainter.java +++ b/src/cuchaz/enigma/gui/SelectionHighlightPainter.java @@ -20,16 +20,15 @@ import java.awt.Shape; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; -public class SelectionHighlightPainter implements Highlighter.HighlightPainter -{ +public class SelectionHighlightPainter implements Highlighter.HighlightPainter { + @Override - public void paint( Graphics g, int start, int end, Shape shape, JTextComponent text ) - { + public void paint(Graphics g, int start, int end, Shape shape, JTextComponent text) { // draw a thick border Graphics2D g2d = (Graphics2D)g; - Rectangle bounds = BoxHighlightPainter.getBounds( text, start, end ); - g2d.setColor( Color.black ); - g2d.setStroke( new BasicStroke( 2.0f ) ); - g2d.drawRoundRect( bounds.x, bounds.y, bounds.width, bounds.height, 4, 4 ); + Rectangle bounds = BoxHighlightPainter.getBounds(text, start, end); + g2d.setColor(Color.black); + g2d.setStroke(new BasicStroke(2.0f)); + g2d.drawRoundRect(bounds.x, bounds.y, bounds.width, bounds.height, 4, 4); } } diff --git a/src/cuchaz/enigma/gui/TokenListCellRenderer.java b/src/cuchaz/enigma/gui/TokenListCellRenderer.java index 9247c06..a49be37 100644 --- a/src/cuchaz/enigma/gui/TokenListCellRenderer.java +++ b/src/cuchaz/enigma/gui/TokenListCellRenderer.java @@ -19,22 +19,20 @@ import javax.swing.ListCellRenderer; import cuchaz.enigma.analysis.Token; -public class TokenListCellRenderer implements ListCellRenderer -{ +public class TokenListCellRenderer implements ListCellRenderer { + private GuiController m_controller; private DefaultListCellRenderer m_defaultRenderer; - public TokenListCellRenderer( GuiController controller ) - { + public TokenListCellRenderer(GuiController controller) { m_controller = controller; m_defaultRenderer = new DefaultListCellRenderer(); } @Override - public Component getListCellRendererComponent( JList list, Token token, int index, boolean isSelected, boolean hasFocus ) - { - JLabel label = (JLabel)m_defaultRenderer.getListCellRendererComponent( list, token, index, isSelected, hasFocus ); - label.setText( m_controller.getReadableToken( token ).toString() ); + public Component getListCellRendererComponent(JList list, Token token, int index, boolean isSelected, boolean hasFocus) { + JLabel label = (JLabel)m_defaultRenderer.getListCellRendererComponent(list, token, index, isSelected, hasFocus); + label.setText(m_controller.getReadableToken(token).toString()); return label; } } diff --git a/src/cuchaz/enigma/mapping/ArgumentEntry.java b/src/cuchaz/enigma/mapping/ArgumentEntry.java index 7ed3d32..2c15f4e 100644 --- a/src/cuchaz/enigma/mapping/ArgumentEntry.java +++ b/src/cuchaz/enigma/mapping/ArgumentEntry.java @@ -14,27 +14,23 @@ import java.io.Serializable; import cuchaz.enigma.Util; -public class ArgumentEntry implements Entry, Serializable -{ +public class ArgumentEntry implements Entry, Serializable { + private static final long serialVersionUID = 4472172468162696006L; private BehaviorEntry m_behaviorEntry; private int m_index; private String m_name; - public ArgumentEntry( BehaviorEntry behaviorEntry, int index, String name ) - { - if( behaviorEntry == null ) - { - throw new IllegalArgumentException( "Behavior cannot be null!" ); + public ArgumentEntry(BehaviorEntry behaviorEntry, int index, String name) { + if (behaviorEntry == null) { + throw new IllegalArgumentException("Behavior cannot be null!"); } - if( index < 0 ) - { - throw new IllegalArgumentException( "Index must be non-negative!" ); + if (index < 0) { + throw new IllegalArgumentException("Index must be non-negative!"); } - if( name == null ) - { - throw new IllegalArgumentException( "Argument name cannot be null!" ); + if (name == null) { + throw new IllegalArgumentException("Argument name cannot be null!"); } m_behaviorEntry = behaviorEntry; @@ -42,90 +38,79 @@ public class ArgumentEntry implements Entry, Serializable m_name = name; } - public ArgumentEntry( ArgumentEntry other ) - { - m_behaviorEntry = (BehaviorEntry)m_behaviorEntry.cloneToNewClass( getClassEntry() ); + public ArgumentEntry(ArgumentEntry other) { + m_behaviorEntry = (BehaviorEntry)m_behaviorEntry.cloneToNewClass(getClassEntry()); m_index = other.m_index; m_name = other.m_name; } - public ArgumentEntry( ArgumentEntry other, String newClassName ) - { - m_behaviorEntry = (BehaviorEntry)other.m_behaviorEntry.cloneToNewClass( new ClassEntry( newClassName ) ); + public ArgumentEntry(ArgumentEntry other, String newClassName) { + m_behaviorEntry = (BehaviorEntry)other.m_behaviorEntry.cloneToNewClass(new ClassEntry(newClassName)); m_index = other.m_index; m_name = other.m_name; } - public BehaviorEntry getBehaviorEntry( ) - { + public BehaviorEntry getBehaviorEntry() { return m_behaviorEntry; } - public int getIndex( ) - { + public int getIndex() { return m_index; } @Override - public String getName( ) - { + public String getName() { return m_name; } @Override - public ClassEntry getClassEntry( ) - { + public ClassEntry getClassEntry() { return m_behaviorEntry.getClassEntry(); } @Override - public String getClassName( ) - { + public String getClassName() { return m_behaviorEntry.getClassName(); } @Override - public ArgumentEntry cloneToNewClass( ClassEntry classEntry ) - { - return new ArgumentEntry( this, classEntry.getName() ); + public ArgumentEntry cloneToNewClass(ClassEntry classEntry) { + return new ArgumentEntry(this, classEntry.getName()); } - public String getMethodName( ) - { + public String getMethodName() { return m_behaviorEntry.getName(); } - public String getMethodSignature( ) - { + public String getMethodSignature() { return m_behaviorEntry.getSignature(); } @Override - public int hashCode( ) - { - return Util.combineHashesOrdered( m_behaviorEntry, Integer.valueOf( m_index ).hashCode(), m_name.hashCode() ); + public int hashCode() { + return Util.combineHashesOrdered( + m_behaviorEntry, + Integer.valueOf(m_index).hashCode(), + m_name.hashCode() + ); } @Override - public boolean equals( Object other ) - { - if( other instanceof ArgumentEntry ) - { - return equals( (ArgumentEntry)other ); + public boolean equals(Object other) { + if (other instanceof ArgumentEntry) { + return equals((ArgumentEntry)other); } return false; } - public boolean equals( ArgumentEntry other ) - { - return m_behaviorEntry.equals( other.m_behaviorEntry ) + public boolean equals(ArgumentEntry other) { + return m_behaviorEntry.equals(other.m_behaviorEntry) && m_index == other.m_index - && m_name.equals( other.m_name ); + && m_name.equals(other.m_name); } @Override - public String toString( ) - { + public String toString() { return m_behaviorEntry.toString() + "(" + m_index + ":" + m_name + ")"; } } diff --git a/src/cuchaz/enigma/mapping/ArgumentMapping.java b/src/cuchaz/enigma/mapping/ArgumentMapping.java index 168306a..f4d8e77 100644 --- a/src/cuchaz/enigma/mapping/ArgumentMapping.java +++ b/src/cuchaz/enigma/mapping/ArgumentMapping.java @@ -12,37 +12,33 @@ package cuchaz.enigma.mapping; import java.io.Serializable; -public class ArgumentMapping implements Serializable, Comparable -{ +public class ArgumentMapping implements Serializable, Comparable { + private static final long serialVersionUID = 8610742471440861315L; private int m_index; private String m_name; // NOTE: this argument order is important for the MethodReader/MethodWriter - public ArgumentMapping( int index, String name ) - { + public ArgumentMapping(int index, String name) { m_index = index; - m_name = NameValidator.validateArgumentName( name ); + m_name = NameValidator.validateArgumentName(name); } - public int getIndex( ) - { + public int getIndex() { return m_index; } - public String getName( ) - { + public String getName() { return m_name; } - public void setName( String val ) - { - m_name = NameValidator.validateArgumentName( val ); + + public void setName(String val) { + m_name = NameValidator.validateArgumentName(val); } @Override - public int compareTo( ArgumentMapping other ) - { - return Integer.compare( m_index, other.m_index ); + public int compareTo(ArgumentMapping other) { + return Integer.compare(m_index, other.m_index); } } diff --git a/src/cuchaz/enigma/mapping/BehaviorEntry.java b/src/cuchaz/enigma/mapping/BehaviorEntry.java index 8fc4eaf..f4200b8 100644 --- a/src/cuchaz/enigma/mapping/BehaviorEntry.java +++ b/src/cuchaz/enigma/mapping/BehaviorEntry.java @@ -10,7 +10,6 @@ ******************************************************************************/ package cuchaz.enigma.mapping; -public interface BehaviorEntry extends Entry -{ +public interface BehaviorEntry extends Entry { String getSignature(); } diff --git a/src/cuchaz/enigma/mapping/BehaviorEntryFactory.java b/src/cuchaz/enigma/mapping/BehaviorEntryFactory.java index d3cfb93..386faeb 100644 --- a/src/cuchaz/enigma/mapping/BehaviorEntryFactory.java +++ b/src/cuchaz/enigma/mapping/BehaviorEntryFactory.java @@ -15,62 +15,43 @@ import javassist.CtConstructor; import javassist.CtMethod; import javassist.bytecode.Descriptor; - -public class BehaviorEntryFactory -{ - public static BehaviorEntry create( String className, String name, String signature ) - { - return create( new ClassEntry( className ), name, signature ); +public class BehaviorEntryFactory { + + public static BehaviorEntry create(String className, String name, String signature) { + return create(new ClassEntry(className), name, signature); } - public static BehaviorEntry create( ClassEntry classEntry, String name, String signature ) - { - if( name.equals( "" ) ) - { - return new ConstructorEntry( classEntry, signature ); - } - else if( name.equals( "" ) ) - { - return new ConstructorEntry( classEntry ); - } - else - { - return new MethodEntry( classEntry, name, signature ); + public static BehaviorEntry create(ClassEntry classEntry, String name, String signature) { + if (name.equals("")) { + return new ConstructorEntry(classEntry, signature); + } else if (name.equals("")) { + return new ConstructorEntry(classEntry); + } else { + return new MethodEntry(classEntry, name, signature); } } - public static BehaviorEntry create( CtBehavior behavior ) - { - String className = Descriptor.toJvmName( behavior.getDeclaringClass().getName() ); - if( behavior instanceof CtMethod ) - { - return create( className, behavior.getName(), behavior.getSignature() ); - } - else if( behavior instanceof CtConstructor ) - { + public static BehaviorEntry create(CtBehavior behavior) { + String className = Descriptor.toJvmName(behavior.getDeclaringClass().getName()); + if (behavior instanceof CtMethod) { + return create(className, behavior.getName(), behavior.getSignature()); + } else if (behavior instanceof CtConstructor) { CtConstructor constructor = (CtConstructor)behavior; - if( constructor.isClassInitializer() ) - { - return create( className, "", null ); - } - else - { - return create( className, "", constructor.getSignature() ); + if (constructor.isClassInitializer()) { + return create(className, "", null); + } else { + return create(className, "", constructor.getSignature()); } - } - else - { - throw new IllegalArgumentException( "Unable to create BehaviorEntry from " + behavior ); + } else { + throw new IllegalArgumentException("Unable to create BehaviorEntry from " + behavior); } } - public static BehaviorEntry createObf( ClassEntry classEntry, MethodMapping methodMapping ) - { - return create( classEntry, methodMapping.getObfName(), methodMapping.getObfSignature() ); + public static BehaviorEntry createObf(ClassEntry classEntry, MethodMapping methodMapping) { + return create(classEntry, methodMapping.getObfName(), methodMapping.getObfSignature()); } - public static BehaviorEntry createDeobf( ClassEntry classEntry, MethodMapping methodMapping ) - { - return create( classEntry, methodMapping.getDeobfName(), methodMapping.getObfSignature() ); + public static BehaviorEntry createDeobf(ClassEntry classEntry, MethodMapping methodMapping) { + return create(classEntry, methodMapping.getDeobfName(), methodMapping.getObfSignature()); } } diff --git a/src/cuchaz/enigma/mapping/ClassEntry.java b/src/cuchaz/enigma/mapping/ClassEntry.java index 2c708f2..cf41001 100644 --- a/src/cuchaz/enigma/mapping/ClassEntry.java +++ b/src/cuchaz/enigma/mapping/ClassEntry.java @@ -12,137 +12,111 @@ package cuchaz.enigma.mapping; import java.io.Serializable; - -public class ClassEntry implements Entry, Serializable -{ +public class ClassEntry implements Entry, Serializable { + private static final long serialVersionUID = 4235460580973955811L; private String m_name; - public ClassEntry( String className ) - { - if( className == null ) - { - throw new IllegalArgumentException( "Class name cannot be null!" ); + public ClassEntry(String className) { + if (className == null) { + throw new IllegalArgumentException("Class name cannot be null!"); } - if( className.indexOf( '.' ) >= 0 ) - { - throw new IllegalArgumentException( "Class name must be in JVM format. ie, path/to/package/class$inner : " + className ); + if (className.indexOf('.') >= 0) { + throw new IllegalArgumentException("Class name must be in JVM format. ie, path/to/package/class$inner : " + className); } m_name = className; - if( isInnerClass() && getInnerClassName().indexOf( '/' ) >= 0 ) - { - throw new IllegalArgumentException( "Inner class must not have a package: " + className ); + if (isInnerClass() && getInnerClassName().indexOf('/') >= 0) { + throw new IllegalArgumentException("Inner class must not have a package: " + className); } } - public ClassEntry( ClassEntry other ) - { + public ClassEntry(ClassEntry other) { m_name = other.m_name; } @Override - public String getName( ) - { + public String getName() { return m_name; } @Override - public String getClassName( ) - { + public String getClassName() { return m_name; } @Override - public ClassEntry getClassEntry( ) - { + public ClassEntry getClassEntry() { return this; } @Override - public ClassEntry cloneToNewClass( ClassEntry classEntry ) - { + public ClassEntry cloneToNewClass(ClassEntry classEntry) { return classEntry; } - + @Override - public int hashCode( ) - { + public int hashCode() { return m_name.hashCode(); } @Override - public boolean equals( Object other ) - { - if( other instanceof ClassEntry ) - { - return equals( (ClassEntry)other ); + public boolean equals(Object other) { + if (other instanceof ClassEntry) { + return equals((ClassEntry)other); } return false; } - public boolean equals( ClassEntry other ) - { - return m_name.equals( other.m_name ); + public boolean equals(ClassEntry other) { + return m_name.equals(other.m_name); } @Override - public String toString( ) - { + public String toString() { return m_name; } - public boolean isInnerClass( ) - { - return m_name.lastIndexOf( '$' ) >= 0; + public boolean isInnerClass() { + return m_name.lastIndexOf('$') >= 0; } - public String getOuterClassName( ) - { - if( isInnerClass() ) - { - return m_name.substring( 0, m_name.lastIndexOf( '$' ) ); + public String getOuterClassName() { + if (isInnerClass()) { + return m_name.substring(0, m_name.lastIndexOf('$')); } return m_name; } - public String getInnerClassName( ) - { - if( !isInnerClass() ) - { - throw new Error( "This is not an inner class!" ); + public String getInnerClassName() { + if (!isInnerClass()) { + throw new Error("This is not an inner class!"); } - return m_name.substring( m_name.lastIndexOf( '$' ) + 1 ); + return m_name.substring(m_name.lastIndexOf('$') + 1); } - public ClassEntry getOuterClassEntry( ) - { - return new ClassEntry( getOuterClassName() ); + public ClassEntry getOuterClassEntry() { + return new ClassEntry(getOuterClassName()); } - public boolean isInDefaultPackage( ) - { - return m_name.indexOf( '/' ) < 0; + public boolean isInDefaultPackage() { + return m_name.indexOf('/') < 0; } - - public String getPackageName( ) - { - int pos = m_name.lastIndexOf( '/' ); - if( pos > 0 ) - { - return m_name.substring( 0, pos ); + + public String getPackageName() { + int pos = m_name.lastIndexOf('/'); + if (pos > 0) { + return m_name.substring(0, pos); } return null; } - - public String getSimpleName( ) - { - int pos = m_name.lastIndexOf( '/' ); - if( pos > 0 ) - { - return m_name.substring( pos + 1 ); + + public String getSimpleName() { + int pos = m_name.lastIndexOf('/'); + if (pos > 0) { + return m_name.substring(pos + 1); } return m_name; } diff --git a/src/cuchaz/enigma/mapping/ClassMapping.java b/src/cuchaz/enigma/mapping/ClassMapping.java index e084d4d..dbb8717 100644 --- a/src/cuchaz/enigma/mapping/ClassMapping.java +++ b/src/cuchaz/enigma/mapping/ClassMapping.java @@ -16,8 +16,8 @@ import java.util.Map; import com.google.common.collect.Maps; -public class ClassMapping implements Serializable, Comparable -{ +public class ClassMapping implements Serializable, Comparable { + private static final long serialVersionUID = -5148491146902340107L; private String m_obfName; @@ -29,15 +29,13 @@ public class ClassMapping implements Serializable, Comparable private Map m_methodsByObf; private Map m_methodsByDeobf; - public ClassMapping( String obfName ) - { - this( obfName, null ); + public ClassMapping(String obfName) { + this(obfName, null); } - public ClassMapping( String obfName, String deobfName ) - { + public ClassMapping(String obfName, String deobfName) { m_obfName = obfName; - m_deobfName = NameValidator.validateClassName( deobfName, false ); + m_deobfName = NameValidator.validateClassName(deobfName, false); m_innerClassesByObf = Maps.newHashMap(); m_innerClassesByDeobf = Maps.newHashMap(); m_fieldsByObf = Maps.newHashMap(); @@ -45,439 +43,363 @@ public class ClassMapping implements Serializable, Comparable m_methodsByObf = Maps.newHashMap(); m_methodsByDeobf = Maps.newHashMap(); } - - public String getObfName( ) - { + + public String getObfName() { return m_obfName; } - public String getDeobfName( ) - { + public String getDeobfName() { return m_deobfName; } - public void setDeobfName( String val ) - { - m_deobfName = NameValidator.validateClassName( val, false ); + + public void setDeobfName(String val) { + m_deobfName = NameValidator.validateClassName(val, false); } //// INNER CLASSES //////// - public Iterable innerClasses( ) - { - assert( m_innerClassesByObf.size() >= m_innerClassesByDeobf.size() ); + public Iterable innerClasses() { + assert (m_innerClassesByObf.size() >= m_innerClassesByDeobf.size()); return m_innerClassesByObf.values(); } - public void addInnerClassMapping( ClassMapping classMapping ) - { - assert( isSimpleClassName( classMapping.getObfName() ) ); - boolean obfWasAdded = m_innerClassesByObf.put( classMapping.getObfName(), classMapping ) == null; - assert( obfWasAdded ); - if( classMapping.getDeobfName() != null ) - { - assert( isSimpleClassName( classMapping.getDeobfName() ) ); - boolean deobfWasAdded = m_innerClassesByDeobf.put( classMapping.getDeobfName(), classMapping ) == null; - assert( deobfWasAdded ); + public void addInnerClassMapping(ClassMapping classMapping) { + assert (isSimpleClassName(classMapping.getObfName())); + boolean obfWasAdded = m_innerClassesByObf.put(classMapping.getObfName(), classMapping) == null; + assert (obfWasAdded); + if (classMapping.getDeobfName() != null) { + assert (isSimpleClassName(classMapping.getDeobfName())); + boolean deobfWasAdded = m_innerClassesByDeobf.put(classMapping.getDeobfName(), classMapping) == null; + assert (deobfWasAdded); } } - public void removeInnerClassMapping( ClassMapping classMapping ) - { - boolean obfWasRemoved = m_innerClassesByObf.remove( classMapping.getObfName() ) != null; - assert( obfWasRemoved ); - if( classMapping.getDeobfName() != null ) - { - boolean deobfWasRemoved = m_innerClassesByDeobf.remove( classMapping.getDeobfName() ) != null; - assert( deobfWasRemoved ); + public void removeInnerClassMapping(ClassMapping classMapping) { + boolean obfWasRemoved = m_innerClassesByObf.remove(classMapping.getObfName()) != null; + assert (obfWasRemoved); + if (classMapping.getDeobfName() != null) { + boolean deobfWasRemoved = m_innerClassesByDeobf.remove(classMapping.getDeobfName()) != null; + assert (deobfWasRemoved); } } - public ClassMapping getOrCreateInnerClass( String obfName ) - { - assert( isSimpleClassName( obfName ) ); - ClassMapping classMapping = m_innerClassesByObf.get( obfName ); - if( classMapping == null ) - { - classMapping = new ClassMapping( obfName ); - boolean wasAdded = m_innerClassesByObf.put( obfName, classMapping ) == null; - assert( wasAdded ); + public ClassMapping getOrCreateInnerClass(String obfName) { + assert (isSimpleClassName(obfName)); + ClassMapping classMapping = m_innerClassesByObf.get(obfName); + if (classMapping == null) { + classMapping = new ClassMapping(obfName); + boolean wasAdded = m_innerClassesByObf.put(obfName, classMapping) == null; + assert (wasAdded); } return classMapping; } - public ClassMapping getInnerClassByObf( String obfName ) - { - assert( isSimpleClassName( obfName ) ); - return m_innerClassesByObf.get( obfName ); + public ClassMapping getInnerClassByObf(String obfName) { + assert (isSimpleClassName(obfName)); + return m_innerClassesByObf.get(obfName); } - public ClassMapping getInnerClassByDeobf( String deobfName ) - { - assert( isSimpleClassName( deobfName ) ); - return m_innerClassesByDeobf.get( deobfName ); + public ClassMapping getInnerClassByDeobf(String deobfName) { + assert (isSimpleClassName(deobfName)); + return m_innerClassesByDeobf.get(deobfName); } - public ClassMapping getInnerClassByDeobfThenObf( String name ) - { - ClassMapping classMapping = getInnerClassByDeobf( name ); - if( classMapping == null ) - { - classMapping = getInnerClassByObf( name ); + public ClassMapping getInnerClassByDeobfThenObf(String name) { + ClassMapping classMapping = getInnerClassByDeobf(name); + if (classMapping == null) { + classMapping = getInnerClassByObf(name); } return classMapping; } - public String getObfInnerClassName( String deobfName ) - { - assert( isSimpleClassName( deobfName ) ); - ClassMapping classMapping = m_innerClassesByDeobf.get( deobfName ); - if( classMapping != null ) - { + public String getObfInnerClassName(String deobfName) { + assert (isSimpleClassName(deobfName)); + ClassMapping classMapping = m_innerClassesByDeobf.get(deobfName); + if (classMapping != null) { return classMapping.getObfName(); } return null; } - public String getDeobfInnerClassName( String obfName ) - { - assert( isSimpleClassName( obfName ) ); - ClassMapping classMapping = m_innerClassesByObf.get( obfName ); - if( classMapping != null ) - { + public String getDeobfInnerClassName(String obfName) { + assert (isSimpleClassName(obfName)); + ClassMapping classMapping = m_innerClassesByObf.get(obfName); + if (classMapping != null) { return classMapping.getDeobfName(); } return null; } - public void setInnerClassName( String obfName, String deobfName ) - { - assert( isSimpleClassName( obfName ) ); - ClassMapping classMapping = getOrCreateInnerClass( obfName ); - if( classMapping.getDeobfName() != null ) - { - boolean wasRemoved = m_innerClassesByDeobf.remove( classMapping.getDeobfName() ) != null; - assert( wasRemoved ); + public void setInnerClassName(String obfName, String deobfName) { + assert (isSimpleClassName(obfName)); + ClassMapping classMapping = getOrCreateInnerClass(obfName); + if (classMapping.getDeobfName() != null) { + boolean wasRemoved = m_innerClassesByDeobf.remove(classMapping.getDeobfName()) != null; + assert (wasRemoved); } - classMapping.setDeobfName( deobfName ); - if( deobfName != null ) - { - assert( isSimpleClassName( deobfName ) ); - boolean wasAdded = m_innerClassesByDeobf.put( deobfName, classMapping ) == null; - assert( wasAdded ); + classMapping.setDeobfName(deobfName); + if (deobfName != null) { + assert (isSimpleClassName(deobfName)); + boolean wasAdded = m_innerClassesByDeobf.put(deobfName, classMapping) == null; + assert (wasAdded); } } //// FIELDS //////// - public Iterable fields( ) - { - assert( m_fieldsByObf.size() == m_fieldsByDeobf.size() ); + public Iterable fields() { + assert (m_fieldsByObf.size() == m_fieldsByDeobf.size()); return m_fieldsByObf.values(); } - public boolean containsObfField( String obfName ) - { - return m_fieldsByObf.containsKey( obfName ); + public boolean containsObfField(String obfName) { + return m_fieldsByObf.containsKey(obfName); } - public boolean containsDeobfField( String deobfName ) - { - return m_fieldsByDeobf.containsKey( deobfName ); + public boolean containsDeobfField(String deobfName) { + return m_fieldsByDeobf.containsKey(deobfName); } - public void addFieldMapping( FieldMapping fieldMapping ) - { - if( m_fieldsByObf.containsKey( fieldMapping.getObfName() ) ) - { - throw new Error( "Already have mapping for " + m_obfName + "." + fieldMapping.getObfName() ); + public void addFieldMapping(FieldMapping fieldMapping) { + if (m_fieldsByObf.containsKey(fieldMapping.getObfName())) { + throw new Error("Already have mapping for " + m_obfName + "." + fieldMapping.getObfName()); } - if( m_fieldsByDeobf.containsKey( fieldMapping.getDeobfName() ) ) - { - throw new Error( "Already have mapping for " + m_deobfName + "." + fieldMapping.getDeobfName() ); + if (m_fieldsByDeobf.containsKey(fieldMapping.getDeobfName())) { + throw new Error("Already have mapping for " + m_deobfName + "." + fieldMapping.getDeobfName()); } - boolean obfWasAdded = m_fieldsByObf.put( fieldMapping.getObfName(), fieldMapping ) == null; - assert( obfWasAdded ); - boolean deobfWasAdded = m_fieldsByDeobf.put( fieldMapping.getDeobfName(), fieldMapping ) == null; - assert( deobfWasAdded ); - assert( m_fieldsByObf.size() == m_fieldsByDeobf.size() ); - } - - public void removeFieldMapping( FieldMapping fieldMapping ) - { - boolean obfWasRemoved = m_fieldsByObf.remove( fieldMapping.getObfName() ) != null; - assert( obfWasRemoved ); - if( fieldMapping.getDeobfName() != null ) - { - boolean deobfWasRemoved = m_fieldsByDeobf.remove( fieldMapping.getDeobfName() ) != null; - assert( deobfWasRemoved ); + boolean obfWasAdded = m_fieldsByObf.put(fieldMapping.getObfName(), fieldMapping) == null; + assert (obfWasAdded); + boolean deobfWasAdded = m_fieldsByDeobf.put(fieldMapping.getDeobfName(), fieldMapping) == null; + assert (deobfWasAdded); + assert (m_fieldsByObf.size() == m_fieldsByDeobf.size()); + } + + public void removeFieldMapping(FieldMapping fieldMapping) { + boolean obfWasRemoved = m_fieldsByObf.remove(fieldMapping.getObfName()) != null; + assert (obfWasRemoved); + if (fieldMapping.getDeobfName() != null) { + boolean deobfWasRemoved = m_fieldsByDeobf.remove(fieldMapping.getDeobfName()) != null; + assert (deobfWasRemoved); } } - public FieldMapping getFieldByObf( String obfName ) - { - return m_fieldsByObf.get( obfName ); + public FieldMapping getFieldByObf(String obfName) { + return m_fieldsByObf.get(obfName); } - public FieldMapping getFieldByDeobf( String deobfName ) - { - return m_fieldsByDeobf.get( deobfName ); + public FieldMapping getFieldByDeobf(String deobfName) { + return m_fieldsByDeobf.get(deobfName); } - - public String getObfFieldName( String deobfName ) - { - FieldMapping fieldMapping = m_fieldsByDeobf.get( deobfName ); - if( fieldMapping != null ) - { + + public String getObfFieldName(String deobfName) { + FieldMapping fieldMapping = m_fieldsByDeobf.get(deobfName); + if (fieldMapping != null) { return fieldMapping.getObfName(); } return null; } - public String getDeobfFieldName( String obfName ) - { - FieldMapping fieldMapping = m_fieldsByObf.get( obfName ); - if( fieldMapping != null ) - { + public String getDeobfFieldName(String obfName) { + FieldMapping fieldMapping = m_fieldsByObf.get(obfName); + if (fieldMapping != null) { return fieldMapping.getDeobfName(); } return null; } - public void setFieldName( String obfName, String deobfName ) - { - FieldMapping fieldMapping = m_fieldsByObf.get( obfName ); - if( fieldMapping == null ) - { - fieldMapping = new FieldMapping( obfName, deobfName ); - boolean obfWasAdded = m_fieldsByObf.put( obfName, fieldMapping ) == null; - assert( obfWasAdded ); + public void setFieldName(String obfName, String deobfName) { + FieldMapping fieldMapping = m_fieldsByObf.get(obfName); + if (fieldMapping == null) { + fieldMapping = new FieldMapping(obfName, deobfName); + boolean obfWasAdded = m_fieldsByObf.put(obfName, fieldMapping) == null; + assert (obfWasAdded); + } else { + boolean wasRemoved = m_fieldsByDeobf.remove(fieldMapping.getDeobfName()) != null; + assert (wasRemoved); } - else - { - boolean wasRemoved = m_fieldsByDeobf.remove( fieldMapping.getDeobfName() ) != null; - assert( wasRemoved ); - } - fieldMapping.setDeobfName( deobfName ); - if( deobfName != null ) - { - boolean wasAdded = m_fieldsByDeobf.put( deobfName, fieldMapping ) == null; - assert( wasAdded ); + fieldMapping.setDeobfName(deobfName); + if (deobfName != null) { + boolean wasAdded = m_fieldsByDeobf.put(deobfName, fieldMapping) == null; + assert (wasAdded); } } //// METHODS //////// - public Iterable methods( ) - { - assert( m_methodsByObf.size() >= m_methodsByDeobf.size() ); + public Iterable methods() { + assert (m_methodsByObf.size() >= m_methodsByDeobf.size()); return m_methodsByObf.values(); } - public boolean containsObfMethod( String obfName, String obfSignature ) - { - return m_methodsByObf.containsKey( getMethodKey( obfName, obfSignature ) ); + public boolean containsObfMethod(String obfName, String obfSignature) { + return m_methodsByObf.containsKey(getMethodKey(obfName, obfSignature)); } - public boolean containsDeobfMethod( String deobfName, String deobfSignature ) - { - return m_methodsByDeobf.containsKey( getMethodKey( deobfName, deobfSignature ) ); + public boolean containsDeobfMethod(String deobfName, String deobfSignature) { + return m_methodsByDeobf.containsKey(getMethodKey(deobfName, deobfSignature)); } - public void addMethodMapping( MethodMapping methodMapping ) - { - String obfKey = getMethodKey( methodMapping.getObfName(), methodMapping.getObfSignature() ); - if( m_methodsByObf.containsKey( obfKey ) ) - { - throw new Error( "Already have mapping for " + m_obfName + "." + obfKey ); + public void addMethodMapping(MethodMapping methodMapping) { + String obfKey = getMethodKey(methodMapping.getObfName(), methodMapping.getObfSignature()); + if (m_methodsByObf.containsKey(obfKey)) { + throw new Error("Already have mapping for " + m_obfName + "." + obfKey); } - boolean wasAdded = m_methodsByObf.put( obfKey, methodMapping ) == null; - assert( wasAdded ); - if( methodMapping.getDeobfName() != null ) - { - String deobfKey = getMethodKey( methodMapping.getDeobfName(), methodMapping.getObfSignature() ); - if( m_methodsByDeobf.containsKey( deobfKey ) ) - { - throw new Error( "Already have mapping for " + m_deobfName + "." + deobfKey ); + boolean wasAdded = m_methodsByObf.put(obfKey, methodMapping) == null; + assert (wasAdded); + if (methodMapping.getDeobfName() != null) { + String deobfKey = getMethodKey(methodMapping.getDeobfName(), methodMapping.getObfSignature()); + if (m_methodsByDeobf.containsKey(deobfKey)) { + throw new Error("Already have mapping for " + m_deobfName + "." + deobfKey); } - boolean deobfWasAdded = m_methodsByDeobf.put( deobfKey, methodMapping ) == null; - assert( deobfWasAdded ); + boolean deobfWasAdded = m_methodsByDeobf.put(deobfKey, methodMapping) == null; + assert (deobfWasAdded); } - assert( m_methodsByObf.size() >= m_methodsByDeobf.size() ); + assert (m_methodsByObf.size() >= m_methodsByDeobf.size()); } - public void removeMethodMapping( MethodMapping methodMapping ) - { - boolean obfWasRemoved = m_methodsByObf.remove( getMethodKey( methodMapping.getObfName(), methodMapping.getObfSignature() ) ) != null; - assert( obfWasRemoved ); - if( methodMapping.getDeobfName() != null ) - { - boolean deobfWasRemoved = m_methodsByDeobf.remove( getMethodKey( methodMapping.getDeobfName(), methodMapping.getObfSignature() ) ) != null; - assert( deobfWasRemoved ); + public void removeMethodMapping(MethodMapping methodMapping) { + boolean obfWasRemoved = m_methodsByObf.remove(getMethodKey(methodMapping.getObfName(), methodMapping.getObfSignature())) != null; + assert (obfWasRemoved); + if (methodMapping.getDeobfName() != null) { + boolean deobfWasRemoved = m_methodsByDeobf.remove(getMethodKey(methodMapping.getDeobfName(), methodMapping.getObfSignature())) != null; + assert (deobfWasRemoved); } } - public MethodMapping getMethodByObf( String obfName, String signature ) - { - return m_methodsByObf.get( getMethodKey( obfName, signature ) ); + public MethodMapping getMethodByObf(String obfName, String signature) { + return m_methodsByObf.get(getMethodKey(obfName, signature)); } - public MethodMapping getMethodByDeobf( String deobfName, String signature ) - { - return m_methodsByDeobf.get( getMethodKey( deobfName, signature ) ); + public MethodMapping getMethodByDeobf(String deobfName, String signature) { + return m_methodsByDeobf.get(getMethodKey(deobfName, signature)); } - private String getMethodKey( String name, String signature ) - { - if( name == null ) - { - throw new IllegalArgumentException( "name cannot be null!" ); + private String getMethodKey(String name, String signature) { + if (name == null) { + throw new IllegalArgumentException("name cannot be null!"); } - if( signature == null ) - { - throw new IllegalArgumentException( "signature cannot be null!" ); + if (signature == null) { + throw new IllegalArgumentException("signature cannot be null!"); } return name + signature; } - public void setMethodName( String obfName, String obfSignature, String deobfName ) - { - MethodMapping methodMapping = m_methodsByObf.get( getMethodKey( obfName, obfSignature ) ); - if( methodMapping == null ) - { - methodMapping = createMethodMapping( obfName, obfSignature ); - } - else if( methodMapping.getDeobfName() != null ) - { - boolean wasRemoved = m_methodsByDeobf.remove( getMethodKey( methodMapping.getDeobfName(), methodMapping.getObfSignature() ) ) != null; - assert( wasRemoved ); + public void setMethodName(String obfName, String obfSignature, String deobfName) { + MethodMapping methodMapping = m_methodsByObf.get(getMethodKey(obfName, obfSignature)); + if (methodMapping == null) { + methodMapping = createMethodMapping(obfName, obfSignature); + } else if (methodMapping.getDeobfName() != null) { + boolean wasRemoved = m_methodsByDeobf.remove(getMethodKey(methodMapping.getDeobfName(), methodMapping.getObfSignature())) != null; + assert (wasRemoved); } - methodMapping.setDeobfName( deobfName ); - if( deobfName != null ) - { - boolean wasAdded = m_methodsByDeobf.put( getMethodKey( deobfName, obfSignature ), methodMapping ) == null; - assert( wasAdded ); + methodMapping.setDeobfName(deobfName); + if (deobfName != null) { + boolean wasAdded = m_methodsByDeobf.put(getMethodKey(deobfName, obfSignature), methodMapping) == null; + assert (wasAdded); } } //// ARGUMENTS //////// - public void setArgumentName( String obfMethodName, String obfMethodSignature, int argumentIndex, String argumentName ) - { - MethodMapping methodMapping = m_methodsByObf.get( getMethodKey( obfMethodName, obfMethodSignature ) ); - if( methodMapping == null ) - { - methodMapping = createMethodMapping( obfMethodName, obfMethodSignature ); + public void setArgumentName(String obfMethodName, String obfMethodSignature, int argumentIndex, String argumentName) { + MethodMapping methodMapping = m_methodsByObf.get(getMethodKey(obfMethodName, obfMethodSignature)); + if (methodMapping == null) { + methodMapping = createMethodMapping(obfMethodName, obfMethodSignature); } - methodMapping.setArgumentName( argumentIndex, argumentName ); + methodMapping.setArgumentName(argumentIndex, argumentName); } - public void removeArgumentName( String obfMethodName, String obfMethodSignature, int argumentIndex ) - { - m_methodsByObf.get( getMethodKey( obfMethodName, obfMethodSignature ) ).removeArgumentName( argumentIndex ); + public void removeArgumentName(String obfMethodName, String obfMethodSignature, int argumentIndex) { + m_methodsByObf.get(getMethodKey(obfMethodName, obfMethodSignature)).removeArgumentName(argumentIndex); } - - private MethodMapping createMethodMapping( String obfName, String obfSignature ) - { - MethodMapping methodMapping = new MethodMapping( obfName, obfSignature ); - boolean wasAdded = m_methodsByObf.put( getMethodKey( obfName, obfSignature ), methodMapping ) == null; - assert( wasAdded ); + + private MethodMapping createMethodMapping(String obfName, String obfSignature) { + MethodMapping methodMapping = new MethodMapping(obfName, obfSignature); + boolean wasAdded = m_methodsByObf.put(getMethodKey(obfName, obfSignature), methodMapping) == null; + assert (wasAdded); return methodMapping; } - + @Override - public String toString( ) - { + public String toString() { StringBuilder buf = new StringBuilder(); - buf.append( m_obfName ); - buf.append( " <-> " ); - buf.append( m_deobfName ); - buf.append( "\n" ); - buf.append( "Fields:\n" ); - for( FieldMapping fieldMapping : fields() ) - { - buf.append( "\t" ); - buf.append( fieldMapping.getObfName() ); - buf.append( " <-> " ); - buf.append( fieldMapping.getDeobfName() ); - buf.append( "\n" ); - } - buf.append( "Methods:\n" ); - for( MethodMapping methodMapping : m_methodsByObf.values() ) - { - buf.append( methodMapping.toString() ); - buf.append( "\n" ); - } - buf.append( "Inner Classes:\n" ); - for( ClassMapping classMapping : m_innerClassesByObf.values() ) - { - buf.append( "\t" ); - buf.append( classMapping.getObfName() ); - buf.append( " <-> " ); - buf.append( classMapping.getDeobfName() ); - buf.append( "\n" ); + buf.append(m_obfName); + buf.append(" <-> "); + buf.append(m_deobfName); + buf.append("\n"); + buf.append("Fields:\n"); + for (FieldMapping fieldMapping : fields()) { + buf.append("\t"); + buf.append(fieldMapping.getObfName()); + buf.append(" <-> "); + buf.append(fieldMapping.getDeobfName()); + buf.append("\n"); + } + buf.append("Methods:\n"); + for (MethodMapping methodMapping : m_methodsByObf.values()) { + buf.append(methodMapping.toString()); + buf.append("\n"); + } + buf.append("Inner Classes:\n"); + for (ClassMapping classMapping : m_innerClassesByObf.values()) { + buf.append("\t"); + buf.append(classMapping.getObfName()); + buf.append(" <-> "); + buf.append(classMapping.getDeobfName()); + buf.append("\n"); } return buf.toString(); } @Override - public int compareTo( ClassMapping other ) - { + public int compareTo(ClassMapping other) { // sort by a, b, c, ... aa, ab, etc - if( m_obfName.length() != other.m_obfName.length() ) - { + if (m_obfName.length() != other.m_obfName.length()) { return m_obfName.length() - other.m_obfName.length(); } - return m_obfName.compareTo( other.m_obfName ); + return m_obfName.compareTo(other.m_obfName); } - public boolean renameObfClass( String oldObfClassName, String newObfClassName ) - { + public boolean renameObfClass(String oldObfClassName, String newObfClassName) { + // rename inner classes - for( ClassMapping innerClassMapping : new ArrayList( m_innerClassesByObf.values() ) ) - { - if( innerClassMapping.renameObfClass( oldObfClassName, newObfClassName ) ) - { - boolean wasRemoved = m_innerClassesByObf.remove( oldObfClassName ) != null; - assert( wasRemoved ); - boolean wasAdded = m_innerClassesByObf.put( newObfClassName, innerClassMapping ) == null; - assert( wasAdded ); + for (ClassMapping innerClassMapping : new ArrayList(m_innerClassesByObf.values())) { + if (innerClassMapping.renameObfClass(oldObfClassName, newObfClassName)) { + boolean wasRemoved = m_innerClassesByObf.remove(oldObfClassName) != null; + assert (wasRemoved); + boolean wasAdded = m_innerClassesByObf.put(newObfClassName, innerClassMapping) == null; + assert (wasAdded); } } // rename method signatures - for( MethodMapping methodMapping : new ArrayList( m_methodsByObf.values() ) ) - { - String oldMethodKey = getMethodKey( methodMapping.getObfName(), methodMapping.getObfSignature() ); - if( methodMapping.renameObfClass( oldObfClassName, newObfClassName ) ) - { - boolean wasRemoved = m_methodsByObf.remove( oldMethodKey ) != null; - assert( wasRemoved ); - boolean wasAdded = m_methodsByObf.put( getMethodKey( methodMapping.getObfName(), methodMapping.getObfSignature() ), methodMapping ) == null; - assert( wasAdded ); + for (MethodMapping methodMapping : new ArrayList(m_methodsByObf.values())) { + String oldMethodKey = getMethodKey(methodMapping.getObfName(), methodMapping.getObfSignature()); + if (methodMapping.renameObfClass(oldObfClassName, newObfClassName)) { + boolean wasRemoved = m_methodsByObf.remove(oldMethodKey) != null; + assert (wasRemoved); + boolean wasAdded = m_methodsByObf.put(getMethodKey(methodMapping.getObfName(), methodMapping.getObfSignature()), methodMapping) == null; + assert (wasAdded); } } - if( m_obfName.equals( oldObfClassName ) ) - { + if (m_obfName.equals(oldObfClassName)) { // rename this class m_obfName = newObfClassName; return true; } return false; } - - public boolean containsArgument( BehaviorEntry obfBehaviorEntry, String name ) - { - MethodMapping methodMapping = m_methodsByObf.get( getMethodKey( obfBehaviorEntry.getName(), obfBehaviorEntry.getSignature() ) ); - if( methodMapping != null ) - { - return methodMapping.containsArgument( name ); + + public boolean containsArgument(BehaviorEntry obfBehaviorEntry, String name) { + MethodMapping methodMapping = m_methodsByObf.get(getMethodKey(obfBehaviorEntry.getName(), obfBehaviorEntry.getSignature())); + if (methodMapping != null) { + return methodMapping.containsArgument(name); } return false; } - public static boolean isSimpleClassName( String name ) - { - return name.indexOf( '/' ) < 0 && name.indexOf( '$' ) < 0; + public static boolean isSimpleClassName(String name) { + return name.indexOf('/') < 0 && name.indexOf('$') < 0; } } diff --git a/src/cuchaz/enigma/mapping/ConstructorEntry.java b/src/cuchaz/enigma/mapping/ConstructorEntry.java index d99d1c3..ea0535f 100644 --- a/src/cuchaz/enigma/mapping/ConstructorEntry.java +++ b/src/cuchaz/enigma/mapping/ConstructorEntry.java @@ -14,129 +14,102 @@ import java.io.Serializable; import cuchaz.enigma.Util; -public class ConstructorEntry implements BehaviorEntry, Serializable -{ +public class ConstructorEntry implements BehaviorEntry, Serializable { + private static final long serialVersionUID = -868346075317366758L; private ClassEntry m_classEntry; private String m_signature; - public ConstructorEntry( ClassEntry classEntry ) - { - this( classEntry, null ); + public ConstructorEntry(ClassEntry classEntry) { + this(classEntry, null); } - public ConstructorEntry( ClassEntry classEntry, String signature ) - { - if( classEntry == null ) - { - throw new IllegalArgumentException( "Class cannot be null!" ); + public ConstructorEntry(ClassEntry classEntry, String signature) { + if (classEntry == null) { + throw new IllegalArgumentException("Class cannot be null!"); } m_classEntry = classEntry; m_signature = signature; } - public ConstructorEntry( ConstructorEntry other ) - { - m_classEntry = new ClassEntry( other.m_classEntry ); + public ConstructorEntry(ConstructorEntry other) { + m_classEntry = new ClassEntry(other.m_classEntry); m_signature = other.m_signature; } - public ConstructorEntry( ConstructorEntry other, String newClassName ) - { - m_classEntry = new ClassEntry( newClassName ); + public ConstructorEntry(ConstructorEntry other, String newClassName) { + m_classEntry = new ClassEntry(newClassName); m_signature = other.m_signature; } @Override - public ClassEntry getClassEntry( ) - { + public ClassEntry getClassEntry() { return m_classEntry; } @Override - public String getName( ) - { - if( isStatic() ) - { + public String getName() { + if (isStatic()) { return ""; } return ""; } - public boolean isStatic( ) - { + public boolean isStatic() { return m_signature == null; } @Override - public String getSignature( ) - { + public String getSignature() { return m_signature; } @Override - public String getClassName( ) - { + public String getClassName() { return m_classEntry.getName(); } @Override - public ConstructorEntry cloneToNewClass( ClassEntry classEntry ) - { - return new ConstructorEntry( this, classEntry.getName() ); + public ConstructorEntry cloneToNewClass(ClassEntry classEntry) { + return new ConstructorEntry(this, classEntry.getName()); } @Override - public int hashCode( ) - { - if( isStatic() ) - { - return Util.combineHashesOrdered( m_classEntry ); - } - else - { - return Util.combineHashesOrdered( m_classEntry, m_signature ); + public int hashCode() { + if (isStatic()) { + return Util.combineHashesOrdered(m_classEntry); + } else { + return Util.combineHashesOrdered(m_classEntry, m_signature); } } @Override - public boolean equals( Object other ) - { - if( other instanceof ConstructorEntry ) - { - return equals( (ConstructorEntry)other ); + public boolean equals(Object other) { + if (other instanceof ConstructorEntry) { + return equals((ConstructorEntry)other); } return false; } - public boolean equals( ConstructorEntry other ) - { - if( isStatic() != other.isStatic() ) - { + public boolean equals(ConstructorEntry other) { + if (isStatic() != other.isStatic()) { return false; } - if( isStatic() ) - { - return m_classEntry.equals( other.m_classEntry ); - } - else - { - return m_classEntry.equals( other.m_classEntry ) && m_signature.equals( other.m_signature ); + if (isStatic()) { + return m_classEntry.equals(other.m_classEntry); + } else { + return m_classEntry.equals(other.m_classEntry) && m_signature.equals(other.m_signature); } } @Override - public String toString( ) - { - if( isStatic() ) - { + public String toString() { + if (isStatic()) { return m_classEntry.getName() + "." + getName(); - } - else - { + } else { return m_classEntry.getName() + "." + getName() + m_signature; } } diff --git a/src/cuchaz/enigma/mapping/Entry.java b/src/cuchaz/enigma/mapping/Entry.java index 8524834..39e1507 100644 --- a/src/cuchaz/enigma/mapping/Entry.java +++ b/src/cuchaz/enigma/mapping/Entry.java @@ -10,10 +10,9 @@ ******************************************************************************/ package cuchaz.enigma.mapping; -public interface Entry -{ - String getName( ); - String getClassName( ); - ClassEntry getClassEntry( ); - Entry cloneToNewClass( ClassEntry classEntry ); +public interface Entry { + String getName(); + String getClassName(); + ClassEntry getClassEntry(); + Entry cloneToNewClass(ClassEntry classEntry); } diff --git a/src/cuchaz/enigma/mapping/EntryPair.java b/src/cuchaz/enigma/mapping/EntryPair.java index f94d77e..60411c4 100644 --- a/src/cuchaz/enigma/mapping/EntryPair.java +++ b/src/cuchaz/enigma/mapping/EntryPair.java @@ -10,15 +10,12 @@ ******************************************************************************/ package cuchaz.enigma.mapping; - - -public class EntryPair -{ +public class EntryPair { + public T obf; public T deobf; - public EntryPair( T obf, T deobf ) - { + public EntryPair(T obf, T deobf) { this.obf = obf; this.deobf = deobf; } diff --git a/src/cuchaz/enigma/mapping/FieldEntry.java b/src/cuchaz/enigma/mapping/FieldEntry.java index 626af57..6cc9eb7 100644 --- a/src/cuchaz/enigma/mapping/FieldEntry.java +++ b/src/cuchaz/enigma/mapping/FieldEntry.java @@ -14,90 +14,75 @@ import java.io.Serializable; import cuchaz.enigma.Util; -public class FieldEntry implements Entry, Serializable -{ +public class FieldEntry implements Entry, Serializable { + private static final long serialVersionUID = 3004663582802885451L; private ClassEntry m_classEntry; private String m_name; // NOTE: this argument order is important for the MethodReader/MethodWriter - public FieldEntry( ClassEntry classEntry, String name ) - { - if( classEntry == null ) - { - throw new IllegalArgumentException( "Class cannot be null!" ); + public FieldEntry(ClassEntry classEntry, String name) { + if (classEntry == null) { + throw new IllegalArgumentException("Class cannot be null!"); } - if( name == null ) - { - throw new IllegalArgumentException( "Field name cannot be null!" ); + if (name == null) { + throw new IllegalArgumentException("Field name cannot be null!"); } m_classEntry = classEntry; m_name = name; } - public FieldEntry( FieldEntry other ) - { - m_classEntry = new ClassEntry( other.m_classEntry ); + public FieldEntry(FieldEntry other) { + m_classEntry = new ClassEntry(other.m_classEntry); m_name = other.m_name; } - - public FieldEntry( FieldEntry other, String newClassName ) - { - m_classEntry = new ClassEntry( newClassName ); + + public FieldEntry(FieldEntry other, String newClassName) { + m_classEntry = new ClassEntry(newClassName); m_name = other.m_name; } @Override - public ClassEntry getClassEntry( ) - { + public ClassEntry getClassEntry() { return m_classEntry; } @Override - public String getName( ) - { + public String getName() { return m_name; } @Override - public String getClassName( ) - { + public String getClassName() { return m_classEntry.getName(); } @Override - public FieldEntry cloneToNewClass( ClassEntry classEntry ) - { - return new FieldEntry( this, classEntry.getName() ); + public FieldEntry cloneToNewClass(ClassEntry classEntry) { + return new FieldEntry(this, classEntry.getName()); } @Override - public int hashCode( ) - { - return Util.combineHashesOrdered( m_classEntry, m_name ); + public int hashCode() { + return Util.combineHashesOrdered(m_classEntry, m_name); } @Override - public boolean equals( Object other ) - { - if( other instanceof FieldEntry ) - { - return equals( (FieldEntry)other ); + public boolean equals(Object other) { + if (other instanceof FieldEntry) { + return equals((FieldEntry)other); } return false; } - public boolean equals( FieldEntry other ) - { - return m_classEntry.equals( other.m_classEntry ) - && m_name.equals( other.m_name ); + public boolean equals(FieldEntry other) { + return m_classEntry.equals(other.m_classEntry) && m_name.equals(other.m_name); } @Override - public String toString( ) - { + public String toString() { return m_classEntry.getName() + "." + m_name; } } diff --git a/src/cuchaz/enigma/mapping/FieldMapping.java b/src/cuchaz/enigma/mapping/FieldMapping.java index ae0855a..5f5c270 100644 --- a/src/cuchaz/enigma/mapping/FieldMapping.java +++ b/src/cuchaz/enigma/mapping/FieldMapping.java @@ -12,36 +12,32 @@ package cuchaz.enigma.mapping; import java.io.Serializable; -public class FieldMapping implements Serializable, Comparable -{ +public class FieldMapping implements Serializable, Comparable { + private static final long serialVersionUID = 8610742471440861315L; private String m_obfName; private String m_deobfName; - public FieldMapping( String obfName, String deobfName ) - { + public FieldMapping(String obfName, String deobfName) { m_obfName = obfName; - m_deobfName = NameValidator.validateFieldName( deobfName ); + m_deobfName = NameValidator.validateFieldName(deobfName); } - - public String getObfName( ) - { + + public String getObfName() { return m_obfName; } - - public String getDeobfName( ) - { + + public String getDeobfName() { return m_deobfName; } - public void setDeobfName( String val ) - { - m_deobfName = NameValidator.validateFieldName( val ); + + public void setDeobfName(String val) { + m_deobfName = NameValidator.validateFieldName(val); } @Override - public int compareTo( FieldMapping other ) - { - return m_obfName.compareTo( other.m_obfName ); + public int compareTo(FieldMapping other) { + return m_obfName.compareTo(other.m_obfName); } } diff --git a/src/cuchaz/enigma/mapping/IllegalNameException.java b/src/cuchaz/enigma/mapping/IllegalNameException.java index 830f05c..aacaf3b 100644 --- a/src/cuchaz/enigma/mapping/IllegalNameException.java +++ b/src/cuchaz/enigma/mapping/IllegalNameException.java @@ -10,39 +10,34 @@ ******************************************************************************/ package cuchaz.enigma.mapping; -public class IllegalNameException extends RuntimeException -{ +public class IllegalNameException extends RuntimeException { + private static final long serialVersionUID = -2279910052561114323L; private String m_name; private String m_reason; - public IllegalNameException( String name ) - { - this( name, null ); + public IllegalNameException(String name) { + this(name, null); } - public IllegalNameException( String name, String reason ) - { + public IllegalNameException(String name, String reason) { m_name = name; m_reason = reason; } - public String getReason( ) - { + public String getReason() { return m_reason; } @Override - public String getMessage( ) - { + public String getMessage() { StringBuilder buf = new StringBuilder(); - buf.append( "Illegal name: " ); - buf.append( m_name ); - if( m_reason != null ) - { - buf.append( " because " ); - buf.append( m_reason ); + buf.append("Illegal name: "); + buf.append(m_name); + if (m_reason != null) { + buf.append(" because "); + buf.append(m_reason); } return buf.toString(); } diff --git a/src/cuchaz/enigma/mapping/MappingParseException.java b/src/cuchaz/enigma/mapping/MappingParseException.java index 4fcc1f1..1974c22 100644 --- a/src/cuchaz/enigma/mapping/MappingParseException.java +++ b/src/cuchaz/enigma/mapping/MappingParseException.java @@ -10,22 +10,20 @@ ******************************************************************************/ package cuchaz.enigma.mapping; -public class MappingParseException extends Exception -{ +public class MappingParseException extends Exception { + private static final long serialVersionUID = -5487280332892507236L; private int m_line; private String m_message; - public MappingParseException( int line, String message ) - { + public MappingParseException(int line, String message) { m_line = line; m_message = message; } @Override - public String getMessage( ) - { + public String getMessage() { return "Line " + m_line + ": " + m_message; } } diff --git a/src/cuchaz/enigma/mapping/Mappings.java b/src/cuchaz/enigma/mapping/Mappings.java index 3a39d10..c5e38f4 100644 --- a/src/cuchaz/enigma/mapping/Mappings.java +++ b/src/cuchaz/enigma/mapping/Mappings.java @@ -26,230 +26,182 @@ import com.google.common.collect.Sets; import cuchaz.enigma.Util; import cuchaz.enigma.mapping.SignatureUpdater.ClassNameUpdater; -public class Mappings implements Serializable -{ +public class Mappings implements Serializable { + private static final long serialVersionUID = 4649790259460259026L; protected Map m_classesByObf; protected Map m_classesByDeobf; - public Mappings( ) - { + public Mappings() { m_classesByObf = Maps.newHashMap(); m_classesByDeobf = Maps.newHashMap(); } - public Mappings( Iterable classes ) - { + public Mappings(Iterable classes) { this(); - for( ClassMapping classMapping : classes ) - { - m_classesByObf.put( classMapping.getObfName(), classMapping ); - if( classMapping.getDeobfName() != null ) - { - m_classesByDeobf.put( classMapping.getDeobfName(), classMapping ); + for (ClassMapping classMapping : classes) { + m_classesByObf.put(classMapping.getObfName(), classMapping); + if (classMapping.getDeobfName() != null) { + m_classesByDeobf.put(classMapping.getDeobfName(), classMapping); } } } - public static Mappings newFromResource( String resource ) - throws IOException - { + public static Mappings newFromResource(String resource) throws IOException { InputStream in = null; - try - { - in = Mappings.class.getResourceAsStream( resource ); - return newFromStream( in ); - } - finally - { - Util.closeQuietly( in ); + try { + in = Mappings.class.getResourceAsStream(resource); + return newFromStream(in); + } finally { + Util.closeQuietly(in); } } - public Collection classes( ) - { - assert( m_classesByObf.size() >= m_classesByDeobf.size() ); + public Collection classes() { + assert (m_classesByObf.size() >= m_classesByDeobf.size()); return m_classesByObf.values(); } - public void addClassMapping( ClassMapping classMapping ) - { - if( m_classesByObf.containsKey( classMapping.getObfName() ) ) - { - throw new Error( "Already have mapping for " + classMapping.getObfName() ); + public void addClassMapping(ClassMapping classMapping) { + if (m_classesByObf.containsKey(classMapping.getObfName())) { + throw new Error("Already have mapping for " + classMapping.getObfName()); } - boolean obfWasAdded = m_classesByObf.put( classMapping.getObfName(), classMapping ) == null; - assert( obfWasAdded ); - if( classMapping.getDeobfName() != null ) - { - if( m_classesByDeobf.containsKey( classMapping.getDeobfName() ) ) - { - throw new Error( "Already have mapping for " + classMapping.getDeobfName() ); + boolean obfWasAdded = m_classesByObf.put(classMapping.getObfName(), classMapping) == null; + assert (obfWasAdded); + if (classMapping.getDeobfName() != null) { + if (m_classesByDeobf.containsKey(classMapping.getDeobfName())) { + throw new Error("Already have mapping for " + classMapping.getDeobfName()); } - boolean deobfWasAdded = m_classesByDeobf.put( classMapping.getDeobfName(), classMapping ) == null; - assert( deobfWasAdded ); + boolean deobfWasAdded = m_classesByDeobf.put(classMapping.getDeobfName(), classMapping) == null; + assert (deobfWasAdded); } } - public void removeClassMapping( ClassMapping classMapping ) - { - boolean obfWasRemoved = m_classesByObf.remove( classMapping.getObfName() ) != null; - assert( obfWasRemoved ); - if( classMapping.getDeobfName() != null ) - { - boolean deobfWasRemoved = m_classesByDeobf.remove( classMapping.getDeobfName() ) != null; - assert( deobfWasRemoved ); + public void removeClassMapping(ClassMapping classMapping) { + boolean obfWasRemoved = m_classesByObf.remove(classMapping.getObfName()) != null; + assert (obfWasRemoved); + if (classMapping.getDeobfName() != null) { + boolean deobfWasRemoved = m_classesByDeobf.remove(classMapping.getDeobfName()) != null; + assert (deobfWasRemoved); } } - public ClassMapping getClassByObf( ClassEntry entry ) - { - return getClassByObf( entry.getName() ); + public ClassMapping getClassByObf(ClassEntry entry) { + return getClassByObf(entry.getName()); } - public ClassMapping getClassByObf( String obfName ) - { - return m_classesByObf.get( obfName ); + public ClassMapping getClassByObf(String obfName) { + return m_classesByObf.get(obfName); } - public ClassMapping getClassByDeobf( ClassEntry entry ) - { - return getClassByDeobf( entry.getName() ); + public ClassMapping getClassByDeobf(ClassEntry entry) { + return getClassByDeobf(entry.getName()); } - public ClassMapping getClassByDeobf( String deobfName ) - { - return m_classesByDeobf.get( deobfName ); + public ClassMapping getClassByDeobf(String deobfName) { + return m_classesByDeobf.get(deobfName); } - public Translator getTranslator( TranslationDirection direction ) - { - switch( direction ) - { + public Translator getTranslator(TranslationDirection direction) { + switch (direction) { case Deobfuscating: - return new Translator( direction, m_classesByObf ); + return new Translator(direction, m_classesByObf); case Obfuscating: // fill in the missing deobf class entries with obf entries Map classes = Maps.newHashMap(); - for( ClassMapping classMapping : classes() ) - { - if( classMapping.getDeobfName() != null ) - { - classes.put( classMapping.getDeobfName(), classMapping ); - } - else - { - classes.put( classMapping.getObfName(), classMapping ); + for (ClassMapping classMapping : classes()) { + if (classMapping.getDeobfName() != null) { + classes.put(classMapping.getDeobfName(), classMapping); + } else { + classes.put(classMapping.getObfName(), classMapping); } } - return new Translator( direction, classes ); + return new Translator(direction, classes); default: - throw new Error( "Invalid translation direction!" ); + throw new Error("Invalid translation direction!"); } } - public static Mappings newFromStream( InputStream in ) - throws IOException - { - try - { - return (Mappings)new ObjectInputStream( new GZIPInputStream( in ) ).readObject(); - } - catch( ClassNotFoundException ex ) - { - throw new Error( ex ); + public static Mappings newFromStream(InputStream in) throws IOException { + try { + return (Mappings)new ObjectInputStream(new GZIPInputStream(in)).readObject(); + } catch (ClassNotFoundException ex) { + throw new Error(ex); } } @Override - public String toString( ) - { + public String toString() { StringBuilder buf = new StringBuilder(); - for( ClassMapping classMapping : m_classesByObf.values() ) - { - buf.append( classMapping.toString() ); - buf.append( "\n" ); + for (ClassMapping classMapping : m_classesByObf.values()) { + buf.append(classMapping.toString()); + buf.append("\n"); } return buf.toString(); } - public void renameObfClass( String oldObfName, String newObfName ) - { - for( ClassMapping classMapping : new ArrayList( classes() ) ) - { - if( classMapping.renameObfClass( oldObfName, newObfName ) ) - { - boolean wasRemoved = m_classesByObf.remove( oldObfName ) != null; - assert( wasRemoved ); - boolean wasAdded = m_classesByObf.put( newObfName, classMapping ) == null; - assert( wasAdded ); + public void renameObfClass(String oldObfName, String newObfName) { + for (ClassMapping classMapping : new ArrayList(classes())) { + if (classMapping.renameObfClass(oldObfName, newObfName)) { + boolean wasRemoved = m_classesByObf.remove(oldObfName) != null; + assert (wasRemoved); + boolean wasAdded = m_classesByObf.put(newObfName, classMapping) == null; + assert (wasAdded); } } } - public Set getAllObfClassNames( ) - { + public Set getAllObfClassNames() { final Set classNames = Sets.newHashSet(); - for( ClassMapping classMapping : classes() ) - { + for (ClassMapping classMapping : classes()) { // add the class name - classNames.add( classMapping.getObfName() ); + classNames.add(classMapping.getObfName()); // add classes from method signatures - for( MethodMapping methodMapping : classMapping.methods() ) - { - SignatureUpdater.update( methodMapping.getObfSignature(), new ClassNameUpdater( ) - { + for (MethodMapping methodMapping : classMapping.methods()) { + SignatureUpdater.update(methodMapping.getObfSignature(), new ClassNameUpdater() { @Override - public String update( String className ) - { - classNames.add( className ); + public String update(String className) { + classNames.add(className); return className; } - } ); + }); } } return classNames; } - - public boolean containsDeobfClass( String deobfName ) - { - return m_classesByDeobf.containsKey( deobfName ); + + public boolean containsDeobfClass(String deobfName) { + return m_classesByDeobf.containsKey(deobfName); } - public boolean containsDeobfField( ClassEntry obfClassEntry, String deobfName ) - { - ClassMapping classMapping = m_classesByObf.get( obfClassEntry.getName() ); - if( classMapping != null ) - { - return classMapping.containsDeobfField( deobfName ); + public boolean containsDeobfField(ClassEntry obfClassEntry, String deobfName) { + ClassMapping classMapping = m_classesByObf.get(obfClassEntry.getName()); + if (classMapping != null) { + return classMapping.containsDeobfField(deobfName); } return false; } - - public boolean containsDeobfMethod( ClassEntry obfClassEntry, String deobfName, String deobfSignature ) - { - ClassMapping classMapping = m_classesByObf.get( obfClassEntry.getName() ); - if( classMapping != null ) - { - return classMapping.containsDeobfMethod( deobfName, deobfSignature ); + + public boolean containsDeobfMethod(ClassEntry obfClassEntry, String deobfName, String deobfSignature) { + ClassMapping classMapping = m_classesByObf.get(obfClassEntry.getName()); + if (classMapping != null) { + return classMapping.containsDeobfMethod(deobfName, deobfSignature); } return false; } - - public boolean containsArgument( BehaviorEntry obfBehaviorEntry, String name ) - { - ClassMapping classMapping = m_classesByObf.get( obfBehaviorEntry.getClassName() ); - if( classMapping != null ) - { - return classMapping.containsArgument( obfBehaviorEntry, name ); + + public boolean containsArgument(BehaviorEntry obfBehaviorEntry, String name) { + ClassMapping classMapping = m_classesByObf.get(obfBehaviorEntry.getClassName()); + if (classMapping != null) { + return classMapping.containsArgument(obfBehaviorEntry, name); } return false; } diff --git a/src/cuchaz/enigma/mapping/MappingsReader.java b/src/cuchaz/enigma/mapping/MappingsReader.java index 4bd9f12..72e829d 100644 --- a/src/cuchaz/enigma/mapping/MappingsReader.java +++ b/src/cuchaz/enigma/mapping/MappingsReader.java @@ -20,209 +20,157 @@ import com.google.common.collect.Queues; import cuchaz.enigma.Constants; import cuchaz.enigma.mapping.SignatureUpdater.ClassNameUpdater; -public class MappingsReader -{ - public Mappings read( Reader in ) - throws IOException, MappingParseException - { - return read( new BufferedReader( in ) ); +public class MappingsReader { + + public Mappings read(Reader in) throws IOException, MappingParseException { + return read(new BufferedReader(in)); } - public Mappings read( BufferedReader in ) - throws IOException, MappingParseException - { + public Mappings read(BufferedReader in) throws IOException, MappingParseException { Mappings mappings = new Mappings(); Deque mappingStack = Queues.newArrayDeque(); int lineNumber = 0; String line = null; - while( ( line = in.readLine() ) != null ) - { + while ( (line = in.readLine()) != null) { lineNumber++; // strip comments - int commentPos = line.indexOf( '#' ); - if( commentPos >= 0 ) - { - line = line.substring( 0, commentPos ); + int commentPos = line.indexOf('#'); + if (commentPos >= 0) { + line = line.substring(0, commentPos); } // skip blank lines - if( line.trim().length() <= 0 ) - { + if (line.trim().length() <= 0) { continue; } // get the indent of this line int indent = 0; - for( int i=0; i implementations = m_index.getRelatedMethodImplementations( obf ); + public void setMethodTreeName(MethodEntry obf, String deobfName) { + Set implementations = m_index.getRelatedMethodImplementations(obf); - deobfName = NameValidator.validateMethodName( deobfName ); - for( MethodEntry entry : implementations ) - { - String deobfSignature = m_mappings.getTranslator( TranslationDirection.Deobfuscating ).translateSignature( obf.getSignature() ); - MethodEntry targetEntry = new MethodEntry( entry.getClassEntry(), deobfName, deobfSignature ); - if( m_mappings.containsDeobfMethod( entry.getClassEntry(), deobfName, entry.getSignature() ) || m_index.containsObfBehavior( targetEntry ) ) - { - String deobfClassName = m_mappings.getTranslator( TranslationDirection.Deobfuscating ).translateClass( entry.getClassName() ); - throw new IllegalNameException( deobfName, "There is already a method with that name and signature in class " + deobfClassName ); + deobfName = NameValidator.validateMethodName(deobfName); + for (MethodEntry entry : implementations) { + String deobfSignature = m_mappings.getTranslator(TranslationDirection.Deobfuscating).translateSignature(obf.getSignature()); + MethodEntry targetEntry = new MethodEntry(entry.getClassEntry(), deobfName, deobfSignature); + if (m_mappings.containsDeobfMethod(entry.getClassEntry(), deobfName, entry.getSignature()) || m_index.containsObfBehavior(targetEntry)) { + String deobfClassName = m_mappings.getTranslator(TranslationDirection.Deobfuscating).translateClass(entry.getClassName()); + throw new IllegalNameException(deobfName, "There is already a method with that name and signature in class " + deobfClassName); } } - for( MethodEntry entry : implementations ) - { - setMethodName( entry, deobfName ); + for (MethodEntry entry : implementations) { + setMethodName(entry, deobfName); } } - - public void setMethodName( MethodEntry obf, String deobfName ) - { - deobfName = NameValidator.validateMethodName( deobfName ); - MethodEntry targetEntry = new MethodEntry( obf.getClassEntry(), deobfName, obf.getSignature() ); - if( m_mappings.containsDeobfMethod( obf.getClassEntry(), deobfName, obf.getSignature() ) || m_index.containsObfBehavior( targetEntry ) ) - { - String deobfClassName = m_mappings.getTranslator( TranslationDirection.Deobfuscating ).translateClass( obf.getClassName() ); - throw new IllegalNameException( deobfName, "There is already a method with that name and signature in class " + deobfClassName ); + + public void setMethodName(MethodEntry obf, String deobfName) { + deobfName = NameValidator.validateMethodName(deobfName); + MethodEntry targetEntry = new MethodEntry(obf.getClassEntry(), deobfName, obf.getSignature()); + if (m_mappings.containsDeobfMethod(obf.getClassEntry(), deobfName, obf.getSignature()) || m_index.containsObfBehavior(targetEntry)) { + String deobfClassName = m_mappings.getTranslator(TranslationDirection.Deobfuscating).translateClass(obf.getClassName()); + throw new IllegalNameException(deobfName, "There is already a method with that name and signature in class " + deobfClassName); } - ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping( obf.getClassEntry() ); - classMapping.setMethodName( obf.getName(), obf.getSignature(), deobfName ); + ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping(obf.getClassEntry()); + classMapping.setMethodName(obf.getName(), obf.getSignature(), deobfName); } - public void removeMethodTreeMapping( MethodEntry obf ) - { - for( MethodEntry implementation : m_index.getRelatedMethodImplementations( obf ) ) - { - removeMethodMapping( implementation ); + public void removeMethodTreeMapping(MethodEntry obf) { + for (MethodEntry implementation : m_index.getRelatedMethodImplementations(obf)) { + removeMethodMapping(implementation); } } - public void removeMethodMapping( MethodEntry obf ) - { - ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping( obf.getClassEntry() ); - classMapping.setMethodName( obf.getName(), obf.getSignature(), null ); + public void removeMethodMapping(MethodEntry obf) { + ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping(obf.getClassEntry()); + classMapping.setMethodName(obf.getName(), obf.getSignature(), null); } - public void markMethodTreeAsDeobfuscated( MethodEntry obf ) - { - for( MethodEntry implementation : m_index.getRelatedMethodImplementations( obf ) ) - { - markMethodAsDeobfuscated( implementation ); + public void markMethodTreeAsDeobfuscated(MethodEntry obf) { + for (MethodEntry implementation : m_index.getRelatedMethodImplementations(obf)) { + markMethodAsDeobfuscated(implementation); } } - public void markMethodAsDeobfuscated( MethodEntry obf ) - { - ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping( obf.getClassEntry() ); - classMapping.setMethodName( obf.getName(), obf.getSignature(), obf.getName() ); + public void markMethodAsDeobfuscated(MethodEntry obf) { + ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping(obf.getClassEntry()); + classMapping.setMethodName(obf.getName(), obf.getSignature(), obf.getName()); } - public void setArgumentName( ArgumentEntry obf, String deobfName ) - { - deobfName = NameValidator.validateArgumentName( deobfName ); + public void setArgumentName(ArgumentEntry obf, String deobfName) { + deobfName = NameValidator.validateArgumentName(deobfName); // NOTE: don't need to check arguments for name collisions with names determined by Procyon - if( m_mappings.containsArgument( obf.getBehaviorEntry(), deobfName ) ) - { - throw new IllegalNameException( deobfName, "There is already an argument with that name" ); + if (m_mappings.containsArgument(obf.getBehaviorEntry(), deobfName)) { + throw new IllegalNameException(deobfName, "There is already an argument with that name"); } - ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping( obf.getClassEntry() ); - classMapping.setArgumentName( obf.getMethodName(), obf.getMethodSignature(), obf.getIndex(), deobfName ); + ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping(obf.getClassEntry()); + classMapping.setArgumentName(obf.getMethodName(), obf.getMethodSignature(), obf.getIndex(), deobfName); } - public void removeArgumentMapping( ArgumentEntry obf ) - { - ClassMapping classMapping = getClassMappingOrInnerClassMapping( obf.getClassEntry() ); - classMapping.removeArgumentName( obf.getMethodName(), obf.getMethodSignature(), obf.getIndex() ); + public void removeArgumentMapping(ArgumentEntry obf) { + ClassMapping classMapping = getClassMappingOrInnerClassMapping(obf.getClassEntry()); + classMapping.removeArgumentName(obf.getMethodName(), obf.getMethodSignature(), obf.getIndex()); } - public void markArgumentAsDeobfuscated( ArgumentEntry obf ) - { - ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping( obf.getClassEntry() ); - classMapping.setArgumentName( obf.getMethodName(), obf.getMethodSignature(), obf.getIndex(), obf.getName() ); + public void markArgumentAsDeobfuscated(ArgumentEntry obf) { + ClassMapping classMapping = getOrCreateClassMappingOrInnerClassMapping(obf.getClassEntry()); + classMapping.setArgumentName(obf.getMethodName(), obf.getMethodSignature(), obf.getIndex(), obf.getName()); } - public boolean moveFieldToObfClass( ClassMapping classMapping, FieldMapping fieldMapping, ClassEntry obfClass ) - { - classMapping.removeFieldMapping( fieldMapping ); - ClassMapping targetClassMapping = getOrCreateClassMapping( obfClass ); - if( !targetClassMapping.containsObfField( fieldMapping.getObfName() ) ) - { - if( !targetClassMapping.containsDeobfField( fieldMapping.getDeobfName() ) ) - { - targetClassMapping.addFieldMapping( fieldMapping ); + public boolean moveFieldToObfClass(ClassMapping classMapping, FieldMapping fieldMapping, ClassEntry obfClass) { + classMapping.removeFieldMapping(fieldMapping); + ClassMapping targetClassMapping = getOrCreateClassMapping(obfClass); + if (!targetClassMapping.containsObfField(fieldMapping.getObfName())) { + if (!targetClassMapping.containsDeobfField(fieldMapping.getDeobfName())) { + targetClassMapping.addFieldMapping(fieldMapping); return true; - } - else - { - System.err.println( "WARNING: deobf field was already there: " + obfClass + "." + fieldMapping.getDeobfName() ); + } else { + System.err.println("WARNING: deobf field was already there: " + obfClass + "." + fieldMapping.getDeobfName()); } } return false; } - public boolean moveMethodToObfClass( ClassMapping classMapping, MethodMapping methodMapping, ClassEntry obfClass ) - { - classMapping.removeMethodMapping( methodMapping ); - ClassMapping targetClassMapping = getOrCreateClassMapping( obfClass ); - if( !targetClassMapping.containsObfMethod( methodMapping.getObfName(), methodMapping.getObfSignature() ) ) - { - if( !targetClassMapping.containsDeobfMethod( methodMapping.getDeobfName(), methodMapping.getObfSignature() ) ) - { - targetClassMapping.addMethodMapping( methodMapping ); + public boolean moveMethodToObfClass(ClassMapping classMapping, MethodMapping methodMapping, ClassEntry obfClass) { + classMapping.removeMethodMapping(methodMapping); + ClassMapping targetClassMapping = getOrCreateClassMapping(obfClass); + if (!targetClassMapping.containsObfMethod(methodMapping.getObfName(), methodMapping.getObfSignature())) { + if (!targetClassMapping.containsDeobfMethod(methodMapping.getDeobfName(), methodMapping.getObfSignature())) { + targetClassMapping.addMethodMapping(methodMapping); return true; - } - else - { - System.err.println( "WARNING: deobf method was already there: " + obfClass + "." + methodMapping.getDeobfName() + methodMapping.getObfSignature() ); + } else { + System.err.println("WARNING: deobf method was already there: " + obfClass + "." + methodMapping.getDeobfName() + methodMapping.getObfSignature()); } } return false; } - public void write( OutputStream out ) - throws IOException - { + public void write(OutputStream out) throws IOException { // TEMP: just use the object output for now. We can find a more efficient storage format later - GZIPOutputStream gzipout = new GZIPOutputStream( out ); - ObjectOutputStream oout = new ObjectOutputStream( gzipout ); - oout.writeObject( this ); + GZIPOutputStream gzipout = new GZIPOutputStream(out); + ObjectOutputStream oout = new ObjectOutputStream(gzipout); + oout.writeObject(this); gzipout.finish(); } - private ClassMapping getClassMapping( ClassEntry obfClassEntry ) - { - return m_mappings.m_classesByObf.get( obfClassEntry.getOuterClassName() ); + private ClassMapping getClassMapping(ClassEntry obfClassEntry) { + return m_mappings.m_classesByObf.get(obfClassEntry.getOuterClassName()); } - private ClassMapping getOrCreateClassMapping( ClassEntry obfClassEntry ) - { + private ClassMapping getOrCreateClassMapping(ClassEntry obfClassEntry) { String obfClassName = obfClassEntry.getOuterClassName(); - ClassMapping classMapping = m_mappings.m_classesByObf.get( obfClassName ); - if( classMapping == null ) - { - classMapping = new ClassMapping( obfClassName ); - boolean obfWasAdded = m_mappings.m_classesByObf.put( classMapping.getObfName(), classMapping ) == null; - assert( obfWasAdded ); + ClassMapping classMapping = m_mappings.m_classesByObf.get(obfClassName); + if (classMapping == null) { + classMapping = new ClassMapping(obfClassName); + boolean obfWasAdded = m_mappings.m_classesByObf.put(classMapping.getObfName(), classMapping) == null; + assert (obfWasAdded); } return classMapping; } - private ClassMapping getClassMappingOrInnerClassMapping( ClassEntry obfClassEntry ) - { - ClassMapping classMapping = getClassMapping( obfClassEntry ); - if( obfClassEntry.isInDefaultPackage() ) - { - classMapping = classMapping.getInnerClassByObf( obfClassEntry.getInnerClassName() ); + private ClassMapping getClassMappingOrInnerClassMapping(ClassEntry obfClassEntry) { + ClassMapping classMapping = getClassMapping(obfClassEntry); + if (obfClassEntry.isInDefaultPackage()) { + classMapping = classMapping.getInnerClassByObf(obfClassEntry.getInnerClassName()); } return classMapping; } - private ClassMapping getOrCreateClassMappingOrInnerClassMapping( ClassEntry obfClassEntry ) - { - ClassMapping classMapping = getOrCreateClassMapping( obfClassEntry ); - if( obfClassEntry.isInnerClass() ) - { - classMapping = classMapping.getOrCreateInnerClass( obfClassEntry.getInnerClassName() ); + private ClassMapping getOrCreateClassMappingOrInnerClassMapping(ClassEntry obfClassEntry) { + ClassMapping classMapping = getOrCreateClassMapping(obfClassEntry); + if (obfClassEntry.isInnerClass()) { + classMapping = classMapping.getOrCreateInnerClass(obfClassEntry.getInnerClassName()); } return classMapping; } diff --git a/src/cuchaz/enigma/mapping/MappingsWriter.java b/src/cuchaz/enigma/mapping/MappingsWriter.java index 3c86dfc..5ac409f 100644 --- a/src/cuchaz/enigma/mapping/MappingsWriter.java +++ b/src/cuchaz/enigma/mapping/MappingsWriter.java @@ -17,105 +17,71 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -public class MappingsWriter -{ - public void write( Writer out, Mappings mappings ) - throws IOException - { - write( new PrintWriter( out ), mappings ); +public class MappingsWriter { + + public void write(Writer out, Mappings mappings) throws IOException { + write(new PrintWriter(out), mappings); } - public void write( PrintWriter out, Mappings mappings ) - throws IOException - { - for( ClassMapping classMapping : sorted( mappings.classes() ) ) - { - write( out, classMapping, 0 ); + public void write(PrintWriter out, Mappings mappings) throws IOException { + for (ClassMapping classMapping : sorted(mappings.classes())) { + write(out, classMapping, 0); } } - private void write( PrintWriter out, ClassMapping classMapping, int depth ) - throws IOException - { - if( classMapping.getDeobfName() == null ) - { - out.format( "%sCLASS %s\n", getIndent( depth ), classMapping.getObfName() ); - } - else - { - out.format( "%sCLASS %s %s\n", getIndent( depth ), classMapping.getObfName(), classMapping.getDeobfName() ); + private void write(PrintWriter out, ClassMapping classMapping, int depth) throws IOException { + if (classMapping.getDeobfName() == null) { + out.format("%sCLASS %s\n", getIndent(depth), classMapping.getObfName()); + } else { + out.format("%sCLASS %s %s\n", getIndent(depth), classMapping.getObfName(), classMapping.getDeobfName()); } - for( ClassMapping innerClassMapping : sorted( classMapping.innerClasses() ) ) - { - write( out, innerClassMapping, depth + 1 ); + for (ClassMapping innerClassMapping : sorted(classMapping.innerClasses())) { + write(out, innerClassMapping, depth + 1); } - for( FieldMapping fieldMapping : sorted( classMapping.fields() ) ) - { - write( out, fieldMapping, depth + 1 ); + for (FieldMapping fieldMapping : sorted(classMapping.fields())) { + write(out, fieldMapping, depth + 1); } - for( MethodMapping methodMapping : sorted( classMapping.methods() ) ) - { - write( out, methodMapping, depth + 1 ); + for (MethodMapping methodMapping : sorted(classMapping.methods())) { + write(out, methodMapping, depth + 1); } } - - private void write( PrintWriter out, FieldMapping fieldMapping, int depth ) - throws IOException - { - out.format( "%sFIELD %s %s\n", getIndent( depth ), fieldMapping.getObfName(), fieldMapping.getDeobfName() ); + + private void write(PrintWriter out, FieldMapping fieldMapping, int depth) throws IOException { + out.format("%sFIELD %s %s\n", getIndent(depth), fieldMapping.getObfName(), fieldMapping.getDeobfName()); } - private void write( PrintWriter out, MethodMapping methodMapping, int depth ) - throws IOException - { - if( methodMapping.getDeobfName() == null ) - { - out.format( "%sMETHOD %s %s\n", - getIndent( depth ), - methodMapping.getObfName(), methodMapping.getObfSignature() - ); - } - else - { - out.format( "%sMETHOD %s %s %s\n", - getIndent( depth ), - methodMapping.getObfName(), methodMapping.getDeobfName(), - methodMapping.getObfSignature() - ); + private void write(PrintWriter out, MethodMapping methodMapping, int depth) throws IOException { + if (methodMapping.getDeobfName() == null) { + out.format("%sMETHOD %s %s\n", getIndent(depth), methodMapping.getObfName(), methodMapping.getObfSignature()); + } else { + out.format("%sMETHOD %s %s %s\n", getIndent(depth), methodMapping.getObfName(), methodMapping.getDeobfName(), methodMapping.getObfSignature()); } - for( ArgumentMapping argumentMapping : sorted( methodMapping.arguments() ) ) - { - write( out, argumentMapping, depth + 1 ); + for (ArgumentMapping argumentMapping : sorted(methodMapping.arguments())) { + write(out, argumentMapping, depth + 1); } } - - private void write( PrintWriter out, ArgumentMapping argumentMapping, int depth ) - throws IOException - { - out.format( "%sARG %d %s\n", getIndent( depth ), argumentMapping.getIndex(), argumentMapping.getName() ); + + private void write(PrintWriter out, ArgumentMapping argumentMapping, int depth) throws IOException { + out.format("%sARG %d %s\n", getIndent(depth), argumentMapping.getIndex(), argumentMapping.getName()); } - private > List sorted( Iterable classes ) - { + private > List sorted(Iterable classes) { List out = new ArrayList(); - for( T t : classes ) - { - out.add( t ); + for (T t : classes) { + out.add(t); } - Collections.sort( out ); + Collections.sort(out); return out; } - private String getIndent( int depth ) - { + private String getIndent(int depth) { StringBuilder buf = new StringBuilder(); - for( int i=0; i -{ +public class MethodMapping implements Serializable, Comparable { + private static final long serialVersionUID = -4409570216084263978L; private String m_obfName; @@ -25,165 +25,135 @@ public class MethodMapping implements Serializable, Comparable private String m_obfSignature; private Map m_arguments; - public MethodMapping( String obfName, String obfSignature ) - { - this( obfName, obfSignature, null ); + public MethodMapping(String obfName, String obfSignature) { + this(obfName, obfSignature, null); } - public MethodMapping( String obfName, String obfSignature, String deobfName ) - { - if( obfName == null ) - { - throw new IllegalArgumentException( "obf name cannot be null!" ); + public MethodMapping(String obfName, String obfSignature, String deobfName) { + if (obfName == null) { + throw new IllegalArgumentException("obf name cannot be null!"); } - if( obfSignature == null ) - { - throw new IllegalArgumentException( "obf signature cannot be null!" ); + if (obfSignature == null) { + throw new IllegalArgumentException("obf signature cannot be null!"); } m_obfName = obfName; - m_deobfName = NameValidator.validateMethodName( deobfName ); + m_deobfName = NameValidator.validateMethodName(deobfName); m_obfSignature = obfSignature; m_arguments = new TreeMap(); } - - public String getObfName( ) - { + + public String getObfName() { return m_obfName; } - public String getDeobfName( ) - { + public String getDeobfName() { return m_deobfName; } - public void setDeobfName( String val ) - { - m_deobfName = NameValidator.validateMethodName( val ); + + public void setDeobfName(String val) { + m_deobfName = NameValidator.validateMethodName(val); } - public String getObfSignature( ) - { + public String getObfSignature() { return m_obfSignature; } - public Iterable arguments( ) - { + public Iterable arguments() { return m_arguments.values(); } - public boolean isConstructor( ) - { - return m_obfName.startsWith( "<" ); + public boolean isConstructor() { + return m_obfName.startsWith("<"); } - public void addArgumentMapping( ArgumentMapping argumentMapping ) - { - boolean wasAdded = m_arguments.put( argumentMapping.getIndex(), argumentMapping ) == null; - assert( wasAdded ); + public void addArgumentMapping(ArgumentMapping argumentMapping) { + boolean wasAdded = m_arguments.put(argumentMapping.getIndex(), argumentMapping) == null; + assert (wasAdded); } - public String getObfArgumentName( int index ) - { - ArgumentMapping argumentMapping = m_arguments.get( index ); - if( argumentMapping != null ) - { + public String getObfArgumentName(int index) { + ArgumentMapping argumentMapping = m_arguments.get(index); + if (argumentMapping != null) { return argumentMapping.getName(); } return null; } - public String getDeobfArgumentName( int index ) - { - ArgumentMapping argumentMapping = m_arguments.get( index ); - if( argumentMapping != null ) - { + public String getDeobfArgumentName(int index) { + ArgumentMapping argumentMapping = m_arguments.get(index); + if (argumentMapping != null) { return argumentMapping.getName(); } return null; } - public void setArgumentName( int index, String name ) - { - ArgumentMapping argumentMapping = m_arguments.get( index ); - if( argumentMapping == null ) - { - argumentMapping = new ArgumentMapping( index, name ); - boolean wasAdded = m_arguments.put( index, argumentMapping ) == null; - assert( wasAdded ); - } - else - { - argumentMapping.setName( name ); + public void setArgumentName(int index, String name) { + ArgumentMapping argumentMapping = m_arguments.get(index); + if (argumentMapping == null) { + argumentMapping = new ArgumentMapping(index, name); + boolean wasAdded = m_arguments.put(index, argumentMapping) == null; + assert (wasAdded); + } else { + argumentMapping.setName(name); } } - public void removeArgumentName( int index ) - { - boolean wasRemoved = m_arguments.remove( index ) != null; - assert( wasRemoved ); + public void removeArgumentName(int index) { + boolean wasRemoved = m_arguments.remove(index) != null; + assert (wasRemoved); } @Override - public String toString( ) - { + public String toString() { StringBuilder buf = new StringBuilder(); - buf.append( "\t" ); - buf.append( m_obfName ); - buf.append( " <-> " ); - buf.append( m_deobfName ); - buf.append( "\n" ); - buf.append( "\t" ); - buf.append( m_obfSignature ); - buf.append( "\n" ); - buf.append( "\tArguments:\n" ); - for( ArgumentMapping argumentMapping : m_arguments.values() ) - { - buf.append( "\t\t" ); - buf.append( argumentMapping.getIndex() ); - buf.append( " -> " ); - buf.append( argumentMapping.getName() ); - buf.append( "\n" ); + buf.append("\t"); + buf.append(m_obfName); + buf.append(" <-> "); + buf.append(m_deobfName); + buf.append("\n"); + buf.append("\t"); + buf.append(m_obfSignature); + buf.append("\n"); + buf.append("\tArguments:\n"); + for (ArgumentMapping argumentMapping : m_arguments.values()) { + buf.append("\t\t"); + buf.append(argumentMapping.getIndex()); + buf.append(" -> "); + buf.append(argumentMapping.getName()); + buf.append("\n"); } return buf.toString(); } @Override - public int compareTo( MethodMapping other ) - { - return ( m_obfName + m_obfSignature ).compareTo( other.m_obfName + other.m_obfSignature ); + public int compareTo(MethodMapping other) { + return (m_obfName + m_obfSignature).compareTo(other.m_obfName + other.m_obfSignature); } - - public boolean renameObfClass( final String oldObfClassName, final String newObfClassName ) - { + + public boolean renameObfClass(final String oldObfClassName, final String newObfClassName) { // rename obf classes in the signature - String newSignature = SignatureUpdater.update( m_obfSignature, new ClassNameUpdater( ) - { + String newSignature = SignatureUpdater.update(m_obfSignature, new ClassNameUpdater() { @Override - public String update( String className ) - { - if( className.equals( oldObfClassName ) ) - { + public String update(String className) { + if (className.equals(oldObfClassName)) { return newObfClassName; } return className; } - } ); + }); - if( newSignature != m_obfSignature ) - { + if (newSignature != m_obfSignature) { m_obfSignature = newSignature; return true; } return false; } - - public boolean containsArgument( String name ) - { - for( ArgumentMapping argumentMapping : m_arguments.values() ) - { - if( argumentMapping.getName().equals( name ) ) - { + + public boolean containsArgument(String name) { + for (ArgumentMapping argumentMapping : m_arguments.values()) { + if (argumentMapping.getName().equals(name)) { return true; } } diff --git a/src/cuchaz/enigma/mapping/NameValidator.java b/src/cuchaz/enigma/mapping/NameValidator.java index c6ae596..35a17f9 100644 --- a/src/cuchaz/enigma/mapping/NameValidator.java +++ b/src/cuchaz/enigma/mapping/NameValidator.java @@ -16,82 +16,65 @@ import java.util.regex.Pattern; import javassist.bytecode.Descriptor; -public class NameValidator -{ +public class NameValidator { + private static final Pattern IdentifierPattern; private static final Pattern ClassPattern; private static final List ReservedWords = Arrays.asList( - "abstract", "continue", "for", "new", "switch", - "assert", "default", "goto", "package", "synchronized", - "boolean", "do", "if", "private", "this", - "break", "double", "implements", "protected", "throw", - "byte", "else", "import", "public", "throws", - "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", - "char", "final", "interface", "static", "void", - "class", "finally", "long", "strictfp", "volatile", - "const", "float", "native", "super", "while" + "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", + "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", + "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", + "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", + "long", "strictfp", "volatile", "const", "float", "native", "super", "while" ); - static - { + static { + // java allows all kinds of weird characters... StringBuilder startChars = new StringBuilder(); StringBuilder partChars = new StringBuilder(); - for( int i = Character.MIN_CODE_POINT; i <= Character.MAX_CODE_POINT; i++ ) - { - if( Character.isJavaIdentifierStart( i ) ) - { - startChars.appendCodePoint( i ); + for (int i = Character.MIN_CODE_POINT; i <= Character.MAX_CODE_POINT; i++) { + if (Character.isJavaIdentifierStart(i)) { + startChars.appendCodePoint(i); } - if( Character.isJavaIdentifierPart( i ) ) - { - partChars.appendCodePoint( i ); + if (Character.isJavaIdentifierPart(i)) { + partChars.appendCodePoint(i); } } String identifierRegex = "[A-Za-z_<][A-Za-z0-9_>]*"; - IdentifierPattern = Pattern.compile( identifierRegex ); - ClassPattern = Pattern.compile( String.format( "^(%s(\\.|/))*(%s)$", identifierRegex, identifierRegex ) ); + IdentifierPattern = Pattern.compile(identifierRegex); + ClassPattern = Pattern.compile(String.format("^(%s(\\.|/))*(%s)$", identifierRegex, identifierRegex)); } - public static String validateClassName( String name, boolean packageRequired ) - { - if( name == null ) - { + public static String validateClassName(String name, boolean packageRequired) { + if (name == null) { return null; } - if( !ClassPattern.matcher( name ).matches() || ReservedWords.contains( name ) ) - { - throw new IllegalNameException( name, "This doesn't look like a legal class name" ); + if (!ClassPattern.matcher(name).matches() || ReservedWords.contains(name)) { + throw new IllegalNameException(name, "This doesn't look like a legal class name"); } - if( packageRequired && new ClassEntry( name ).getPackageName() == null ) - { - throw new IllegalNameException( name, "Class must be in a package" ); + if (packageRequired && new ClassEntry(name).getPackageName() == null) { + throw new IllegalNameException(name, "Class must be in a package"); } - return Descriptor.toJvmName( name ); + return Descriptor.toJvmName(name); } - public static String validateFieldName( String name ) - { - if( name == null ) - { + public static String validateFieldName(String name) { + if (name == null) { return null; } - if( !IdentifierPattern.matcher( name ).matches() || ReservedWords.contains( name ) ) - { - throw new IllegalNameException( name, "This doesn't look like a legal identifier" ); + if (!IdentifierPattern.matcher(name).matches() || ReservedWords.contains(name)) { + throw new IllegalNameException(name, "This doesn't look like a legal identifier"); } return name; } - public static String validateMethodName( String name ) - { - return validateFieldName( name ); + public static String validateMethodName(String name) { + return validateFieldName(name); } - public static String validateArgumentName( String name ) - { - return validateFieldName( name ); + public static String validateArgumentName(String name) { + return validateFieldName(name); } } diff --git a/src/cuchaz/enigma/mapping/SignatureUpdater.java b/src/cuchaz/enigma/mapping/SignatureUpdater.java index 809473e..3477cd5 100644 --- a/src/cuchaz/enigma/mapping/SignatureUpdater.java +++ b/src/cuchaz/enigma/mapping/SignatureUpdater.java @@ -16,84 +16,63 @@ import java.util.List; import com.google.common.collect.Lists; -public class SignatureUpdater -{ - public interface ClassNameUpdater - { - String update( String className ); +public class SignatureUpdater { + + public interface ClassNameUpdater { + String update(String className); } - public static String update( String signature, ClassNameUpdater updater ) - { - try - { + public static String update(String signature, ClassNameUpdater updater) { + try { StringBuilder buf = new StringBuilder(); // read the signature character-by-character - StringReader reader = new StringReader( signature ); + StringReader reader = new StringReader(signature); int i = -1; - while( ( i = reader.read() ) != -1 ) - { + while ( (i = reader.read()) != -1) { char c = (char)i; // does this character start a class name? - if( c == 'L' ) - { + if (c == 'L') { // update the class name and add it to the buffer - buf.append( 'L' ); - String className = readClass( reader ); - if( className == null ) - { - throw new IllegalArgumentException( "Malformed signature: " + signature ); + buf.append('L'); + String className = readClass(reader); + if (className == null) { + throw new IllegalArgumentException("Malformed signature: " + signature); } - buf.append( updater.update( className ) ); - buf.append( ';' ); - } - else - { + buf.append(updater.update(className)); + buf.append(';'); + } else { // copy the character into the buffer - buf.append( c ); + buf.append(c); } } return buf.toString(); - } - catch( IOException ex ) - { + } catch (IOException ex) { // I'm pretty sure a StringReader will never throw one of these - throw new Error( ex ); + throw new Error(ex); } } - private static String readClass( StringReader reader ) - throws IOException - { + private static String readClass(StringReader reader) throws IOException { // read all the characters in the buffer until we hit a ';' // remember to treat generics correctly StringBuilder buf = new StringBuilder(); int depth = 0; int i = -1; - while( ( i = reader.read() ) != -1 ) - { + while ( (i = reader.read()) != -1) { char c = (char)i; - if( c == '<' ) - { + if (c == '<') { depth++; - } - else if( c == '>' ) - { + } else if (c == '>') { depth--; - } - else if( depth == 0 ) - { - if( c == ';' ) - { + } else if (depth == 0) { + if (c == ';') { return buf.toString(); - } - else - { - buf.append( c ); + } else { + buf.append(c); } } } @@ -101,18 +80,15 @@ public class SignatureUpdater return null; } - public static List getClasses( String signature ) - { + public static List getClasses(String signature) { final List classNames = Lists.newArrayList(); - update( signature, new ClassNameUpdater( ) - { + update(signature, new ClassNameUpdater() { @Override - public String update( String className ) - { - classNames.add( className ); + public String update(String className) { + classNames.add(className); return className; } - } ); + }); return classNames; } } diff --git a/src/cuchaz/enigma/mapping/TranslationDirection.java b/src/cuchaz/enigma/mapping/TranslationDirection.java index 79ae0d3..d1b14cd 100644 --- a/src/cuchaz/enigma/mapping/TranslationDirection.java +++ b/src/cuchaz/enigma/mapping/TranslationDirection.java @@ -10,25 +10,20 @@ ******************************************************************************/ package cuchaz.enigma.mapping; - -public enum TranslationDirection -{ - Deobfuscating - { +public enum TranslationDirection { + + Deobfuscating { @Override - public T choose( T deobfChoice, T obfChoice ) - { + public T choose(T deobfChoice, T obfChoice) { return deobfChoice; } }, - Obfuscating - { + Obfuscating { @Override - public T choose( T deobfChoice, T obfChoice ) - { + public T choose(T deobfChoice, T obfChoice) { return obfChoice; } }; - - public abstract T choose( T deobfChoice, T obfChoice ); + + public abstract T choose(T deobfChoice, T obfChoice); } diff --git a/src/cuchaz/enigma/mapping/Translator.java b/src/cuchaz/enigma/mapping/Translator.java index 6cb5240..d8d9f48 100644 --- a/src/cuchaz/enigma/mapping/Translator.java +++ b/src/cuchaz/enigma/mapping/Translator.java @@ -16,277 +16,203 @@ import com.google.common.collect.Maps; import cuchaz.enigma.mapping.SignatureUpdater.ClassNameUpdater; -public class Translator -{ +public class Translator { + private TranslationDirection m_direction; private Map m_classes; - public Translator( ) - { + public Translator() { m_direction = null; m_classes = Maps.newHashMap(); } - public Translator( TranslationDirection direction, Map classes ) - { + public Translator(TranslationDirection direction, Map classes) { m_direction = direction; m_classes = classes; } - @SuppressWarnings( "unchecked" ) - public T translateEntry( T entry ) - { - if( entry instanceof ClassEntry ) - { - return (T)translateEntry( (ClassEntry)entry ); - } - else if( entry instanceof FieldEntry ) - { - return (T)translateEntry( (FieldEntry)entry ); - } - else if( entry instanceof MethodEntry ) - { - return (T)translateEntry( (MethodEntry)entry ); - } - else if( entry instanceof ConstructorEntry ) - { - return (T)translateEntry( (ConstructorEntry)entry ); - } - else if( entry instanceof ArgumentEntry ) - { - return (T)translateEntry( (ArgumentEntry)entry ); - } - else - { - throw new Error( "Unknown entry type: " + entry.getClass().getName() ); + @SuppressWarnings("unchecked") + public T translateEntry(T entry) { + if (entry instanceof ClassEntry) { + return (T)translateEntry((ClassEntry)entry); + } else if (entry instanceof FieldEntry) { + return (T)translateEntry((FieldEntry)entry); + } else if (entry instanceof MethodEntry) { + return (T)translateEntry((MethodEntry)entry); + } else if (entry instanceof ConstructorEntry) { + return (T)translateEntry((ConstructorEntry)entry); + } else if (entry instanceof ArgumentEntry) { + return (T)translateEntry((ArgumentEntry)entry); + } else { + throw new Error("Unknown entry type: " + entry.getClass().getName()); } } - public String translateClass( String className ) - { - return translate( new ClassEntry( className ) ); + public String translateClass(String className) { + return translate(new ClassEntry(className)); } - public String translate( ClassEntry in ) - { - ClassMapping classMapping = m_classes.get( in.getOuterClassName() ); - if( classMapping != null ) - { - if( in.isInnerClass() ) - { + public String translate(ClassEntry in) { + ClassMapping classMapping = m_classes.get(in.getOuterClassName()); + if (classMapping != null) { + if (in.isInnerClass()) { // translate the inner class String translatedInnerClassName = m_direction.choose( - classMapping.getDeobfInnerClassName( in.getInnerClassName() ), - classMapping.getObfInnerClassName( in.getInnerClassName() ) + classMapping.getDeobfInnerClassName(in.getInnerClassName()), + classMapping.getObfInnerClassName(in.getInnerClassName()) ); - if( translatedInnerClassName != null ) - { + if (translatedInnerClassName != null) { // try to translate the outer name - String translatedOuterClassName = m_direction.choose( - classMapping.getDeobfName(), - classMapping.getObfName() - ); - if( translatedOuterClassName != null ) - { + String translatedOuterClassName = m_direction.choose(classMapping.getDeobfName(), classMapping.getObfName()); + if (translatedOuterClassName != null) { return translatedOuterClassName + "$" + translatedInnerClassName; - } - else - { + } else { return in.getOuterClassName() + "$" + translatedInnerClassName; } } - } - else - { + } else { // just return outer - return m_direction.choose( - classMapping.getDeobfName(), - classMapping.getObfName() - ); + return m_direction.choose(classMapping.getDeobfName(), classMapping.getObfName()); } } return null; } - public ClassEntry translateEntry( ClassEntry in ) - { + public ClassEntry translateEntry(ClassEntry in) { + // can we translate the inner class? - String name = translate( in ); - if( name != null ) - { - return new ClassEntry( name ); + String name = translate(in); + if (name != null) { + return new ClassEntry(name); } - if( in.isInnerClass() ) - { + if (in.isInnerClass()) { + // guess not. just translate the outer class name then - String outerClassName = translate( in.getOuterClassEntry() ); - if( outerClassName != null ) - { - return new ClassEntry( outerClassName + "$" + in.getInnerClassName() ); + String outerClassName = translate(in.getOuterClassEntry()); + if (outerClassName != null) { + return new ClassEntry(outerClassName + "$" + in.getInnerClassName()); } } return in; } - public String translate( FieldEntry in ) - { + public String translate(FieldEntry in) { + // look for the class - ClassMapping classMapping = findClassMapping( in.getClassEntry() ); - if( classMapping != null ) - { + ClassMapping classMapping = findClassMapping(in.getClassEntry()); + if (classMapping != null) { + // look for the field String translatedName = m_direction.choose( - classMapping.getDeobfFieldName( in.getName() ), - classMapping.getObfFieldName( in.getName() ) + classMapping.getDeobfFieldName(in.getName()), + classMapping.getObfFieldName(in.getName()) ); - if( translatedName != null ) - { + if (translatedName != null) { return translatedName; } } return null; } - public FieldEntry translateEntry( FieldEntry in ) - { - String name = translate( in ); - if( name == null ) - { + public FieldEntry translateEntry(FieldEntry in) { + String name = translate(in); + if (name == null) { name = in.getName(); } - return new FieldEntry( - translateEntry( in.getClassEntry() ), - name - ); + return new FieldEntry(translateEntry(in.getClassEntry()), name); } - public String translate( MethodEntry in ) - { + public String translate(MethodEntry in) { + // look for class - ClassMapping classMapping = findClassMapping( in.getClassEntry() ); - if( classMapping != null ) - { + ClassMapping classMapping = findClassMapping(in.getClassEntry()); + if (classMapping != null) { + // look for the method - MethodMapping methodMapping = m_direction.choose( - classMapping.getMethodByObf( in.getName(), in.getSignature() ), - classMapping.getMethodByDeobf( in.getName(), translateSignature( in.getSignature() ) ) - ); - if( methodMapping != null ) - { - return m_direction.choose( - methodMapping.getDeobfName(), - methodMapping.getObfName() - ); + MethodMapping methodMapping = m_direction.choose(classMapping.getMethodByObf(in.getName(), in.getSignature()), + classMapping.getMethodByDeobf(in.getName(), translateSignature(in.getSignature()))); + if (methodMapping != null) { + return m_direction.choose(methodMapping.getDeobfName(), methodMapping.getObfName()); } } return null; } - public MethodEntry translateEntry( MethodEntry in ) - { - String name = translate( in ); - if( name == null ) - { + public MethodEntry translateEntry(MethodEntry in) { + String name = translate(in); + if (name == null) { name = in.getName(); } - return new MethodEntry( - translateEntry( in.getClassEntry() ), - name, - translateSignature( in.getSignature() ) - ); + return new MethodEntry(translateEntry(in.getClassEntry()), name, translateSignature(in.getSignature())); } - public ConstructorEntry translateEntry( ConstructorEntry in ) - { - if( in.isStatic() ) - { - return new ConstructorEntry( translateEntry( in.getClassEntry() ) ); - } - else - { - return new ConstructorEntry( - translateEntry( in.getClassEntry() ), - translateSignature( in.getSignature() ) - ); + public ConstructorEntry translateEntry(ConstructorEntry in) { + if (in.isStatic()) { + return new ConstructorEntry(translateEntry(in.getClassEntry())); + } else { + return new ConstructorEntry(translateEntry(in.getClassEntry()), translateSignature(in.getSignature())); } } - public BehaviorEntry translateEntry( BehaviorEntry in ) - { - if( in instanceof MethodEntry ) - { - return translateEntry( (MethodEntry)in ); + public BehaviorEntry translateEntry(BehaviorEntry in) { + if (in instanceof MethodEntry) { + return translateEntry((MethodEntry)in); + } else if (in instanceof ConstructorEntry) { + return translateEntry((ConstructorEntry)in); } - else if( in instanceof ConstructorEntry ) - { - return translateEntry( (ConstructorEntry)in ); - } - throw new Error( "Wrong entry type!" ); + throw new Error("Wrong entry type!"); } - public String translate( ArgumentEntry in ) - { + public String translate(ArgumentEntry in) { + // look for the class - ClassMapping classMapping = findClassMapping( in.getClassEntry() ); - if( classMapping != null ) - { + ClassMapping classMapping = findClassMapping(in.getClassEntry()); + if (classMapping != null) { + // look for the method MethodMapping methodMapping = m_direction.choose( - classMapping.getMethodByObf( in.getMethodName(), in.getMethodSignature() ), - classMapping.getMethodByDeobf( in.getMethodName(), translateSignature( in.getMethodSignature() ) ) + classMapping.getMethodByObf(in.getMethodName(), in.getMethodSignature()), + classMapping.getMethodByDeobf(in.getMethodName(), translateSignature(in.getMethodSignature())) ); - if( methodMapping != null ) - { + if (methodMapping != null) { return m_direction.choose( - methodMapping.getDeobfArgumentName( in.getIndex() ), - methodMapping.getObfArgumentName( in.getIndex() ) + methodMapping.getDeobfArgumentName(in.getIndex()), + methodMapping.getObfArgumentName(in.getIndex()) ); } } return null; } - public ArgumentEntry translateEntry( ArgumentEntry in ) - { - String name = translate( in ); - if( name == null ) - { + public ArgumentEntry translateEntry(ArgumentEntry in) { + String name = translate(in); + if (name == null) { name = in.getName(); } - return new ArgumentEntry( - translateEntry( in.getBehaviorEntry() ), - in.getIndex(), - name - ); + return new ArgumentEntry(translateEntry(in.getBehaviorEntry()), in.getIndex(), name); } - public String translateSignature( String signature ) - { - return SignatureUpdater.update( signature, new ClassNameUpdater( ) - { + public String translateSignature(String signature) { + return SignatureUpdater.update(signature, new ClassNameUpdater() { @Override - public String update( String className ) - { - String translatedName = translateClass( className ); - if( translatedName != null ) - { + public String update(String className) { + String translatedName = translateClass(className); + if (translatedName != null) { return translatedName; } return className; } - } ); + }); } - private ClassMapping findClassMapping( ClassEntry classEntry ) - { - ClassMapping classMapping = m_classes.get( classEntry.getOuterClassName() ); - if( classMapping != null && classEntry.isInnerClass() ) - { + private ClassMapping findClassMapping(ClassEntry classEntry) { + ClassMapping classMapping = m_classes.get(classEntry.getOuterClassName()); + if (classMapping != null && classEntry.isInnerClass()) { classMapping = m_direction.choose( - classMapping.getInnerClassByObf( classEntry.getInnerClassName() ), - classMapping.getInnerClassByDeobfThenObf( classEntry.getInnerClassName() ) + classMapping.getInnerClassByObf(classEntry.getInnerClassName()), + classMapping.getInnerClassByDeobfThenObf(classEntry.getInnerClassName()) ); } return classMapping; diff --git a/test/cuchaz/enigma/EntryFactory.java b/test/cuchaz/enigma/EntryFactory.java index 5a8a427..d9317ef 100644 --- a/test/cuchaz/enigma/EntryFactory.java +++ b/test/cuchaz/enigma/EntryFactory.java @@ -18,45 +18,37 @@ import cuchaz.enigma.mapping.ConstructorEntry; import cuchaz.enigma.mapping.FieldEntry; import cuchaz.enigma.mapping.MethodEntry; -public class EntryFactory -{ - public static ClassEntry newClass( String name ) - { - return new ClassEntry( name ); +public class EntryFactory { + + public static ClassEntry newClass(String name) { + return new ClassEntry(name); } - public static FieldEntry newField( String className, String fieldName ) - { - return new FieldEntry( newClass( className ), fieldName ); + public static FieldEntry newField(String className, String fieldName) { + return new FieldEntry(newClass(className), fieldName); } - public static MethodEntry newMethod( String className, String methodName, String methodSignature ) - { - return new MethodEntry( newClass( className ), methodName, methodSignature ); + public static MethodEntry newMethod(String className, String methodName, String methodSignature) { + return new MethodEntry(newClass(className), methodName, methodSignature); } - public static ConstructorEntry newConstructor( String className, String signature ) - { - return new ConstructorEntry( newClass( className ), signature ); + public static ConstructorEntry newConstructor(String className, String signature) { + return new ConstructorEntry(newClass(className), signature); } - public static EntryReference newFieldReferenceByMethod( FieldEntry fieldEntry, String callerClassName, String callerName, String callerSignature ) - { - return new EntryReference( fieldEntry, "", newMethod( callerClassName, callerName, callerSignature ) ); + public static EntryReference newFieldReferenceByMethod(FieldEntry fieldEntry, String callerClassName, String callerName, String callerSignature) { + return new EntryReference(fieldEntry, "", newMethod(callerClassName, callerName, callerSignature)); } - public static EntryReference newFieldReferenceByConstructor( FieldEntry fieldEntry, String callerClassName, String callerSignature ) - { - return new EntryReference( fieldEntry, "", newConstructor( callerClassName, callerSignature ) ); + public static EntryReference newFieldReferenceByConstructor(FieldEntry fieldEntry, String callerClassName, String callerSignature) { + return new EntryReference(fieldEntry, "", newConstructor(callerClassName, callerSignature)); } - public static EntryReference newBehaviorReferenceByMethod( BehaviorEntry behaviorEntry, String callerClassName, String callerName, String callerSignature ) - { - return new EntryReference( behaviorEntry, "", newMethod( callerClassName, callerName, callerSignature ) ); + public static EntryReference newBehaviorReferenceByMethod(BehaviorEntry behaviorEntry, String callerClassName, String callerName, String callerSignature) { + return new EntryReference(behaviorEntry, "", newMethod(callerClassName, callerName, callerSignature)); } - public static EntryReference newBehaviorReferenceByConstructor( BehaviorEntry behaviorEntry, String callerClassName, String callerSignature ) - { - return new EntryReference( behaviorEntry, "", newConstructor( callerClassName, callerSignature ) ); + public static EntryReference newBehaviorReferenceByConstructor(BehaviorEntry behaviorEntry, String callerClassName, String callerSignature) { + return new EntryReference(behaviorEntry, "", newConstructor(callerClassName, callerSignature)); } } diff --git a/test/cuchaz/enigma/TestDeobfuscator.java b/test/cuchaz/enigma/TestDeobfuscator.java index 71de24a..45d27c4 100644 --- a/test/cuchaz/enigma/TestDeobfuscator.java +++ b/test/cuchaz/enigma/TestDeobfuscator.java @@ -23,40 +23,32 @@ import com.google.common.collect.Lists; import cuchaz.enigma.mapping.ClassEntry; -public class TestDeobfuscator -{ - private Deobfuscator getDeobfuscator( ) - throws IOException - { - return new Deobfuscator( new File( "build/libs/testLoneClass.obf.jar" ) ); +public class TestDeobfuscator { + + private Deobfuscator getDeobfuscator() throws IOException { + return new Deobfuscator(new File("build/libs/testLoneClass.obf.jar")); } @Test - public void loadJar( ) - throws Exception - { + public void loadJar() throws Exception { getDeobfuscator(); } @Test - public void getClasses( ) - throws Exception - { + public void getClasses() throws Exception { Deobfuscator deobfuscator = getDeobfuscator(); List obfClasses = Lists.newArrayList(); List deobfClasses = Lists.newArrayList(); - deobfuscator.getSeparatedClasses( obfClasses, deobfClasses ); - assertEquals( 1, obfClasses.size() ); - assertEquals( "none/a", obfClasses.get( 0 ).getName() ); - assertEquals( 1, deobfClasses.size() ); - assertEquals( "cuchaz/enigma/inputs/Keep", deobfClasses.get( 0 ).getName() ); + deobfuscator.getSeparatedClasses(obfClasses, deobfClasses); + assertEquals(1, obfClasses.size()); + assertEquals("none/a", obfClasses.get(0).getName()); + assertEquals(1, deobfClasses.size()); + assertEquals("cuchaz/enigma/inputs/Keep", deobfClasses.get(0).getName()); } @Test - public void decompileClass( ) - throws Exception - { + public void decompileClass() throws Exception { Deobfuscator deobfuscator = getDeobfuscator(); - deobfuscator.getSource( deobfuscator.getSourceTree( "none/a" ) ); + deobfuscator.getSource(deobfuscator.getSourceTree("none/a")); } } diff --git a/test/cuchaz/enigma/TestInnerClasses.java b/test/cuchaz/enigma/TestInnerClasses.java index a7ee0b6..c84d755 100644 --- a/test/cuchaz/enigma/TestInnerClasses.java +++ b/test/cuchaz/enigma/TestInnerClasses.java @@ -20,8 +20,8 @@ import org.junit.Test; import cuchaz.enigma.analysis.JarIndex; -public class TestInnerClasses -{ +public class TestInnerClasses { + private JarIndex m_index; private static final String AnonymousOuter = "none/a"; @@ -33,42 +33,36 @@ public class TestInnerClasses private static final String AnonymousWithScopeArgsOuter = "none/c"; private static final String AnonymousWithScopeArgsInner = "d"; - public TestInnerClasses( ) - throws Exception - { + public TestInnerClasses() throws Exception { m_index = new JarIndex(); - m_index.indexJar( new JarFile( "build/libs/testInnerClasses.obf.jar" ), true ); + m_index.indexJar(new JarFile("build/libs/testInnerClasses.obf.jar"), true); } @Test - public void simple( ) - { - assertThat( m_index.getOuterClass( SimpleInner ), is( SimpleOuter ) ); - assertThat( m_index.getInnerClasses( SimpleOuter ), containsInAnyOrder( SimpleInner ) ); - assertThat( m_index.isAnonymousClass( SimpleInner ), is( false ) ); + public void simple() { + assertThat(m_index.getOuterClass(SimpleInner), is(SimpleOuter)); + assertThat(m_index.getInnerClasses(SimpleOuter), containsInAnyOrder(SimpleInner)); + assertThat(m_index.isAnonymousClass(SimpleInner), is(false)); } @Test - public void anonymous( ) - { - assertThat( m_index.getOuterClass( AnonymousInner ), is( AnonymousOuter ) ); - assertThat( m_index.getInnerClasses( AnonymousOuter ), containsInAnyOrder( AnonymousInner ) ); - assertThat( m_index.isAnonymousClass( AnonymousInner ), is( true ) ); + public void anonymous() { + assertThat(m_index.getOuterClass(AnonymousInner), is(AnonymousOuter)); + assertThat(m_index.getInnerClasses(AnonymousOuter), containsInAnyOrder(AnonymousInner)); + assertThat(m_index.isAnonymousClass(AnonymousInner), is(true)); } - + @Test - public void constructorArgs( ) - { - assertThat( m_index.getOuterClass( ConstructorArgsInner ), is( ConstructorArgsOuter ) ); - assertThat( m_index.getInnerClasses( ConstructorArgsOuter ), containsInAnyOrder( ConstructorArgsInner ) ); - assertThat( m_index.isAnonymousClass( ConstructorArgsInner ), is( false ) ); + public void constructorArgs() { + assertThat(m_index.getOuterClass(ConstructorArgsInner), is(ConstructorArgsOuter)); + assertThat(m_index.getInnerClasses(ConstructorArgsOuter), containsInAnyOrder(ConstructorArgsInner)); + assertThat(m_index.isAnonymousClass(ConstructorArgsInner), is(false)); } @Test - public void anonymousWithScopeArgs( ) - { - assertThat( m_index.getOuterClass( AnonymousWithScopeArgsInner ), is( AnonymousWithScopeArgsOuter ) ); - assertThat( m_index.getInnerClasses( AnonymousWithScopeArgsOuter ), containsInAnyOrder( AnonymousWithScopeArgsInner ) ); - assertThat( m_index.isAnonymousClass( AnonymousWithScopeArgsInner ), is( true ) ); + public void anonymousWithScopeArgs() { + assertThat(m_index.getOuterClass(AnonymousWithScopeArgsInner), is(AnonymousWithScopeArgsOuter)); + assertThat(m_index.getInnerClasses(AnonymousWithScopeArgsOuter), containsInAnyOrder(AnonymousWithScopeArgsInner)); + assertThat(m_index.isAnonymousClass(AnonymousWithScopeArgsInner), is(true)); } } diff --git a/test/cuchaz/enigma/TestJarIndexConstructorReferences.java b/test/cuchaz/enigma/TestJarIndexConstructorReferences.java index 0238171..b5f4c7f 100644 --- a/test/cuchaz/enigma/TestJarIndexConstructorReferences.java +++ b/test/cuchaz/enigma/TestJarIndexConstructorReferences.java @@ -26,117 +26,99 @@ import cuchaz.enigma.mapping.BehaviorEntry; import cuchaz.enigma.mapping.ClassEntry; import cuchaz.enigma.mapping.ConstructorEntry; -public class TestJarIndexConstructorReferences -{ +public class TestJarIndexConstructorReferences { + private JarIndex m_index; - - private ClassEntry m_baseClass = new ClassEntry( "none/a" ); - private ClassEntry m_subClass = new ClassEntry( "none/d" ); - private ClassEntry m_subsubClass = new ClassEntry( "none/e" ); - private ClassEntry m_defaultClass = new ClassEntry( "none/c" ); - private ClassEntry m_callerClass = new ClassEntry( "none/b" ); - - public TestJarIndexConstructorReferences( ) - throws Exception - { - File jarFile = new File( "build/libs/testConstructors.obf.jar" ); + + private ClassEntry m_baseClass = new ClassEntry("none/a"); + private ClassEntry m_subClass = new ClassEntry("none/d"); + private ClassEntry m_subsubClass = new ClassEntry("none/e"); + private ClassEntry m_defaultClass = new ClassEntry("none/c"); + private ClassEntry m_callerClass = new ClassEntry("none/b"); + + public TestJarIndexConstructorReferences() throws Exception { + File jarFile = new File("build/libs/testConstructors.obf.jar"); m_index = new JarIndex(); - m_index.indexJar( new JarFile( jarFile ), false ); + m_index.indexJar(new JarFile(jarFile), false); } @Test - public void obfEntries( ) - { - assertThat( m_index.getObfClassEntries(), containsInAnyOrder( - newClass( "cuchaz/enigma/inputs/Keep" ), - m_baseClass, - m_subClass, - m_subsubClass, - m_defaultClass, - m_callerClass - ) ); + public void obfEntries() { + assertThat(m_index.getObfClassEntries(), containsInAnyOrder(newClass("cuchaz/enigma/inputs/Keep"), m_baseClass, m_subClass, m_subsubClass, m_defaultClass, m_callerClass)); } @Test - @SuppressWarnings( "unchecked" ) - public void baseDefault( ) - { - BehaviorEntry source = new ConstructorEntry( m_baseClass, "()V" ); - Collection> references = m_index.getBehaviorReferences( source ); - assertThat( references, containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_callerClass.getName(), "a", "()V" ), - newBehaviorReferenceByConstructor( source, m_subClass.getName(), "()V" ), - newBehaviorReferenceByConstructor( source, m_subClass.getName(), "(III)V" ) - ) ); + @SuppressWarnings("unchecked") + public void baseDefault() { + BehaviorEntry source = new ConstructorEntry(m_baseClass, "()V"); + Collection> references = m_index.getBehaviorReferences(source); + assertThat(references, containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_callerClass.getName(), "a", "()V"), + newBehaviorReferenceByConstructor(source, m_subClass.getName(), "()V"), + newBehaviorReferenceByConstructor(source, m_subClass.getName(), "(III)V") + )); } @Test - @SuppressWarnings( "unchecked" ) - public void baseInt( ) - { - BehaviorEntry source = new ConstructorEntry( m_baseClass, "(I)V" ); - assertThat( m_index.getBehaviorReferences( source ), containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_callerClass.getName(), "b", "()V" ) - ) ); + @SuppressWarnings("unchecked") + public void baseInt() { + BehaviorEntry source = new ConstructorEntry(m_baseClass, "(I)V"); + assertThat(m_index.getBehaviorReferences(source), containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_callerClass.getName(), "b", "()V") + )); } - + @Test - @SuppressWarnings( "unchecked" ) - public void subDefault( ) - { - BehaviorEntry source = new ConstructorEntry( m_subClass, "()V" ); - assertThat( m_index.getBehaviorReferences( source ), containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_callerClass.getName(), "c", "()V" ), - newBehaviorReferenceByConstructor( source, m_subClass.getName(), "(I)V" ) - ) ); + @SuppressWarnings("unchecked") + public void subDefault() { + BehaviorEntry source = new ConstructorEntry(m_subClass, "()V"); + assertThat(m_index.getBehaviorReferences(source), containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_callerClass.getName(), "c", "()V"), + newBehaviorReferenceByConstructor(source, m_subClass.getName(), "(I)V") + )); } - + @Test - @SuppressWarnings( "unchecked" ) - public void subInt( ) - { - BehaviorEntry source = new ConstructorEntry( m_subClass, "(I)V" ); - assertThat( m_index.getBehaviorReferences( source ), containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_callerClass.getName(), "d", "()V" ), - newBehaviorReferenceByConstructor( source, m_subClass.getName(), "(II)V" ), - newBehaviorReferenceByConstructor( source, m_subsubClass.getName(), "(I)V" ) - ) ); + @SuppressWarnings("unchecked") + public void subInt() { + BehaviorEntry source = new ConstructorEntry(m_subClass, "(I)V"); + assertThat(m_index.getBehaviorReferences(source), containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_callerClass.getName(), "d", "()V"), + newBehaviorReferenceByConstructor(source, m_subClass.getName(), "(II)V"), + newBehaviorReferenceByConstructor(source, m_subsubClass.getName(), "(I)V") + )); } - + @Test - @SuppressWarnings( "unchecked" ) - public void subIntInt( ) - { - BehaviorEntry source = new ConstructorEntry( m_subClass, "(II)V" ); - assertThat( m_index.getBehaviorReferences( source ), containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_callerClass.getName(), "e", "()V" ) - ) ); + @SuppressWarnings("unchecked") + public void subIntInt() { + BehaviorEntry source = new ConstructorEntry(m_subClass, "(II)V"); + assertThat(m_index.getBehaviorReferences(source), containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_callerClass.getName(), "e", "()V") + )); } - + @Test - public void subIntIntInt( ) - { - BehaviorEntry source = new ConstructorEntry( m_subClass, "(III)V" ); - assertThat( m_index.getBehaviorReferences( source ), is( empty() ) ); + public void subIntIntInt() { + BehaviorEntry source = new ConstructorEntry(m_subClass, "(III)V"); + assertThat(m_index.getBehaviorReferences(source), is(empty())); } - + @Test - @SuppressWarnings( "unchecked" ) - public void subsubInt( ) - { - BehaviorEntry source = new ConstructorEntry( m_subsubClass, "(I)V" ); - assertThat( m_index.getBehaviorReferences( source ), containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_callerClass.getName(), "f", "()V" ) - ) ); + @SuppressWarnings("unchecked") + public void subsubInt() { + BehaviorEntry source = new ConstructorEntry(m_subsubClass, "(I)V"); + assertThat(m_index.getBehaviorReferences(source), containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_callerClass.getName(), "f", "()V") + )); } - + @Test - @SuppressWarnings( "unchecked" ) - public void defaultConstructable( ) - { - BehaviorEntry source = new ConstructorEntry( m_defaultClass, "()V" ); - assertThat( m_index.getBehaviorReferences( source ), containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_callerClass.getName(), "g", "()V" ) - ) ); + @SuppressWarnings("unchecked") + public void defaultConstructable() { + BehaviorEntry source = new ConstructorEntry(m_defaultClass, "()V"); + assertThat(m_index.getBehaviorReferences(source), containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_callerClass.getName(), "g", "()V") + )); } } diff --git a/test/cuchaz/enigma/TestJarIndexInheritanceTree.java b/test/cuchaz/enigma/TestJarIndexInheritanceTree.java index 50c2282..caf6578 100644 --- a/test/cuchaz/enigma/TestJarIndexInheritanceTree.java +++ b/test/cuchaz/enigma/TestJarIndexInheritanceTree.java @@ -30,209 +30,199 @@ import cuchaz.enigma.mapping.ConstructorEntry; import cuchaz.enigma.mapping.FieldEntry; import cuchaz.enigma.mapping.MethodEntry; -public class TestJarIndexInheritanceTree -{ +public class TestJarIndexInheritanceTree { + private JarIndex m_index; - private ClassEntry m_baseClass = new ClassEntry( "none/a" ); - private ClassEntry m_subClassA = new ClassEntry( "none/b" ); - private ClassEntry m_subClassAA = new ClassEntry( "none/d" ); - private ClassEntry m_subClassB = new ClassEntry( "none/c" ); - private FieldEntry m_nameField = new FieldEntry( m_baseClass, "a" ); - private FieldEntry m_numThingsField = new FieldEntry( m_subClassB, "a" ); + private ClassEntry m_baseClass = new ClassEntry("none/a"); + private ClassEntry m_subClassA = new ClassEntry("none/b"); + private ClassEntry m_subClassAA = new ClassEntry("none/d"); + private ClassEntry m_subClassB = new ClassEntry("none/c"); + private FieldEntry m_nameField = new FieldEntry(m_baseClass, "a"); + private FieldEntry m_numThingsField = new FieldEntry(m_subClassB, "a"); - public TestJarIndexInheritanceTree( ) - throws Exception - { + public TestJarIndexInheritanceTree() throws Exception { m_index = new JarIndex(); - m_index.indexJar( new JarFile( "build/libs/testInheritanceTree.obf.jar" ), false ); + m_index.indexJar(new JarFile("build/libs/testInheritanceTree.obf.jar"), false); } @Test - public void obfEntries( ) - { - assertThat( m_index.getObfClassEntries(), containsInAnyOrder( - newClass( "cuchaz/enigma/inputs/Keep" ), + public void obfEntries() { + assertThat(m_index.getObfClassEntries(), containsInAnyOrder( + newClass("cuchaz/enigma/inputs/Keep"), m_baseClass, m_subClassA, m_subClassAA, m_subClassB - ) ); + )); } @Test - public void translationIndex( ) - { + public void translationIndex() { + TranslationIndex index = m_index.getTranslationIndex(); // base class - assertThat( index.getSuperclassName( m_baseClass.getName() ), is( nullValue() ) ); - assertThat( index.getAncestry( m_baseClass.getName() ), is( empty() ) ); - assertThat( index.getSubclassNames( m_baseClass.getName() ), containsInAnyOrder( + assertThat(index.getSuperclassName(m_baseClass.getName()), is(nullValue())); + assertThat(index.getAncestry(m_baseClass.getName()), is(empty())); + assertThat(index.getSubclassNames(m_baseClass.getName()), containsInAnyOrder( m_subClassA.getName(), m_subClassB.getName() - ) ); + )); // subclass a - assertThat( index.getSuperclassName( m_subClassA.getName() ), is( m_baseClass.getName() ) ); - assertThat( index.getAncestry( m_subClassA.getName() ), contains( m_baseClass.getName() ) ); - assertThat( index.getSubclassNames( m_subClassA.getName() ), contains( m_subClassAA.getName() ) ); + assertThat(index.getSuperclassName(m_subClassA.getName()), is(m_baseClass.getName())); + assertThat(index.getAncestry(m_subClassA.getName()), contains(m_baseClass.getName())); + assertThat(index.getSubclassNames(m_subClassA.getName()), contains(m_subClassAA.getName())); // subclass aa - assertThat( index.getSuperclassName( m_subClassAA.getName() ), is( m_subClassA.getName() ) ); - assertThat( index.getAncestry( m_subClassAA.getName() ), contains( - m_subClassA.getName(), - m_baseClass.getName() - ) ); - assertThat( index.getSubclassNames( m_subClassAA.getName() ), is( empty() ) ); + assertThat(index.getSuperclassName(m_subClassAA.getName()), is(m_subClassA.getName())); + assertThat(index.getAncestry(m_subClassAA.getName()), contains(m_subClassA.getName(), m_baseClass.getName())); + assertThat(index.getSubclassNames(m_subClassAA.getName()), is(empty())); // subclass b - assertThat( index.getSuperclassName( m_subClassB.getName() ), is( m_baseClass.getName() ) ); - assertThat( index.getAncestry( m_subClassB.getName() ), contains( m_baseClass.getName() ) ); - assertThat( index.getSubclassNames( m_subClassB.getName() ), is( empty() ) ); + assertThat(index.getSuperclassName(m_subClassB.getName()), is(m_baseClass.getName())); + assertThat(index.getAncestry(m_subClassB.getName()), contains(m_baseClass.getName())); + assertThat(index.getSubclassNames(m_subClassB.getName()), is(empty())); } @Test - public void access( ) - { - assertThat( m_index.getAccess( m_nameField ), is( Access.Private ) ); - assertThat( m_index.getAccess( m_numThingsField ), is( Access.Private ) ); + public void access() { + assertThat(m_index.getAccess(m_nameField), is(Access.Private)); + assertThat(m_index.getAccess(m_numThingsField), is(Access.Private)); } @Test - public void relatedMethodImplementations( ) - { + public void relatedMethodImplementations() { + Set entries; // getName() - entries = m_index.getRelatedMethodImplementations( new MethodEntry( m_baseClass, "a", "()Ljava/lang/String;" ) ); - assertThat( entries, containsInAnyOrder( - new MethodEntry( m_baseClass, "a", "()Ljava/lang/String;" ), - new MethodEntry( m_subClassAA, "a", "()Ljava/lang/String;" ) - ) ); - entries = m_index.getRelatedMethodImplementations( new MethodEntry( m_subClassAA, "a", "()Ljava/lang/String;" ) ); - assertThat( entries, containsInAnyOrder( - new MethodEntry( m_baseClass, "a", "()Ljava/lang/String;" ), - new MethodEntry( m_subClassAA, "a", "()Ljava/lang/String;" ) - ) ); + entries = m_index.getRelatedMethodImplementations(new MethodEntry(m_baseClass, "a", "()Ljava/lang/String;")); + assertThat(entries, containsInAnyOrder( + new MethodEntry(m_baseClass, "a", "()Ljava/lang/String;"), + new MethodEntry(m_subClassAA, "a", "()Ljava/lang/String;") + )); + entries = m_index.getRelatedMethodImplementations(new MethodEntry(m_subClassAA, "a", "()Ljava/lang/String;")); + assertThat(entries, containsInAnyOrder( + new MethodEntry(m_baseClass, "a", "()Ljava/lang/String;"), + new MethodEntry(m_subClassAA, "a", "()Ljava/lang/String;") + )); // doBaseThings() - entries = m_index.getRelatedMethodImplementations( new MethodEntry( m_baseClass, "a", "()V" ) ); - assertThat( entries, containsInAnyOrder( - new MethodEntry( m_baseClass, "a", "()V" ), - new MethodEntry( m_subClassAA, "a", "()V" ), - new MethodEntry( m_subClassB, "a", "()V" ) - ) ); - entries = m_index.getRelatedMethodImplementations( new MethodEntry( m_subClassAA, "a", "()V" ) ); - assertThat( entries, containsInAnyOrder( - new MethodEntry( m_baseClass, "a", "()V" ), - new MethodEntry( m_subClassAA, "a", "()V" ), - new MethodEntry( m_subClassB, "a", "()V" ) - ) ); - entries = m_index.getRelatedMethodImplementations( new MethodEntry( m_subClassB, "a", "()V" ) ); - assertThat( entries, containsInAnyOrder( - new MethodEntry( m_baseClass, "a", "()V" ), - new MethodEntry( m_subClassAA, "a", "()V" ), - new MethodEntry( m_subClassB, "a", "()V" ) - ) ); + entries = m_index.getRelatedMethodImplementations(new MethodEntry(m_baseClass, "a", "()V")); + assertThat(entries, containsInAnyOrder( + new MethodEntry(m_baseClass, "a", "()V"), + new MethodEntry(m_subClassAA, "a", "()V"), + new MethodEntry(m_subClassB, "a", "()V") + )); + entries = m_index.getRelatedMethodImplementations(new MethodEntry(m_subClassAA, "a", "()V")); + assertThat(entries, containsInAnyOrder( + new MethodEntry(m_baseClass, "a", "()V"), + new MethodEntry(m_subClassAA, "a", "()V"), + new MethodEntry(m_subClassB, "a", "()V") + )); + entries = m_index.getRelatedMethodImplementations(new MethodEntry(m_subClassB, "a", "()V")); + assertThat(entries, containsInAnyOrder( + new MethodEntry(m_baseClass, "a", "()V"), + new MethodEntry(m_subClassAA, "a", "()V"), + new MethodEntry(m_subClassB, "a", "()V") + )); // doBThings - entries = m_index.getRelatedMethodImplementations( new MethodEntry( m_subClassB, "b", "()V" ) ); - assertThat( entries, containsInAnyOrder( - new MethodEntry( m_subClassB, "b", "()V" ) - ) ); + entries = m_index.getRelatedMethodImplementations(new MethodEntry(m_subClassB, "b", "()V")); + assertThat(entries, containsInAnyOrder(new MethodEntry(m_subClassB, "b", "()V"))); } @Test - @SuppressWarnings( "unchecked" ) - public void fieldReferences( ) - { + @SuppressWarnings("unchecked") + public void fieldReferences() { Collection> references; // name - references = m_index.getFieldReferences( m_nameField ); - assertThat( references, containsInAnyOrder( - newFieldReferenceByConstructor( m_nameField, m_baseClass.getName(), "(Ljava/lang/String;)V" ), - newFieldReferenceByMethod( m_nameField, m_baseClass.getName(), "a", "()Ljava/lang/String;" ) - ) ); + references = m_index.getFieldReferences(m_nameField); + assertThat(references, containsInAnyOrder( + newFieldReferenceByConstructor(m_nameField, m_baseClass.getName(), "(Ljava/lang/String;)V"), + newFieldReferenceByMethod(m_nameField, m_baseClass.getName(), "a", "()Ljava/lang/String;") + )); // numThings - references = m_index.getFieldReferences( m_numThingsField ); - assertThat( references, containsInAnyOrder( - newFieldReferenceByConstructor( m_numThingsField, m_subClassB.getName(), "()V" ), - newFieldReferenceByMethod( m_numThingsField, m_subClassB.getName(), "b", "()V" ) - ) ); + references = m_index.getFieldReferences(m_numThingsField); + assertThat(references, containsInAnyOrder( + newFieldReferenceByConstructor(m_numThingsField, m_subClassB.getName(), "()V"), + newFieldReferenceByMethod(m_numThingsField, m_subClassB.getName(), "b", "()V") + )); } @Test - @SuppressWarnings( "unchecked" ) - public void behaviorReferences( ) - { + @SuppressWarnings("unchecked") + public void behaviorReferences() { + BehaviorEntry source; Collection> references; // baseClass constructor - source = new ConstructorEntry( m_baseClass, "(Ljava/lang/String;)V" ); - references = m_index.getBehaviorReferences( source ); - assertThat( references, containsInAnyOrder( - newBehaviorReferenceByConstructor( source, m_subClassA.getName(), "(Ljava/lang/String;)V" ), - newBehaviorReferenceByConstructor( source, m_subClassB.getName(), "()V" ) - ) ); + source = new ConstructorEntry(m_baseClass, "(Ljava/lang/String;)V"); + references = m_index.getBehaviorReferences(source); + assertThat(references, containsInAnyOrder( + newBehaviorReferenceByConstructor(source, m_subClassA.getName(), "(Ljava/lang/String;)V"), + newBehaviorReferenceByConstructor(source, m_subClassB.getName(), "()V") + )); // subClassA constructor - source = new ConstructorEntry( m_subClassA, "(Ljava/lang/String;)V" ); - references = m_index.getBehaviorReferences( source ); - assertThat( references, containsInAnyOrder( - newBehaviorReferenceByConstructor( source, m_subClassAA.getName(), "()V" ) - ) ); + source = new ConstructorEntry(m_subClassA, "(Ljava/lang/String;)V"); + references = m_index.getBehaviorReferences(source); + assertThat(references, containsInAnyOrder( + newBehaviorReferenceByConstructor(source, m_subClassAA.getName(), "()V") + )); // baseClass.getName() - source = new MethodEntry( m_baseClass, "a", "()Ljava/lang/String;" ); - references = m_index.getBehaviorReferences( source ); - assertThat( references, containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_subClassAA.getName(), "a", "()Ljava/lang/String;" ), - newBehaviorReferenceByMethod( source, m_subClassB.getName(), "a", "()V" ) - ) ); + source = new MethodEntry(m_baseClass, "a", "()Ljava/lang/String;"); + references = m_index.getBehaviorReferences(source); + assertThat(references, containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_subClassAA.getName(), "a", "()Ljava/lang/String;"), + newBehaviorReferenceByMethod(source, m_subClassB.getName(), "a", "()V") + )); // subclassAA.getName() - source = new MethodEntry( m_subClassAA, "a", "()Ljava/lang/String;" ); - references = m_index.getBehaviorReferences( source ); - assertThat( references, containsInAnyOrder( - newBehaviorReferenceByMethod( source, m_subClassAA.getName(), "a", "()V" ) - ) ); + source = new MethodEntry(m_subClassAA, "a", "()Ljava/lang/String;"); + references = m_index.getBehaviorReferences(source); + assertThat(references, containsInAnyOrder( + newBehaviorReferenceByMethod(source, m_subClassAA.getName(), "a", "()V") + )); } @Test - public void containsEntries( ) - { + public void containsEntries() { + // classes - assertThat( m_index.containsObfClass( m_baseClass ), is( true ) ); - assertThat( m_index.containsObfClass( m_subClassA ), is( true ) ); - assertThat( m_index.containsObfClass( m_subClassAA ), is( true ) ); - assertThat( m_index.containsObfClass( m_subClassB ), is( true ) ); + assertThat(m_index.containsObfClass(m_baseClass), is(true)); + assertThat(m_index.containsObfClass(m_subClassA), is(true)); + assertThat(m_index.containsObfClass(m_subClassAA), is(true)); + assertThat(m_index.containsObfClass(m_subClassB), is(true)); // fields - assertThat( m_index.containsObfField( m_nameField ), is( true ) ); - assertThat( m_index.containsObfField( m_numThingsField ), is( true ) ); + assertThat(m_index.containsObfField(m_nameField), is(true)); + assertThat(m_index.containsObfField(m_numThingsField), is(true)); // methods // getName() - assertThat( m_index.containsObfBehavior( new MethodEntry( m_baseClass, "a", "()Ljava/lang/String;" ) ), is( true ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassA, "a", "()Ljava/lang/String;" ) ), is( false ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassAA, "a", "()Ljava/lang/String;" ) ), is( true ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassB, "a", "()Ljava/lang/String;" ) ), is( false ) ); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_baseClass, "a", "()Ljava/lang/String;")), is(true)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassA, "a", "()Ljava/lang/String;")), is(false)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassAA, "a", "()Ljava/lang/String;")), is(true)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassB, "a", "()Ljava/lang/String;")), is(false)); // doBaseThings() - assertThat( m_index.containsObfBehavior( new MethodEntry( m_baseClass, "a", "()V" ) ), is( true ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassA, "a", "()V" ) ), is( false ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassAA, "a", "()V" ) ), is( true ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassB, "a", "()V" ) ), is( true ) ); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_baseClass, "a", "()V")), is(true)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassA, "a", "()V")), is(false)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassAA, "a", "()V")), is(true)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassB, "a", "()V")), is(true)); // doBThings() - assertThat( m_index.containsObfBehavior( new MethodEntry( m_baseClass, "b", "()V" ) ), is( false ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassA, "b", "()V" ) ), is( false ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassAA, "b", "()V" ) ), is( false ) ); - assertThat( m_index.containsObfBehavior( new MethodEntry( m_subClassB, "b", "()V" ) ), is( true ) ); - + assertThat(m_index.containsObfBehavior(new MethodEntry(m_baseClass, "b", "()V")), is(false)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassA, "b", "()V")), is(false)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassAA, "b", "()V")), is(false)); + assertThat(m_index.containsObfBehavior(new MethodEntry(m_subClassB, "b", "()V")), is(true)); + } } diff --git a/test/cuchaz/enigma/TestJarIndexLoneClass.java b/test/cuchaz/enigma/TestJarIndexLoneClass.java index e2a87d0..0575eec 100644 --- a/test/cuchaz/enigma/TestJarIndexLoneClass.java +++ b/test/cuchaz/enigma/TestJarIndexLoneClass.java @@ -33,154 +33,136 @@ import cuchaz.enigma.mapping.FieldEntry; import cuchaz.enigma.mapping.MethodEntry; import cuchaz.enigma.mapping.Translator; -public class TestJarIndexLoneClass -{ +public class TestJarIndexLoneClass { + private JarIndex m_index; - public TestJarIndexLoneClass( ) - throws Exception - { + public TestJarIndexLoneClass() throws Exception { m_index = new JarIndex(); - m_index.indexJar( new JarFile( "build/libs/testLoneClass.obf.jar" ), false ); + m_index.indexJar(new JarFile("build/libs/testLoneClass.obf.jar"), false); } @Test - public void obfEntries( ) - { - assertThat( m_index.getObfClassEntries(), containsInAnyOrder( - newClass( "cuchaz/enigma/inputs/Keep" ), - newClass( "none/a" ) - ) ); + public void obfEntries() { + assertThat(m_index.getObfClassEntries(), containsInAnyOrder( + newClass("cuchaz/enigma/inputs/Keep"), + newClass("none/a") + )); } @Test - public void translationIndex( ) - { - assertThat( m_index.getTranslationIndex().getSuperclassName( "none/a" ), is( nullValue() ) ); - assertThat( m_index.getTranslationIndex().getSuperclassName( "cuchaz/enigma/inputs/Keep" ), is( nullValue() ) ); - assertThat( m_index.getTranslationIndex().getAncestry( "none/a" ), is( empty() ) ); - assertThat( m_index.getTranslationIndex().getAncestry( "cuchaz/enigma/inputs/Keep" ), is( empty() ) ); - assertThat( m_index.getTranslationIndex().getSubclassNames( "none/a" ), is( empty() ) ); - assertThat( m_index.getTranslationIndex().getSubclassNames( "cuchaz/enigma/inputs/Keep" ), is( empty() ) ); + public void translationIndex() { + assertThat(m_index.getTranslationIndex().getSuperclassName("none/a"), is(nullValue())); + assertThat(m_index.getTranslationIndex().getSuperclassName("cuchaz/enigma/inputs/Keep"), is(nullValue())); + assertThat(m_index.getTranslationIndex().getAncestry("none/a"), is(empty())); + assertThat(m_index.getTranslationIndex().getAncestry("cuchaz/enigma/inputs/Keep"), is(empty())); + assertThat(m_index.getTranslationIndex().getSubclassNames("none/a"), is(empty())); + assertThat(m_index.getTranslationIndex().getSubclassNames("cuchaz/enigma/inputs/Keep"), is(empty())); } @Test - public void access( ) - { - assertThat( m_index.getAccess( newField( "none/a", "a" ) ), is( Access.Private ) ); - assertThat( m_index.getAccess( newMethod( "none/a", "a", "()Ljava/lang/String;" ) ), is( Access.Public ) ); - assertThat( m_index.getAccess( newField( "none/a", "b" ) ), is( nullValue() ) ); + public void access() { + assertThat(m_index.getAccess(newField("none/a", "a")), is(Access.Private)); + assertThat(m_index.getAccess(newMethod("none/a", "a", "()Ljava/lang/String;")), is(Access.Public)); + assertThat(m_index.getAccess(newField("none/a", "b")), is(nullValue())); } @Test - public void classInheritance( ) - { - ClassInheritanceTreeNode node = m_index.getClassInheritance( new Translator(), newClass( "none/a" ) ); - assertThat( node, is( not( nullValue() ) ) ); - assertThat( node.getObfClassName(), is( "none/a" ) ); - assertThat( node.getChildCount(), is( 0 ) ); + public void classInheritance() { + ClassInheritanceTreeNode node = m_index.getClassInheritance(new Translator(), newClass("none/a")); + assertThat(node, is(not(nullValue()))); + assertThat(node.getObfClassName(), is("none/a")); + assertThat(node.getChildCount(), is(0)); } - + @Test - public void methodInheritance( ) - { - MethodEntry source = newMethod( "none/a", "a", "()Ljava/lang/String;" ); - MethodInheritanceTreeNode node = m_index.getMethodInheritance( new Translator(), source ); - assertThat( node, is( not( nullValue() ) ) ); - assertThat( node.getMethodEntry(), is( source ) ); - assertThat( node.getChildCount(), is( 0 ) ); + public void methodInheritance() { + MethodEntry source = newMethod("none/a", "a", "()Ljava/lang/String;"); + MethodInheritanceTreeNode node = m_index.getMethodInheritance(new Translator(), source); + assertThat(node, is(not(nullValue()))); + assertThat(node.getMethodEntry(), is(source)); + assertThat(node.getChildCount(), is(0)); } @Test - public void classImplementations( ) - { - ClassImplementationsTreeNode node = m_index.getClassImplementations( new Translator(), newClass( "none/a" ) ); - assertThat( node, is( nullValue() ) ); + public void classImplementations() { + ClassImplementationsTreeNode node = m_index.getClassImplementations(new Translator(), newClass("none/a")); + assertThat(node, is(nullValue())); } @Test - public void methodImplementations( ) - { - MethodEntry source = newMethod( "none/a", "a", "()Ljava/lang/String;" ); - MethodImplementationsTreeNode node = m_index.getMethodImplementations( new Translator(), source ); - assertThat( node, is( nullValue() ) ); + public void methodImplementations() { + MethodEntry source = newMethod("none/a", "a", "()Ljava/lang/String;"); + MethodImplementationsTreeNode node = m_index.getMethodImplementations(new Translator(), source); + assertThat(node, is(nullValue())); } @Test - public void relatedMethodImplementations( ) - { - Set entries = m_index.getRelatedMethodImplementations( newMethod( "none/a", "a", "()Ljava/lang/String;" ) ); - assertThat( entries, containsInAnyOrder( newMethod( "none/a", "a", "()Ljava/lang/String;" ) ) ); + public void relatedMethodImplementations() { + Set entries = m_index.getRelatedMethodImplementations(newMethod("none/a", "a", "()Ljava/lang/String;")); + assertThat(entries, containsInAnyOrder( + newMethod("none/a", "a", "()Ljava/lang/String;") + )); } @Test - @SuppressWarnings( "unchecked" ) - public void fieldReferences( ) - { - FieldEntry source = newField( "none/a", "a" ); - Collection> references = m_index.getFieldReferences( source ); - assertThat( references, containsInAnyOrder( - newFieldReferenceByConstructor( source, "none/a", "(Ljava/lang/String;)V" ), - newFieldReferenceByMethod( source, "none/a", "a", "()Ljava/lang/String;" ) - ) ); + @SuppressWarnings("unchecked") + public void fieldReferences() { + FieldEntry source = newField("none/a", "a"); + Collection> references = m_index.getFieldReferences(source); + assertThat(references, containsInAnyOrder( + newFieldReferenceByConstructor(source, "none/a", "(Ljava/lang/String;)V"), + newFieldReferenceByMethod(source, "none/a", "a", "()Ljava/lang/String;") + )); } @Test - public void behaviorReferences( ) - { - assertThat( m_index.getBehaviorReferences( newMethod( "none/a", "a", "()Ljava/lang/String;" ) ), is( empty() ) ); + public void behaviorReferences() { + assertThat(m_index.getBehaviorReferences(newMethod("none/a", "a", "()Ljava/lang/String;")), is(empty())); } @Test - public void innerClasses( ) - { - assertThat( m_index.getInnerClasses( "none/a" ), is( empty() ) ); + public void innerClasses() { + assertThat(m_index.getInnerClasses("none/a"), is(empty())); } @Test - public void outerClass( ) - { - assertThat( m_index.getOuterClass( "a" ), is( nullValue() ) ); + public void outerClass() { + assertThat(m_index.getOuterClass("a"), is(nullValue())); } @Test - public void isAnonymousClass( ) - { - assertThat( m_index.isAnonymousClass( "none/a" ), is( false ) ); + public void isAnonymousClass() { + assertThat(m_index.isAnonymousClass("none/a"), is(false)); } @Test - public void interfaces( ) - { - assertThat( m_index.getInterfaces( "none/a" ), is( empty() ) ); + public void interfaces() { + assertThat(m_index.getInterfaces("none/a"), is(empty())); } @Test - public void implementingClasses( ) - { - assertThat( m_index.getImplementingClasses( "none/a" ), is( empty() ) ); + public void implementingClasses() { + assertThat(m_index.getImplementingClasses("none/a"), is(empty())); } @Test - public void isInterface( ) - { - assertThat( m_index.isInterface( "none/a" ), is( false ) ); + public void isInterface() { + assertThat(m_index.isInterface("none/a"), is(false)); } @Test - public void bridgeMethods( ) - { - assertThat( m_index.getBridgeMethod( newMethod( "none/a", "a", "()Ljava/lang/String;" ) ), is( nullValue() ) ); + public void bridgeMethods() { + assertThat(m_index.getBridgeMethod(newMethod("none/a", "a", "()Ljava/lang/String;")), is(nullValue())); } @Test - public void contains( ) - { - assertThat( m_index.containsObfClass( newClass( "none/a" ) ), is( true ) ); - assertThat( m_index.containsObfClass( newClass( "none/b" ) ), is( false ) ); - assertThat( m_index.containsObfField( newField( "none/a", "a" ) ), is( true ) ); - assertThat( m_index.containsObfField( newField( "none/a", "b" ) ), is( false ) ); - assertThat( m_index.containsObfBehavior( newMethod( "none/a", "a", "()Ljava/lang/String;" ) ), is( true ) ); - assertThat( m_index.containsObfBehavior( newMethod( "none/a", "b", "()Ljava/lang/String;" ) ), is( false ) ); + public void contains() { + assertThat(m_index.containsObfClass(newClass("none/a")), is(true)); + assertThat(m_index.containsObfClass(newClass("none/b")), is(false)); + assertThat(m_index.containsObfField(newField("none/a", "a")), is(true)); + assertThat(m_index.containsObfField(newField("none/a", "b")), is(false)); + assertThat(m_index.containsObfBehavior(newMethod("none/a", "a", "()Ljava/lang/String;")), is(true)); + assertThat(m_index.containsObfBehavior(newMethod("none/a", "b", "()Ljava/lang/String;")), is(false)); } } diff --git a/test/cuchaz/enigma/TestSourceIndex.java b/test/cuchaz/enigma/TestSourceIndex.java index dc6ca7e..fb385e0 100644 --- a/test/cuchaz/enigma/TestSourceIndex.java +++ b/test/cuchaz/enigma/TestSourceIndex.java @@ -21,35 +21,27 @@ import com.strobel.decompiler.languages.java.ast.CompilationUnit; import cuchaz.enigma.mapping.ClassEntry; -public class TestSourceIndex -{ +public class TestSourceIndex { + @Test - public void indexEverything( ) - throws Exception - { - Deobfuscator deobfuscator = new Deobfuscator( new File( "input/1.8.jar" ) ); + public void indexEverything() throws Exception { + Deobfuscator deobfuscator = new Deobfuscator(new File("input/1.8.jar")); // get all classes that aren't inner classes Set classEntries = Sets.newHashSet(); - for( ClassEntry obfClassEntry : deobfuscator.getJarIndex().getObfClassEntries() ) - { - if( !obfClassEntry.isInnerClass() ) - { - classEntries.add( obfClassEntry ); + for (ClassEntry obfClassEntry : deobfuscator.getJarIndex().getObfClassEntries()) { + if (!obfClassEntry.isInnerClass()) { + classEntries.add(obfClassEntry); } } - for( ClassEntry obfClassEntry : classEntries ) - { - try - { - CompilationUnit tree = deobfuscator.getSourceTree( obfClassEntry.getName() ); - String source = deobfuscator.getSource( tree ); - deobfuscator.getSourceIndex( tree, source ); - } - catch( Throwable t ) - { - throw new Error( "Unable to index " + obfClassEntry, t ); + for (ClassEntry obfClassEntry : classEntries) { + try { + CompilationUnit tree = deobfuscator.getSourceTree(obfClassEntry.getName()); + String source = deobfuscator.getSource(tree); + deobfuscator.getSourceIndex(tree, source); + } catch (Throwable t) { + throw new Error("Unable to index " + obfClassEntry, t); } } } diff --git a/test/cuchaz/enigma/TestTokensConstructors.java b/test/cuchaz/enigma/TestTokensConstructors.java index 2409153..f805a65 100644 --- a/test/cuchaz/enigma/TestTokensConstructors.java +++ b/test/cuchaz/enigma/TestTokensConstructors.java @@ -24,129 +24,116 @@ import org.junit.Test; import cuchaz.enigma.mapping.BehaviorEntry; -public class TestTokensConstructors extends TokenChecker -{ - public TestTokensConstructors( ) - throws Exception - { - super( new File( "build/libs/testConstructors.obf.jar" ) ); +public class TestTokensConstructors extends TokenChecker { + + public TestTokensConstructors() throws Exception { + super(new File("build/libs/testConstructors.obf.jar")); } @Test - public void baseDeclarations( ) - { - assertThat( getDeclarationToken( newConstructor( "none/a", "()V" ) ), is( "a" ) ); - assertThat( getDeclarationToken( newConstructor( "none/a", "(I)V" ) ), is( "a" ) ); + public void baseDeclarations() { + assertThat(getDeclarationToken(newConstructor("none/a", "()V")), is("a")); + assertThat(getDeclarationToken(newConstructor("none/a", "(I)V")), is("a")); } @Test - public void subDeclarations( ) - { - assertThat( getDeclarationToken( newConstructor( "none/d", "()V" ) ), is( "d" ) ); - assertThat( getDeclarationToken( newConstructor( "none/d", "(I)V" ) ), is( "d" ) ); - assertThat( getDeclarationToken( newConstructor( "none/d", "(II)V" ) ), is( "d" ) ); - assertThat( getDeclarationToken( newConstructor( "none/d", "(III)V" ) ), is( "d" ) ); + public void subDeclarations() { + assertThat(getDeclarationToken(newConstructor("none/d", "()V")), is("d")); + assertThat(getDeclarationToken(newConstructor("none/d", "(I)V")), is("d")); + assertThat(getDeclarationToken(newConstructor("none/d", "(II)V")), is("d")); + assertThat(getDeclarationToken(newConstructor("none/d", "(III)V")), is("d")); } @Test - public void subsubDeclarations( ) - { - assertThat( getDeclarationToken( newConstructor( "none/e", "(I)V" ) ), is( "e" ) ); + public void subsubDeclarations() { + assertThat(getDeclarationToken(newConstructor("none/e", "(I)V")), is("e")); } @Test - public void defaultDeclarations( ) - { - assertThat( getDeclarationToken( newConstructor( "none/c", "()V" ) ), nullValue() ); + public void defaultDeclarations() { + assertThat(getDeclarationToken(newConstructor("none/c", "()V")), nullValue()); } @Test - public void baseDefaultReferences( ) - { - BehaviorEntry source = newConstructor( "none/a", "()V" ); + public void baseDefaultReferences() { + BehaviorEntry source = newConstructor("none/a", "()V"); assertThat( - getReferenceTokens( newBehaviorReferenceByMethod( source, "none/b", "a", "()V" ) ), - containsInAnyOrder( "a" ) + getReferenceTokens(newBehaviorReferenceByMethod(source, "none/b", "a", "()V")), + containsInAnyOrder("a") ); assertThat( - getReferenceTokens( newBehaviorReferenceByConstructor( source, "none/d", "()V" ) ), - containsInAnyOrder( "super" ) // implicit call, decompiled to "super" + getReferenceTokens(newBehaviorReferenceByConstructor(source, "none/d", "()V")), + containsInAnyOrder("super") // implicit call, decompiled to "super" ); assertThat( - getReferenceTokens( newBehaviorReferenceByConstructor( source, "none/d", "(III)V" ) ), - containsInAnyOrder( "super" ) // implicit call, decompiled to "super" + getReferenceTokens(newBehaviorReferenceByConstructor(source, "none/d", "(III)V")), + containsInAnyOrder("super") // implicit call, decompiled to "super" ); } @Test - public void baseIntReferences( ) - { - BehaviorEntry source = newConstructor( "none/a", "(I)V" ); + public void baseIntReferences() { + BehaviorEntry source = newConstructor("none/a", "(I)V"); assertThat( - getReferenceTokens( newBehaviorReferenceByMethod( source, "none/b", "b", "()V" ) ), - containsInAnyOrder( "a" ) + getReferenceTokens(newBehaviorReferenceByMethod(source, "none/b", "b", "()V")), + containsInAnyOrder("a") ); } - + @Test - public void subDefaultReferences( ) - { - BehaviorEntry source = newConstructor( "none/d", "()V" ); + public void subDefaultReferences() { + BehaviorEntry source = newConstructor("none/d", "()V"); assertThat( - getReferenceTokens( newBehaviorReferenceByMethod( source, "none/b", "c", "()V" ) ), - containsInAnyOrder( "d" ) + getReferenceTokens(newBehaviorReferenceByMethod(source, "none/b", "c", "()V")), + containsInAnyOrder("d") ); assertThat( - getReferenceTokens( newBehaviorReferenceByConstructor( source, "none/d", "(I)V" ) ), - containsInAnyOrder( "this" ) + getReferenceTokens(newBehaviorReferenceByConstructor(source, "none/d", "(I)V")), + containsInAnyOrder("this") ); } - + @Test - public void subIntReferences( ) - { - BehaviorEntry source = newConstructor( "none/d", "(I)V" ); - assertThat( - getReferenceTokens( newBehaviorReferenceByMethod( source, "none/b", "d", "()V" ) ), - containsInAnyOrder( "d" ) + public void subIntReferences() { + BehaviorEntry source = newConstructor("none/d", "(I)V"); + assertThat(getReferenceTokens( + newBehaviorReferenceByMethod(source, "none/b", "d", "()V")), + containsInAnyOrder("d") ); - assertThat( - getReferenceTokens( newBehaviorReferenceByConstructor( source, "none/d", "(II)V" ) ), - containsInAnyOrder( "this" ) + assertThat(getReferenceTokens( + newBehaviorReferenceByConstructor(source, "none/d", "(II)V")), + containsInAnyOrder("this") ); - assertThat( - getReferenceTokens( newBehaviorReferenceByConstructor( source, "none/e", "(I)V" ) ), - containsInAnyOrder( "super" ) + assertThat(getReferenceTokens( + newBehaviorReferenceByConstructor(source, "none/e", "(I)V")), + containsInAnyOrder("super") ); } - + @Test - public void subIntIntReferences( ) - { - BehaviorEntry source = newConstructor( "none/d", "(II)V" ); + public void subIntIntReferences() { + BehaviorEntry source = newConstructor("none/d", "(II)V"); assertThat( - getReferenceTokens( newBehaviorReferenceByMethod( source, "none/b", "e", "()V" ) ), - containsInAnyOrder( "d" ) + getReferenceTokens(newBehaviorReferenceByMethod(source, "none/b", "e", "()V")), + containsInAnyOrder("d") ); } - + @Test - public void subsubIntReferences( ) - { - BehaviorEntry source = newConstructor( "none/e", "(I)V" ); + public void subsubIntReferences() { + BehaviorEntry source = newConstructor("none/e", "(I)V"); assertThat( - getReferenceTokens( newBehaviorReferenceByMethod( source, "none/b", "f", "()V" ) ), - containsInAnyOrder( "e" ) + getReferenceTokens(newBehaviorReferenceByMethod(source, "none/b", "f", "()V")), + containsInAnyOrder("e") ); } - + @Test - public void defaultConstructableReferences( ) - { - BehaviorEntry source = newConstructor( "none/c", "()V" ); + public void defaultConstructableReferences() { + BehaviorEntry source = newConstructor("none/c", "()V"); assertThat( - getReferenceTokens( newBehaviorReferenceByMethod( source, "none/b", "g", "()V" ) ), - containsInAnyOrder( "c" ) + getReferenceTokens(newBehaviorReferenceByMethod(source, "none/b", "g", "()V")), + containsInAnyOrder("c") ); } } diff --git a/test/cuchaz/enigma/TokenChecker.java b/test/cuchaz/enigma/TokenChecker.java index c0852f3..524c5ec 100644 --- a/test/cuchaz/enigma/TokenChecker.java +++ b/test/cuchaz/enigma/TokenChecker.java @@ -23,47 +23,41 @@ import cuchaz.enigma.analysis.SourceIndex; import cuchaz.enigma.analysis.Token; import cuchaz.enigma.mapping.Entry; -public class TokenChecker -{ +public class TokenChecker { + private Deobfuscator m_deobfuscator; - - protected TokenChecker( File jarFile ) - throws IOException - { - m_deobfuscator = new Deobfuscator( jarFile ); + + protected TokenChecker(File jarFile) throws IOException { + m_deobfuscator = new Deobfuscator(jarFile); } - protected String getDeclarationToken( Entry entry ) - { + protected String getDeclarationToken(Entry entry) { // decompile the class - CompilationUnit tree = m_deobfuscator.getSourceTree( entry.getClassName() ); + CompilationUnit tree = m_deobfuscator.getSourceTree(entry.getClassName()); // DEBUG - //tree.acceptVisitor( new TreeDumpVisitor( new File( "tree." + entry.getClassName().replace( '/', '.' ) + ".txt" ) ), null ); - String source = m_deobfuscator.getSource( tree ); - SourceIndex index = m_deobfuscator.getSourceIndex( tree, source ); + // tree.acceptVisitor( new TreeDumpVisitor( new File( "tree." + entry.getClassName().replace( '/', '.' ) + ".txt" ) ), null ); + String source = m_deobfuscator.getSource(tree); + SourceIndex index = m_deobfuscator.getSourceIndex(tree, source); // get the token value - Token token = index.getDeclarationToken( entry ); - if( token == null ) - { + Token token = index.getDeclarationToken(entry); + if (token == null) { return null; } - return source.substring( token.start, token.end ); + return source.substring(token.start, token.end); } - @SuppressWarnings( "unchecked" ) - protected Collection getReferenceTokens( EntryReference reference ) - { + @SuppressWarnings("unchecked") + protected Collection getReferenceTokens(EntryReference reference) { // decompile the class - CompilationUnit tree = m_deobfuscator.getSourceTree( reference.context.getClassName() ); - String source = m_deobfuscator.getSource( tree ); - SourceIndex index = m_deobfuscator.getSourceIndex( tree, source ); + CompilationUnit tree = m_deobfuscator.getSourceTree(reference.context.getClassName()); + String source = m_deobfuscator.getSource(tree); + SourceIndex index = m_deobfuscator.getSourceIndex(tree, source); // get the token values List values = Lists.newArrayList(); - for( Token token : index.getReferenceTokens( (EntryReference)reference ) ) - { - values.add( source.substring( token.start, token.end ) ); + for (Token token : index.getReferenceTokens((EntryReference)reference)) { + values.add(source.substring(token.start, token.end)); } return values; } diff --git a/test/cuchaz/enigma/inputs/Keep.java b/test/cuchaz/enigma/inputs/Keep.java index 3c12bae..390e82f 100644 --- a/test/cuchaz/enigma/inputs/Keep.java +++ b/test/cuchaz/enigma/inputs/Keep.java @@ -1,9 +1,7 @@ package cuchaz.enigma.inputs; -public class Keep -{ - public static void main( String[] args ) - { - System.out.println( "Keep me!" ); +public class Keep { + public static void main(String[] args) { + System.out.println("Keep me!"); } } diff --git a/test/cuchaz/enigma/inputs/constructors/BaseClass.java b/test/cuchaz/enigma/inputs/constructors/BaseClass.java index e6d8768..9345308 100644 --- a/test/cuchaz/enigma/inputs/constructors/BaseClass.java +++ b/test/cuchaz/enigma/inputs/constructors/BaseClass.java @@ -1,17 +1,15 @@ package cuchaz.enigma.inputs.constructors; // none/a -public class BaseClass -{ +public class BaseClass { + // ()V - public BaseClass( ) - { - System.out.println( "Default constructor" ); + public BaseClass() { + System.out.println("Default constructor"); } - + // (I)V - public BaseClass( int i ) - { - System.out.println( "Int constructor " + i ); + public BaseClass(int i) { + System.out.println("Int constructor " + i); } } diff --git a/test/cuchaz/enigma/inputs/constructors/Caller.java b/test/cuchaz/enigma/inputs/constructors/Caller.java index b218619..5727875 100644 --- a/test/cuchaz/enigma/inputs/constructors/Caller.java +++ b/test/cuchaz/enigma/inputs/constructors/Caller.java @@ -1,54 +1,47 @@ package cuchaz.enigma.inputs.constructors; // none/b -public class Caller -{ +public class Caller { + // a()V - public void callBaseDefault( ) - { + public void callBaseDefault() { // none/a.()V - System.out.println( new BaseClass() ); + System.out.println(new BaseClass()); } - + // b()V - public void callBaseInt( ) - { + public void callBaseInt() { // none/a.(I)V - System.out.println( new BaseClass( 5 ) ); + System.out.println(new BaseClass(5)); } - + // c()V - public void callSubDefault( ) - { + public void callSubDefault() { // none/d.()V - System.out.println( new SubClass() ); + System.out.println(new SubClass()); } - + // d()V - public void callSubInt( ) - { + public void callSubInt() { // none/d.(I)V - System.out.println( new SubClass( 6 ) ); + System.out.println(new SubClass(6)); } - + // e()V - public void callSubIntInt( ) - { + public void callSubIntInt() { // none/d.(II)V - System.out.println( new SubClass( 4, 2 ) ); + System.out.println(new SubClass(4, 2)); } - + // f()V - public void callSubSubInt( ) - { + public void callSubSubInt() { // none/e.(I)V - System.out.println( new SubSubClass( 3 ) ); + System.out.println(new SubSubClass(3)); } // g()V - public void callDefaultConstructable() - { + public void callDefaultConstructable() { // none/c.()V - System.out.println( new DefaultConstructable() ); + System.out.println(new DefaultConstructable()); } } diff --git a/test/cuchaz/enigma/inputs/constructors/DefaultConstructable.java b/test/cuchaz/enigma/inputs/constructors/DefaultConstructable.java index 6cfd35e..26a3ddb 100644 --- a/test/cuchaz/enigma/inputs/constructors/DefaultConstructable.java +++ b/test/cuchaz/enigma/inputs/constructors/DefaultConstructable.java @@ -1,6 +1,5 @@ package cuchaz.enigma.inputs.constructors; -public class DefaultConstructable -{ +public class DefaultConstructable { // only default constructor } diff --git a/test/cuchaz/enigma/inputs/constructors/SubClass.java b/test/cuchaz/enigma/inputs/constructors/SubClass.java index 6ef7732..fecfa2b 100644 --- a/test/cuchaz/enigma/inputs/constructors/SubClass.java +++ b/test/cuchaz/enigma/inputs/constructors/SubClass.java @@ -1,32 +1,28 @@ package cuchaz.enigma.inputs.constructors; // none/d extends none/a -public class SubClass extends BaseClass -{ +public class SubClass extends BaseClass { + // ()V - public SubClass( ) - { + public SubClass() { // none/a.()V } // (I)V - public SubClass( int num ) - { + public SubClass(int num) { // ()V this(); - System.out.println( "SubClass " + num ); + System.out.println("SubClass " + num); } // (II)V - public SubClass( int a, int b ) - { + public SubClass(int a, int b) { // (I)V - this( a + b ); + this(a + b); } // (III)V - public SubClass( int a, int b, int c ) - { + public SubClass(int a, int b, int c) { // none/a.()V } } diff --git a/test/cuchaz/enigma/inputs/constructors/SubSubClass.java b/test/cuchaz/enigma/inputs/constructors/SubSubClass.java index 76a0f1f..ab84161 100644 --- a/test/cuchaz/enigma/inputs/constructors/SubSubClass.java +++ b/test/cuchaz/enigma/inputs/constructors/SubSubClass.java @@ -1,12 +1,11 @@ package cuchaz.enigma.inputs.constructors; // none/e extends none/d -public class SubSubClass extends SubClass -{ +public class SubSubClass extends SubClass { + // (I)V - public SubSubClass( int i ) - { + public SubSubClass(int i) { // none/c.(I)V - super( i ); + super(i); } } diff --git a/test/cuchaz/enigma/inputs/inheritanceTree/BaseClass.java b/test/cuchaz/enigma/inputs/inheritanceTree/BaseClass.java index 8402dde..5b416c4 100644 --- a/test/cuchaz/enigma/inputs/inheritanceTree/BaseClass.java +++ b/test/cuchaz/enigma/inputs/inheritanceTree/BaseClass.java @@ -1,23 +1,21 @@ package cuchaz.enigma.inputs.inheritanceTree; // none/a -public abstract class BaseClass -{ +public abstract class BaseClass { + // a private String m_name; // (Ljava/lang/String;)V - protected BaseClass( String name ) - { + protected BaseClass(String name) { m_name = name; } // a()Ljava/lang/String; - public String getName( ) - { + public String getName() { return m_name; } // a()V - public abstract void doBaseThings( ); + public abstract void doBaseThings(); } diff --git a/test/cuchaz/enigma/inputs/inheritanceTree/SubclassA.java b/test/cuchaz/enigma/inputs/inheritanceTree/SubclassA.java index ed50709..7a99d51 100644 --- a/test/cuchaz/enigma/inputs/inheritanceTree/SubclassA.java +++ b/test/cuchaz/enigma/inputs/inheritanceTree/SubclassA.java @@ -1,12 +1,11 @@ package cuchaz.enigma.inputs.inheritanceTree; // none/b extends none/a -public abstract class SubclassA extends BaseClass -{ +public abstract class SubclassA extends BaseClass { + // (Ljava/lang/String;)V - protected SubclassA( String name ) - { + protected SubclassA(String name) { // call to none/a.(Ljava/lang/String)V - super( name ); + super(name); } } diff --git a/test/cuchaz/enigma/inputs/inheritanceTree/SubclassB.java b/test/cuchaz/enigma/inputs/inheritanceTree/SubclassB.java index fc4c8ee..c9485d3 100644 --- a/test/cuchaz/enigma/inputs/inheritanceTree/SubclassB.java +++ b/test/cuchaz/enigma/inputs/inheritanceTree/SubclassB.java @@ -1,16 +1,15 @@ package cuchaz.enigma.inputs.inheritanceTree; // none/c extends none/a -public class SubclassB extends BaseClass -{ +public class SubclassB extends BaseClass { + // a private int m_numThings; // ()V - protected SubclassB( ) - { + protected SubclassB() { // none/a.(Ljava/lang/String;)V - super( "B" ); + super("B"); // access to a m_numThings = 4; @@ -18,16 +17,14 @@ public class SubclassB extends BaseClass @Override // a()V - public void doBaseThings( ) - { + public void doBaseThings() { // call to none/a.a()Ljava/lang/String; - System.out.println( "Base things by B! " + getName() ); + System.out.println("Base things by B! " + getName()); } // b()V - public void doBThings( ) - { + public void doBThings() { // access to a - System.out.println( "" + m_numThings + " B things!" ); + System.out.println("" + m_numThings + " B things!"); } } diff --git a/test/cuchaz/enigma/inputs/inheritanceTree/SubsubclassAA.java b/test/cuchaz/enigma/inputs/inheritanceTree/SubsubclassAA.java index b3b8342..afd03ac 100644 --- a/test/cuchaz/enigma/inputs/inheritanceTree/SubsubclassAA.java +++ b/test/cuchaz/enigma/inputs/inheritanceTree/SubsubclassAA.java @@ -1,27 +1,24 @@ package cuchaz.enigma.inputs.inheritanceTree; // none/d extends none/b -public class SubsubclassAA extends SubclassA -{ - protected SubsubclassAA( ) - { +public class SubsubclassAA extends SubclassA { + + protected SubsubclassAA() { // call to none/b.(Ljava/lang/String;)V - super( "AA" ); + super("AA"); } @Override // a()Ljava/lang/String; - public String getName( ) - { + public String getName() { // call to none/b.a()Ljava/lang/String; return "subsub" + super.getName(); } @Override // a()V - public void doBaseThings( ) - { + public void doBaseThings() { // call to none/d.a()Ljava/lang/String; - System.out.println( "Base things by " + getName() ); + System.out.println("Base things by " + getName()); } } diff --git a/test/cuchaz/enigma/inputs/innerClasses/Anonymous.java b/test/cuchaz/enigma/inputs/innerClasses/Anonymous.java index d36a514..f5d9d1c 100644 --- a/test/cuchaz/enigma/inputs/innerClasses/Anonymous.java +++ b/test/cuchaz/enigma/inputs/innerClasses/Anonymous.java @@ -1,14 +1,11 @@ package cuchaz.enigma.inputs.innerClasses; -public class Anonymous -{ - public void foo( ) - { - Runnable runnable = new Runnable( ) - { +public class Anonymous { + + public void foo() { + Runnable runnable = new Runnable() { @Override - public void run( ) - { + public void run() { // don't care } }; diff --git a/test/cuchaz/enigma/inputs/innerClasses/AnonymousWithScopeArgs.java b/test/cuchaz/enigma/inputs/innerClasses/AnonymousWithScopeArgs.java index e0a65e2..b3ba1af 100644 --- a/test/cuchaz/enigma/inputs/innerClasses/AnonymousWithScopeArgs.java +++ b/test/cuchaz/enigma/inputs/innerClasses/AnonymousWithScopeArgs.java @@ -1,16 +1,13 @@ package cuchaz.enigma.inputs.innerClasses; -public class AnonymousWithScopeArgs -{ - public static void foo( final Simple arg ) - { - System.out.println( new Object( ) - { +public class AnonymousWithScopeArgs { + + public static void foo(final Simple arg) { + System.out.println(new Object() { @Override - public String toString( ) - { + public String toString() { return arg.toString(); } - } ); + }); } } diff --git a/test/cuchaz/enigma/inputs/innerClasses/ConstructorArgs.java b/test/cuchaz/enigma/inputs/innerClasses/ConstructorArgs.java index e24395c..08135fe 100644 --- a/test/cuchaz/enigma/inputs/innerClasses/ConstructorArgs.java +++ b/test/cuchaz/enigma/inputs/innerClasses/ConstructorArgs.java @@ -1,22 +1,20 @@ package cuchaz.enigma.inputs.innerClasses; -@SuppressWarnings( "unused" ) -public class ConstructorArgs -{ - class Inner - { +@SuppressWarnings("unused") +public class ConstructorArgs { + + class Inner { + private int a; - public Inner( int a ) - { + public Inner(int a) { this.a = a; } } Inner i; - public void foo( ) - { - i = new Inner( 5 ); + public void foo() { + i = new Inner(5); } } diff --git a/test/cuchaz/enigma/inputs/innerClasses/Simple.java b/test/cuchaz/enigma/inputs/innerClasses/Simple.java index 405c639..cb536fa 100644 --- a/test/cuchaz/enigma/inputs/innerClasses/Simple.java +++ b/test/cuchaz/enigma/inputs/innerClasses/Simple.java @@ -1,9 +1,8 @@ package cuchaz.enigma.inputs.innerClasses; -public class Simple -{ - class Inner - { +public class Simple { + + class Inner { // nothing to do } } diff --git a/test/cuchaz/enigma/inputs/loneClass/LoneClass.java b/test/cuchaz/enigma/inputs/loneClass/LoneClass.java index 961b012..18c716e 100644 --- a/test/cuchaz/enigma/inputs/loneClass/LoneClass.java +++ b/test/cuchaz/enigma/inputs/loneClass/LoneClass.java @@ -1,16 +1,14 @@ package cuchaz.enigma.inputs.loneClass; -public class LoneClass -{ +public class LoneClass { + private String m_name; - public LoneClass( String name ) - { + public LoneClass(String name) { m_name = name; } - public String getName( ) - { + public String getName() { return m_name; } } -- cgit v1.2.3