summaryrefslogtreecommitdiff
path: root/src/cuchaz/enigma/convert/ClassMatcher.java
diff options
context:
space:
mode:
authorGravatar jeff2015-02-03 22:00:53 -0500
committerGravatar jeff2015-02-03 22:00:53 -0500
commit52ab426d8fad3dbee7e728f523a35af94facebda (patch)
tree146fadfd8e639a909d6c1d6a193e7eddeab0be4a /src/cuchaz/enigma/convert/ClassMatcher.java
downloadenigma-fork-52ab426d8fad3dbee7e728f523a35af94facebda.tar.gz
enigma-fork-52ab426d8fad3dbee7e728f523a35af94facebda.tar.xz
enigma-fork-52ab426d8fad3dbee7e728f523a35af94facebda.zip
oops, don't depend on local procyon project
Diffstat (limited to 'src/cuchaz/enigma/convert/ClassMatcher.java')
-rw-r--r--src/cuchaz/enigma/convert/ClassMatcher.java415
1 files changed, 415 insertions, 0 deletions
diff --git a/src/cuchaz/enigma/convert/ClassMatcher.java b/src/cuchaz/enigma/convert/ClassMatcher.java
new file mode 100644
index 0000000..fc39ed0
--- /dev/null
+++ b/src/cuchaz/enigma/convert/ClassMatcher.java
@@ -0,0 +1,415 @@
1/*******************************************************************************
2 * Copyright (c) 2014 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Public License v3.0
5 * which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/gpl.html
7 *
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import java.io.File;
14import java.io.FileReader;
15import java.io.FileWriter;
16import java.io.IOException;
17import java.util.ArrayList;
18import java.util.Arrays;
19import java.util.Collection;
20import java.util.Collections;
21import java.util.Comparator;
22import java.util.Iterator;
23import java.util.LinkedHashMap;
24import java.util.List;
25import java.util.Map;
26import java.util.Set;
27import java.util.jar.JarFile;
28
29import javassist.CtBehavior;
30import javassist.CtClass;
31
32import com.google.common.collect.ArrayListMultimap;
33import com.google.common.collect.BiMap;
34import com.google.common.collect.HashBiMap;
35import com.google.common.collect.Lists;
36import com.google.common.collect.Maps;
37import com.google.common.collect.Multimap;
38import com.google.common.collect.Sets;
39
40import cuchaz.enigma.TranslatingTypeLoader;
41import cuchaz.enigma.analysis.JarIndex;
42import cuchaz.enigma.convert.ClassNamer.SidedClassNamer;
43import cuchaz.enigma.mapping.ClassEntry;
44import cuchaz.enigma.mapping.ClassMapping;
45import cuchaz.enigma.mapping.MappingParseException;
46import cuchaz.enigma.mapping.Mappings;
47import cuchaz.enigma.mapping.MappingsReader;
48import cuchaz.enigma.mapping.MappingsWriter;
49import cuchaz.enigma.mapping.MethodEntry;
50import cuchaz.enigma.mapping.MethodMapping;
51
52public class ClassMatcher {
53
54 public static void main(String[] args) throws IOException, MappingParseException {
55 // TEMP
56 JarFile sourceJar = new JarFile(new File("input/1.8-pre3.jar"));
57 JarFile destJar = new JarFile(new File("input/1.8.jar"));
58 File inMappingsFile = new File("../Enigma Mappings/1.8-pre3.mappings");
59 File outMappingsFile = new File("../Enigma Mappings/1.8.mappings");
60
61 // define a matching to use when the automated system cannot find a match
62 Map<String,String> fallbackMatching = Maps.newHashMap();
63 fallbackMatching.put("none/ayb", "none/ayf");
64 fallbackMatching.put("none/ayd", "none/ayd");
65 fallbackMatching.put("none/bgk", "unknown/bgk");
66
67 // do the conversion
68 Mappings mappings = new MappingsReader().read(new FileReader(inMappingsFile));
69 convertMappings(sourceJar, destJar, mappings, fallbackMatching);
70
71 // write out the converted mappings
72 FileWriter writer = new FileWriter(outMappingsFile);
73 new MappingsWriter().write(writer, mappings);
74 writer.close();
75 System.out.println("Wrote converted mappings to:\n\t" + outMappingsFile.getAbsolutePath());
76 }
77
78 private static void convertMappings(JarFile sourceJar, JarFile destJar, Mappings mappings, Map<String,String> fallbackMatching) {
79 // index jars
80 System.out.println("Indexing source jar...");
81 JarIndex sourceIndex = new JarIndex();
82 sourceIndex.indexJar(sourceJar, false);
83 System.out.println("Indexing dest jar...");
84 JarIndex destIndex = new JarIndex();
85 destIndex.indexJar(destJar, false);
86 TranslatingTypeLoader sourceLoader = new TranslatingTypeLoader(sourceJar, sourceIndex);
87 TranslatingTypeLoader destLoader = new TranslatingTypeLoader(destJar, destIndex);
88
89 // compute the matching
90 ClassMatching matching = computeMatching(sourceIndex, sourceLoader, destIndex, destLoader);
91 Map<String,Map.Entry<ClassIdentity,List<ClassIdentity>>> matchingIndex = matching.getIndex();
92
93 // get all the obf class names used in the mappings
94 Set<String> usedClassNames = mappings.getAllObfClassNames();
95 Set<String> allClassNames = Sets.newHashSet();
96 for (ClassEntry classEntry : sourceIndex.getObfClassEntries()) {
97 allClassNames.add(classEntry.getName());
98 }
99 usedClassNames.retainAll(allClassNames);
100 System.out.println("Used " + usedClassNames.size() + " classes in the mappings");
101
102 // probabilistically match the non-uniquely-matched source classes
103 for (Map.Entry<ClassIdentity,List<ClassIdentity>> entry : matchingIndex.values()) {
104 ClassIdentity sourceClass = entry.getKey();
105 List<ClassIdentity> destClasses = entry.getValue();
106
107 // skip classes that are uniquely matched
108 if (destClasses.size() == 1) {
109 continue;
110 }
111
112 // skip classes that aren't used in the mappings
113 if (!usedClassNames.contains(sourceClass.getClassEntry().getName())) {
114 continue;
115 }
116
117 System.out.println("No exact match for source class " + sourceClass.getClassEntry());
118
119 // find the closest classes
120 Multimap<Integer,ClassIdentity> scoredMatches = ArrayListMultimap.create();
121 for (ClassIdentity c : destClasses) {
122 scoredMatches.put(sourceClass.getMatchScore(c), c);
123 }
124 List<Integer> scores = new ArrayList<Integer>(scoredMatches.keySet());
125 Collections.sort(scores, Collections.reverseOrder());
126 printScoredMatches(sourceClass.getMaxMatchScore(), scores, scoredMatches);
127
128 // does the best match have a non-zero score and the same name?
129 int bestScore = scores.get(0);
130 Collection<ClassIdentity> bestMatches = scoredMatches.get(bestScore);
131 if (bestScore > 0 && bestMatches.size() == 1) {
132 ClassIdentity bestMatch = bestMatches.iterator().next();
133 if (bestMatch.getClassEntry().equals(sourceClass.getClassEntry())) {
134 // use it
135 System.out.println("\tAutomatically choosing likely match: " + bestMatch.getClassEntry().getName());
136 destClasses.clear();
137 destClasses.add(bestMatch);
138 }
139 }
140 }
141
142 // group the matching into unique and non-unique matches
143 BiMap<String,String> matchedClassNames = HashBiMap.create();
144 Set<String> unmatchedSourceClassNames = Sets.newHashSet();
145 for (String className : usedClassNames) {
146 // is there a match for this class?
147 Map.Entry<ClassIdentity,List<ClassIdentity>> entry = matchingIndex.get(className);
148 ClassIdentity sourceClass = entry.getKey();
149 List<ClassIdentity> matches = entry.getValue();
150
151 if (matches.size() == 1) {
152 // unique match! We're good to go!
153 matchedClassNames.put(sourceClass.getClassEntry().getName(), matches.get(0).getClassEntry().getName());
154 } else {
155 // no match, check the fallback matching
156 String fallbackMatch = fallbackMatching.get(className);
157 if (fallbackMatch != null) {
158 matchedClassNames.put(sourceClass.getClassEntry().getName(), fallbackMatch);
159 } else {
160 unmatchedSourceClassNames.add(className);
161 }
162 }
163 }
164
165 // report unmatched classes
166 if (!unmatchedSourceClassNames.isEmpty()) {
167 System.err.println("ERROR: there were unmatched classes!");
168 for (String className : unmatchedSourceClassNames) {
169 System.err.println("\t" + className);
170 }
171 return;
172 }
173
174 // get the class name changes from the matched class names
175 Map<String,String> classChanges = Maps.newHashMap();
176 for (Map.Entry<String,String> entry : matchedClassNames.entrySet()) {
177 if (!entry.getKey().equals(entry.getValue())) {
178 classChanges.put(entry.getKey(), entry.getValue());
179 System.out.println(String.format("Class change: %s -> %s", entry.getKey(), entry.getValue()));
180 /* DEBUG
181 System.out.println(String.format("\n%s\n%s",
182 new ClassIdentity(sourceLoader.loadClass(entry.getKey()), null, sourceIndex, false, false),
183 new ClassIdentity( destLoader.loadClass(entry.getValue()), null, destIndex, false, false)
184 ));
185 */
186 }
187 }
188
189 // sort the changes so classes are renamed in the correct order
190 // ie. if we have the mappings a->b, b->c, we have to apply b->c before a->b
191 LinkedHashMap<String,String> orderedClassChanges = Maps.newLinkedHashMap();
192 int numChangesLeft = classChanges.size();
193 while (!classChanges.isEmpty()) {
194 Iterator<Map.Entry<String,String>> iter = classChanges.entrySet().iterator();
195 while (iter.hasNext()) {
196 Map.Entry<String,String> entry = iter.next();
197 if (classChanges.get(entry.getValue()) == null) {
198 orderedClassChanges.put(entry.getKey(), entry.getValue());
199 iter.remove();
200 }
201 }
202
203 // did we remove any changes?
204 if (numChangesLeft - classChanges.size() > 0) {
205 // keep going
206 numChangesLeft = classChanges.size();
207 } else {
208 // can't sort anymore. There must be a loop
209 break;
210 }
211 }
212 if (classChanges.size() > 0) {
213 throw new Error(String.format("Unable to sort %d/%d class changes!", classChanges.size(), matchedClassNames.size()));
214 }
215
216 // convert the mappings in the correct class order
217 for (Map.Entry<String,String> entry : orderedClassChanges.entrySet()) {
218 mappings.renameObfClass(entry.getKey(), entry.getValue());
219 }
220
221 // check the method matches
222 System.out.println("Checking methods...");
223 for (ClassMapping classMapping : mappings.classes()) {
224 ClassEntry classEntry = new ClassEntry(classMapping.getObfName());
225 for (MethodMapping methodMapping : classMapping.methods()) {
226
227 // skip constructors
228 if (methodMapping.getObfName().equals("<init>")) {
229 continue;
230 }
231
232 MethodEntry methodEntry = new MethodEntry(
233 classEntry,
234 methodMapping.getObfName(),
235 methodMapping.getObfSignature()
236 );
237 if (!destIndex.containsObfBehavior(methodEntry)) {
238 System.err.println("WARNING: method doesn't match: " + methodEntry);
239
240 // show the available methods
241 System.err.println("\tAvailable dest methods:");
242 CtClass c = destLoader.loadClass(classMapping.getObfName());
243 for (CtBehavior behavior : c.getDeclaredBehaviors()) {
244 MethodEntry declaredMethodEntry = new MethodEntry(
245 new ClassEntry(classMapping.getObfName()),
246 behavior.getName(),
247 behavior.getSignature()
248 );
249 System.err.println("\t\t" + declaredMethodEntry);
250 }
251
252 System.err.println("\tAvailable source methods:");
253 c = sourceLoader.loadClass(matchedClassNames.inverse().get(classMapping.getObfName()));
254 for (CtBehavior behavior : c.getDeclaredBehaviors()) {
255 MethodEntry declaredMethodEntry = new MethodEntry(
256 new ClassEntry(classMapping.getObfName()),
257 behavior.getName(),
258 behavior.getSignature()
259 );
260 System.err.println("\t\t" + declaredMethodEntry);
261 }
262 }
263 }
264 }
265
266 System.out.println("Done!");
267 }
268
269 public static ClassMatching computeMatching(JarIndex sourceIndex, TranslatingTypeLoader sourceLoader, JarIndex destIndex, TranslatingTypeLoader destLoader) {
270
271 System.out.println("Matching classes...");
272
273 ClassMatching matching = null;
274 for (boolean useReferences : Arrays.asList(false, true)) {
275 int numMatches = 0;
276 do {
277 SidedClassNamer sourceNamer = null;
278 SidedClassNamer destNamer = null;
279 if (matching != null) {
280 // build a class namer
281 ClassNamer namer = new ClassNamer(matching.getUniqueMatches());
282 sourceNamer = namer.getSourceNamer();
283 destNamer = namer.getDestNamer();
284
285 // note the number of matches
286 numMatches = matching.getUniqueMatches().size();
287 }
288
289 // get the entries left to match
290 Set<ClassEntry> sourceClassEntries = Sets.newHashSet();
291 Set<ClassEntry> destClassEntries = Sets.newHashSet();
292 if (matching == null) {
293 sourceClassEntries.addAll(sourceIndex.getObfClassEntries());
294 destClassEntries.addAll(destIndex.getObfClassEntries());
295 matching = new ClassMatching();
296 } else {
297 for (Map.Entry<List<ClassIdentity>,List<ClassIdentity>> entry : matching.getAmbiguousMatches().entrySet()) {
298 for (ClassIdentity c : entry.getKey()) {
299 sourceClassEntries.add(c.getClassEntry());
300 matching.removeSource(c);
301 }
302 for (ClassIdentity c : entry.getValue()) {
303 destClassEntries.add(c.getClassEntry());
304 matching.removeDest(c);
305 }
306 }
307 for (ClassIdentity c : matching.getUnmatchedSourceClasses()) {
308 sourceClassEntries.add(c.getClassEntry());
309 matching.removeSource(c);
310 }
311 for (ClassIdentity c : matching.getUnmatchedDestClasses()) {
312 destClassEntries.add(c.getClassEntry());
313 matching.removeDest(c);
314 }
315 }
316
317 // compute a matching for the classes
318 for (ClassEntry classEntry : sourceClassEntries) {
319 CtClass c = sourceLoader.loadClass(classEntry.getName());
320 ClassIdentity sourceClass = new ClassIdentity(c, sourceNamer, sourceIndex, useReferences);
321 matching.addSource(sourceClass);
322 }
323 for (ClassEntry classEntry : destClassEntries) {
324 CtClass c = destLoader.loadClass(classEntry.getName());
325 ClassIdentity destClass = new ClassIdentity(c, destNamer, destIndex, useReferences);
326 matching.matchDestClass(destClass);
327 }
328
329 // TEMP
330 System.out.println(matching);
331 } while (matching.getUniqueMatches().size() - numMatches > 0);
332 }
333
334 // check the class matches
335 System.out.println("Checking class matches...");
336 ClassNamer namer = new ClassNamer(matching.getUniqueMatches());
337 SidedClassNamer sourceNamer = namer.getSourceNamer();
338 SidedClassNamer destNamer = namer.getDestNamer();
339 for (Map.Entry<ClassIdentity,ClassIdentity> entry : matching.getUniqueMatches().entrySet()) {
340
341 // check source
342 ClassIdentity sourceClass = entry.getKey();
343 CtClass sourceC = sourceLoader.loadClass(sourceClass.getClassEntry().getName());
344 assert (sourceC != null) : "Unable to load source class " + sourceClass.getClassEntry();
345 assert (sourceClass.matches(sourceC)) : "Source " + sourceClass + " doesn't match " + new ClassIdentity(sourceC, sourceNamer, sourceIndex, false);
346
347 // check dest
348 ClassIdentity destClass = entry.getValue();
349 CtClass destC = destLoader.loadClass(destClass.getClassEntry().getName());
350 assert (destC != null) : "Unable to load dest class " + destClass.getClassEntry();
351 assert (destClass.matches(destC)) : "Dest " + destClass + " doesn't match " + new ClassIdentity(destC, destNamer, destIndex, false);
352 }
353
354 // warn about the ambiguous matchings
355 List<Map.Entry<List<ClassIdentity>,List<ClassIdentity>>> ambiguousMatches = new ArrayList<Map.Entry<List<ClassIdentity>,List<ClassIdentity>>>(matching.getAmbiguousMatches().entrySet());
356 Collections.sort(ambiguousMatches, new Comparator<Map.Entry<List<ClassIdentity>,List<ClassIdentity>>>() {
357 @Override
358 public int compare(Map.Entry<List<ClassIdentity>,List<ClassIdentity>> a, Map.Entry<List<ClassIdentity>,List<ClassIdentity>> b) {
359 String aName = a.getKey().get(0).getClassEntry().getName();
360 String bName = b.getKey().get(0).getClassEntry().getName();
361 return aName.compareTo(bName);
362 }
363 });
364 for (Map.Entry<List<ClassIdentity>,List<ClassIdentity>> entry : ambiguousMatches) {
365 System.out.println("Ambiguous matching:");
366 System.out.println("\tSource: " + getClassNames(entry.getKey()));
367 System.out.println("\tDest: " + getClassNames(entry.getValue()));
368 }
369
370 /* DEBUG
371 Map.Entry<List<ClassIdentity>,List<ClassIdentity>> entry = ambiguousMatches.get( 7 );
372 for (ClassIdentity c : entry.getKey()) {
373 System.out.println(c);
374 }
375 for(ClassIdentity c : entry.getKey()) {
376 System.out.println(decompile(sourceLoader, c.getClassEntry()));
377 }
378 */
379
380 return matching;
381 }
382
383 private static void printScoredMatches(int maxScore, List<Integer> scores, Multimap<Integer,ClassIdentity> scoredMatches) {
384 int numScoredMatchesShown = 0;
385 for (int score : scores) {
386 for (ClassIdentity scoredMatch : scoredMatches.get(score)) {
387 System.out.println(String.format("\tScore: %3d %3.0f%% %s", score, 100.0 * score / maxScore, scoredMatch.getClassEntry().getName()));
388 if (numScoredMatchesShown++ > 10) {
389 return;
390 }
391 }
392 }
393 }
394
395 private static List<String> getClassNames(Collection<ClassIdentity> classes) {
396 List<String> out = Lists.newArrayList();
397 for (ClassIdentity c : classes) {
398 out.add(c.getClassEntry().getName());
399 }
400 Collections.sort(out);
401 return out;
402 }
403
404 /* DEBUG
405 private static String decompile(TranslatingTypeLoader loader, ClassEntry classEntry) {
406 PlainTextOutput output = new PlainTextOutput();
407 DecompilerSettings settings = DecompilerSettings.javaDefaults();
408 settings.setForceExplicitImports(true);
409 settings.setShowSyntheticMembers(true);
410 settings.setTypeLoader(loader);
411 Decompiler.decompile(classEntry.getName(), output, settings);
412 return output.toString();
413 }
414 */
415}