summaryrefslogtreecommitdiff
path: root/src/main/java/cuchaz/enigma/convert
diff options
context:
space:
mode:
authorGravatar asiekierka2016-08-17 18:35:12 +0200
committerGravatar asiekierka2016-08-17 18:35:12 +0200
commit5540c815de36e316d0749ce2163f12c61895b327 (patch)
tree2b30d5ae98735ee7cba7d1c0087c51d68ed3ebf9 /src/main/java/cuchaz/enigma/convert
parentRevert "Removed util" (diff)
downloadenigma-fork-5540c815de36e316d0749ce2163f12c61895b327.tar.gz
enigma-fork-5540c815de36e316d0749ce2163f12c61895b327.tar.xz
enigma-fork-5540c815de36e316d0749ce2163f12c61895b327.zip
Revert "Removed unused methods"
This reverts commit 1742190f784d0d62e7cc869eebafdfe1927e448f.
Diffstat (limited to 'src/main/java/cuchaz/enigma/convert')
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassForest.java60
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassIdentifier.java56
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassIdentity.java441
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassMatch.java84
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassMatches.java159
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassMatching.java155
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassNamer.java56
-rw-r--r--src/main/java/cuchaz/enigma/convert/FieldMatches.java151
-rw-r--r--src/main/java/cuchaz/enigma/convert/MappingsConverter.java583
-rw-r--r--src/main/java/cuchaz/enigma/convert/MatchesReader.java109
-rw-r--r--src/main/java/cuchaz/enigma/convert/MatchesWriter.java121
-rw-r--r--src/main/java/cuchaz/enigma/convert/MemberMatches.java155
12 files changed, 2130 insertions, 0 deletions
diff --git a/src/main/java/cuchaz/enigma/convert/ClassForest.java b/src/main/java/cuchaz/enigma/convert/ClassForest.java
new file mode 100644
index 0000000..b08d48f
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassForest.java
@@ -0,0 +1,60 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.HashMultimap;
14import com.google.common.collect.Multimap;
15
16import java.util.Collection;
17
18import cuchaz.enigma.mapping.ClassEntry;
19
20
21public class ClassForest {
22
23 private ClassIdentifier identifier;
24 private Multimap<ClassIdentity, ClassEntry> forest;
25
26 public ClassForest(ClassIdentifier identifier) {
27 this.identifier = identifier;
28 this.forest = HashMultimap.create();
29 }
30
31 public void addAll(Iterable<ClassEntry> entries) {
32 for (ClassEntry entry : entries) {
33 add(entry);
34 }
35 }
36
37 public void add(ClassEntry entry) {
38 try {
39 this.forest.put(this.identifier.identify(entry), entry);
40 } catch (ClassNotFoundException ex) {
41 throw new Error("Unable to find class " + entry.getName());
42 }
43 }
44
45 public Collection<ClassIdentity> identities() {
46 return this.forest.keySet();
47 }
48
49 public Collection<ClassEntry> classes() {
50 return this.forest.values();
51 }
52
53 public Collection<ClassEntry> getClasses(ClassIdentity identity) {
54 return this.forest.get(identity);
55 }
56
57 public boolean containsIdentity(ClassIdentity identity) {
58 return this.forest.containsKey(identity);
59 }
60}
diff --git a/src/main/java/cuchaz/enigma/convert/ClassIdentifier.java b/src/main/java/cuchaz/enigma/convert/ClassIdentifier.java
new file mode 100644
index 0000000..f545437
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassIdentifier.java
@@ -0,0 +1,56 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.Maps;
14
15import java.util.Map;
16import java.util.jar.JarFile;
17
18import cuchaz.enigma.TranslatingTypeLoader;
19import cuchaz.enigma.analysis.JarIndex;
20import cuchaz.enigma.convert.ClassNamer.SidedClassNamer;
21import cuchaz.enigma.mapping.ClassEntry;
22import cuchaz.enigma.mapping.TranslationDirection;
23import cuchaz.enigma.mapping.Translator;
24import javassist.CtClass;
25
26
27public class ClassIdentifier {
28
29 private JarIndex index;
30 private SidedClassNamer namer;
31 private boolean useReferences;
32 private TranslatingTypeLoader loader;
33 private Map<ClassEntry, ClassIdentity> cache;
34
35 public ClassIdentifier(JarFile jar, JarIndex index, SidedClassNamer namer, boolean useReferences) {
36 this.index = index;
37 this.namer = namer;
38 this.useReferences = useReferences;
39 this.loader = new TranslatingTypeLoader(jar, index, new Translator(), new Translator());
40 this.cache = Maps.newHashMap();
41 }
42
43 public ClassIdentity identify(ClassEntry classEntry)
44 throws ClassNotFoundException {
45 ClassIdentity identity = this.cache.get(classEntry);
46 if (identity == null) {
47 CtClass c = this.loader.loadClass(classEntry.getName());
48 if (c == null) {
49 throw new ClassNotFoundException(classEntry.getName());
50 }
51 identity = new ClassIdentity(c, this.namer, this.index, this.useReferences);
52 this.cache.put(classEntry, identity);
53 }
54 return identity;
55 }
56}
diff --git a/src/main/java/cuchaz/enigma/convert/ClassIdentity.java b/src/main/java/cuchaz/enigma/convert/ClassIdentity.java
new file mode 100644
index 0000000..606c1df
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassIdentity.java
@@ -0,0 +1,441 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.*;
14
15import java.io.UnsupportedEncodingException;
16import java.security.MessageDigest;
17import java.security.NoSuchAlgorithmException;
18import java.util.Enumeration;
19import java.util.List;
20import java.util.Map;
21import java.util.Set;
22
23import cuchaz.enigma.Constants;
24import cuchaz.enigma.Util;
25import cuchaz.enigma.analysis.ClassImplementationsTreeNode;
26import cuchaz.enigma.analysis.EntryReference;
27import cuchaz.enigma.analysis.JarIndex;
28import cuchaz.enigma.bytecode.ConstPoolEditor;
29import cuchaz.enigma.bytecode.InfoType;
30import cuchaz.enigma.bytecode.accessors.ConstInfoAccessor;
31import cuchaz.enigma.convert.ClassNamer.SidedClassNamer;
32import cuchaz.enigma.mapping.*;
33import javassist.*;
34import javassist.bytecode.*;
35import javassist.expr.*;
36
37public class ClassIdentity {
38
39 private ClassEntry classEntry;
40 private SidedClassNamer namer;
41 private Multiset<String> fields;
42 private Multiset<String> methods;
43 private Multiset<String> constructors;
44 private String staticInitializer;
45 private String extendz;
46 private Multiset<String> implementz;
47 private Set<String> stringLiterals;
48 private Multiset<String> implementations;
49 private Multiset<String> references;
50 private String outer;
51
52 private final ClassNameReplacer m_classNameReplacer = new ClassNameReplacer() {
53
54 private Map<String, String> m_classNames = Maps.newHashMap();
55
56 @Override
57 public String replace(String className) {
58
59 // classes not in the none package can be passed through
60 ClassEntry classEntry = new ClassEntry(className);
61 if (!classEntry.getPackageName().equals(Constants.NONE_PACKAGE)) {
62 return className;
63 }
64
65 // is this class ourself?
66 if (className.equals(classEntry.getName())) {
67 return "CSelf";
68 }
69
70 // try the namer
71 if (namer != null) {
72 String newName = namer.getName(className);
73 if (newName != null) {
74 return newName;
75 }
76 }
77
78 // otherwise, use local naming
79 if (!m_classNames.containsKey(className)) {
80 m_classNames.put(className, getNewClassName());
81 }
82 return m_classNames.get(className);
83 }
84
85 private String getNewClassName() {
86 return String.format("C%03d", m_classNames.size());
87 }
88 };
89
90 public ClassIdentity(CtClass c, SidedClassNamer namer, JarIndex index, boolean useReferences) {
91 this.namer = namer;
92
93 // stuff from the bytecode
94
95 this.classEntry = EntryFactory.getClassEntry(c);
96 this.fields = HashMultiset.create();
97 for (CtField field : c.getDeclaredFields()) {
98 this.fields.add(scrubType(field.getSignature()));
99 }
100 this.methods = HashMultiset.create();
101 for (CtMethod method : c.getDeclaredMethods()) {
102 this.methods.add(scrubSignature(method.getSignature()) + "0x" + getBehaviorSignature(method));
103 }
104 this.constructors = HashMultiset.create();
105 for (CtConstructor constructor : c.getDeclaredConstructors()) {
106 this.constructors.add(scrubSignature(constructor.getSignature()) + "0x" + getBehaviorSignature(constructor));
107 }
108 this.staticInitializer = "";
109 if (c.getClassInitializer() != null) {
110 this.staticInitializer = getBehaviorSignature(c.getClassInitializer());
111 }
112 this.extendz = "";
113 if (c.getClassFile().getSuperclass() != null) {
114 this.extendz = scrubClassName(Descriptor.toJvmName(c.getClassFile().getSuperclass()));
115 }
116 this.implementz = HashMultiset.create();
117 for (String interfaceName : c.getClassFile().getInterfaces()) {
118 this.implementz.add(scrubClassName(Descriptor.toJvmName(interfaceName)));
119 }
120
121 this.stringLiterals = Sets.newHashSet();
122 ConstPool constants = c.getClassFile().getConstPool();
123 for (int i = 1; i < constants.getSize(); i++) {
124 if (constants.getTag(i) == ConstPool.CONST_String) {
125 this.stringLiterals.add(constants.getStringInfo(i));
126 }
127 }
128
129 // stuff from the jar index
130
131 this.implementations = HashMultiset.create();
132 ClassImplementationsTreeNode implementationsNode = index.getClassImplementations(null, this.classEntry);
133 if (implementationsNode != null) {
134 @SuppressWarnings("unchecked")
135 Enumeration<ClassImplementationsTreeNode> implementations = implementationsNode.children();
136 while (implementations.hasMoreElements()) {
137 ClassImplementationsTreeNode node = implementations.nextElement();
138 this.implementations.add(scrubClassName(node.getClassEntry().getName()));
139 }
140 }
141
142 this.references = HashMultiset.create();
143 if (useReferences) {
144 for (CtField field : c.getDeclaredFields()) {
145 FieldEntry fieldEntry = EntryFactory.getFieldEntry(field);
146 index.getFieldReferences(fieldEntry).forEach(this::addReference);
147 }
148 for (CtBehavior behavior : c.getDeclaredBehaviors()) {
149 BehaviorEntry behaviorEntry = EntryFactory.getBehaviorEntry(behavior);
150 index.getBehaviorReferences(behaviorEntry).forEach(this::addReference);
151 }
152 }
153
154 this.outer = null;
155 if (this.classEntry.isInnerClass()) {
156 this.outer = this.classEntry.getOuterClassName();
157 }
158 }
159
160 private void addReference(EntryReference<? extends Entry, BehaviorEntry> reference) {
161 if (reference.context.getSignature() != null) {
162 this.references.add(String.format("%s_%s",
163 scrubClassName(reference.context.getClassName()),
164 scrubSignature(reference.context.getSignature())
165 ));
166 } else {
167 this.references.add(String.format("%s_<clinit>",
168 scrubClassName(reference.context.getClassName())
169 ));
170 }
171 }
172
173 public ClassEntry getClassEntry() {
174 return this.classEntry;
175 }
176
177 @Override
178 public String toString() {
179 StringBuilder buf = new StringBuilder();
180 buf.append("class: ");
181 buf.append(this.classEntry.getName());
182 buf.append(" ");
183 buf.append(hashCode());
184 buf.append("\n");
185 for (String field : this.fields) {
186 buf.append("\tfield ");
187 buf.append(field);
188 buf.append("\n");
189 }
190 for (String method : this.methods) {
191 buf.append("\tmethod ");
192 buf.append(method);
193 buf.append("\n");
194 }
195 for (String constructor : this.constructors) {
196 buf.append("\tconstructor ");
197 buf.append(constructor);
198 buf.append("\n");
199 }
200 if (this.staticInitializer.length() > 0) {
201 buf.append("\tinitializer ");
202 buf.append(this.staticInitializer);
203 buf.append("\n");
204 }
205 if (this.extendz.length() > 0) {
206 buf.append("\textends ");
207 buf.append(this.extendz);
208 buf.append("\n");
209 }
210 for (String interfaceName : this.implementz) {
211 buf.append("\timplements ");
212 buf.append(interfaceName);
213 buf.append("\n");
214 }
215 for (String implementation : this.implementations) {
216 buf.append("\timplemented by ");
217 buf.append(implementation);
218 buf.append("\n");
219 }
220 for (String reference : this.references) {
221 buf.append("\treference ");
222 buf.append(reference);
223 buf.append("\n");
224 }
225 buf.append("\touter ");
226 buf.append(this.outer);
227 buf.append("\n");
228 return buf.toString();
229 }
230
231 private String scrubClassName(String className) {
232 return m_classNameReplacer.replace(className);
233 }
234
235 private String scrubType(String typeName) {
236 return scrubType(new Type(typeName)).toString();
237 }
238
239 private Type scrubType(Type type) {
240 if (type.hasClass()) {
241 return new Type(type, m_classNameReplacer);
242 } else {
243 return type;
244 }
245 }
246
247 private String scrubSignature(String signature) {
248 return scrubSignature(new Signature(signature)).toString();
249 }
250
251 private Signature scrubSignature(Signature signature) {
252 return new Signature(signature, m_classNameReplacer);
253 }
254
255 private boolean isClassMatchedUniquely(String className) {
256 return this.namer != null && this.namer.getName(Descriptor.toJvmName(className)) != null;
257 }
258
259 private String getBehaviorSignature(CtBehavior behavior) {
260 try {
261 // does this method have an implementation?
262 if (behavior.getMethodInfo().getCodeAttribute() == null) {
263 return "(none)";
264 }
265
266 // compute the hash from the opcodes
267 ConstPool constants = behavior.getMethodInfo().getConstPool();
268 final MessageDigest digest = MessageDigest.getInstance("MD5");
269 CodeIterator iter = behavior.getMethodInfo().getCodeAttribute().iterator();
270 while (iter.hasNext()) {
271 int pos = iter.next();
272
273 // update the hash with the opcode
274 int opcode = iter.byteAt(pos);
275 digest.update((byte) opcode);
276
277 switch (opcode) {
278 case Opcode.LDC: {
279 int constIndex = iter.byteAt(pos + 1);
280 updateHashWithConstant(digest, constants, constIndex);
281 }
282 break;
283
284 case Opcode.LDC_W:
285 case Opcode.LDC2_W: {
286 int constIndex = (iter.byteAt(pos + 1) << 8) | iter.byteAt(pos + 2);
287 updateHashWithConstant(digest, constants, constIndex);
288 }
289 break;
290 }
291 }
292
293 // update hash with method and field accesses
294 behavior.instrument(new ExprEditor() {
295 @Override
296 public void edit(MethodCall call) {
297 updateHashWithString(digest, scrubClassName(Descriptor.toJvmName(call.getClassName())));
298 updateHashWithString(digest, scrubSignature(call.getSignature()));
299 if (isClassMatchedUniquely(call.getClassName())) {
300 updateHashWithString(digest, call.getMethodName());
301 }
302 }
303
304 @Override
305 public void edit(FieldAccess access) {
306 updateHashWithString(digest, scrubClassName(Descriptor.toJvmName(access.getClassName())));
307 updateHashWithString(digest, scrubType(access.getSignature()));
308 if (isClassMatchedUniquely(access.getClassName())) {
309 updateHashWithString(digest, access.getFieldName());
310 }
311 }
312
313 @Override
314 public void edit(ConstructorCall call) {
315 updateHashWithString(digest, scrubClassName(Descriptor.toJvmName(call.getClassName())));
316 updateHashWithString(digest, scrubSignature(call.getSignature()));
317 }
318
319 @Override
320 public void edit(NewExpr expr) {
321 updateHashWithString(digest, scrubClassName(Descriptor.toJvmName(expr.getClassName())));
322 }
323 });
324
325 // convert the hash to a hex string
326 return toHex(digest.digest());
327 } catch (BadBytecode | NoSuchAlgorithmException | CannotCompileException ex) {
328 throw new Error(ex);
329 }
330 }
331
332 private void updateHashWithConstant(MessageDigest digest, ConstPool constants, int index) {
333 ConstPoolEditor editor = new ConstPoolEditor(constants);
334 ConstInfoAccessor item = editor.getItem(index);
335 if (item.getType() == InfoType.StringInfo) {
336 updateHashWithString(digest, constants.getStringInfo(index));
337 }
338 // TODO: other constants
339 }
340
341 private void updateHashWithString(MessageDigest digest, String val) {
342 try {
343 digest.update(val.getBytes("UTF8"));
344 } catch (UnsupportedEncodingException ex) {
345 throw new Error(ex);
346 }
347 }
348
349 private String toHex(byte[] bytes) {
350 // function taken from:
351 // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
352 final char[] hexArray = "0123456789ABCDEF".toCharArray();
353 char[] hexChars = new char[bytes.length * 2];
354 for (int j = 0; j < bytes.length; j++) {
355 int v = bytes[j] & 0xFF;
356 hexChars[j * 2] = hexArray[v >>> 4];
357 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
358 }
359 return new String(hexChars);
360 }
361
362 @Override
363 public boolean equals(Object other) {
364 return other instanceof ClassIdentity && equals((ClassIdentity) other);
365 }
366
367 public boolean equals(ClassIdentity other) {
368 return this.fields.equals(other.fields)
369 && this.methods.equals(other.methods)
370 && this.constructors.equals(other.constructors)
371 && this.staticInitializer.equals(other.staticInitializer)
372 && this.extendz.equals(other.extendz)
373 && this.implementz.equals(other.implementz)
374 && this.implementations.equals(other.implementations)
375 && this.references.equals(other.references);
376 }
377
378 @Override
379 public int hashCode() {
380 List<Object> objs = Lists.newArrayList();
381 objs.addAll(this.fields);
382 objs.addAll(this.methods);
383 objs.addAll(this.constructors);
384 objs.add(this.staticInitializer);
385 objs.add(this.extendz);
386 objs.addAll(this.implementz);
387 objs.addAll(this.implementations);
388 objs.addAll(this.references);
389 return Util.combineHashesOrdered(objs);
390 }
391
392 public int getMatchScore(ClassIdentity other) {
393 return 2 * getNumMatches(this.extendz, other.extendz)
394 + 2 * getNumMatches(this.outer, other.outer)
395 + 2 * getNumMatches(this.implementz, other.implementz)
396 + getNumMatches(this.stringLiterals, other.stringLiterals)
397 + getNumMatches(this.fields, other.fields)
398 + getNumMatches(this.methods, other.methods)
399 + getNumMatches(this.constructors, other.constructors);
400 }
401
402 public int getMaxMatchScore() {
403 return 2 + 2 + 2 * this.implementz.size() + this.stringLiterals.size() + this.fields.size() + this.methods.size() + this.constructors.size();
404 }
405
406 public boolean matches(CtClass c) {
407 // just compare declaration counts
408 return this.fields.size() == c.getDeclaredFields().length
409 && this.methods.size() == c.getDeclaredMethods().length
410 && this.constructors.size() == c.getDeclaredConstructors().length;
411 }
412
413 private int getNumMatches(Set<String> a, Set<String> b) {
414 int numMatches = 0;
415 for (String val : a) {
416 if (b.contains(val)) {
417 numMatches++;
418 }
419 }
420 return numMatches;
421 }
422
423 private int getNumMatches(Multiset<String> a, Multiset<String> b) {
424 int numMatches = 0;
425 for (String val : a) {
426 if (b.contains(val)) {
427 numMatches++;
428 }
429 }
430 return numMatches;
431 }
432
433 private int getNumMatches(String a, String b) {
434 if (a == null && b == null) {
435 return 1;
436 } else if (a != null && b != null && a.equals(b)) {
437 return 1;
438 }
439 return 0;
440 }
441}
diff --git a/src/main/java/cuchaz/enigma/convert/ClassMatch.java b/src/main/java/cuchaz/enigma/convert/ClassMatch.java
new file mode 100644
index 0000000..422529e
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassMatch.java
@@ -0,0 +1,84 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.Sets;
14
15import java.util.Collection;
16import java.util.Set;
17
18import cuchaz.enigma.Util;
19import cuchaz.enigma.mapping.ClassEntry;
20
21
22public class ClassMatch {
23
24 public Set<ClassEntry> sourceClasses;
25 public Set<ClassEntry> destClasses;
26
27 public ClassMatch(Collection<ClassEntry> sourceClasses, Collection<ClassEntry> destClasses) {
28 this.sourceClasses = Sets.newHashSet(sourceClasses);
29 this.destClasses = Sets.newHashSet(destClasses);
30 }
31
32 public ClassMatch(ClassEntry sourceClass, ClassEntry destClass) {
33 sourceClasses = Sets.newHashSet();
34 if (sourceClass != null) {
35 sourceClasses.add(sourceClass);
36 }
37 destClasses = Sets.newHashSet();
38 if (destClass != null) {
39 destClasses.add(destClass);
40 }
41 }
42
43 public boolean isMatched() {
44 return sourceClasses.size() > 0 && destClasses.size() > 0;
45 }
46
47 public boolean isAmbiguous() {
48 return sourceClasses.size() > 1 || destClasses.size() > 1;
49 }
50
51 public ClassEntry getUniqueSource() {
52 if (sourceClasses.size() != 1) {
53 throw new IllegalStateException("Match has ambiguous source!");
54 }
55 return sourceClasses.iterator().next();
56 }
57
58 public ClassEntry getUniqueDest() {
59 if (destClasses.size() != 1) {
60 throw new IllegalStateException("Match has ambiguous source!");
61 }
62 return destClasses.iterator().next();
63 }
64
65 public Set<ClassEntry> intersectSourceClasses(Set<ClassEntry> classes) {
66 Set<ClassEntry> intersection = Sets.newHashSet(sourceClasses);
67 intersection.retainAll(classes);
68 return intersection;
69 }
70
71 @Override
72 public int hashCode() {
73 return Util.combineHashesOrdered(sourceClasses, destClasses);
74 }
75
76 @Override
77 public boolean equals(Object other) {
78 return other instanceof ClassMatch && equals((ClassMatch) other);
79 }
80
81 public boolean equals(ClassMatch other) {
82 return this.sourceClasses.equals(other.sourceClasses) && this.destClasses.equals(other.destClasses);
83 }
84}
diff --git a/src/main/java/cuchaz/enigma/convert/ClassMatches.java b/src/main/java/cuchaz/enigma/convert/ClassMatches.java
new file mode 100644
index 0000000..3a25435
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassMatches.java
@@ -0,0 +1,159 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.BiMap;
14import com.google.common.collect.HashBiMap;
15import com.google.common.collect.Maps;
16import com.google.common.collect.Sets;
17
18import java.util.*;
19
20import cuchaz.enigma.mapping.ClassEntry;
21
22
23public class ClassMatches implements Iterable<ClassMatch> {
24
25 Collection<ClassMatch> m_matches;
26 Map<ClassEntry, ClassMatch> m_matchesBySource;
27 Map<ClassEntry, ClassMatch> m_matchesByDest;
28 BiMap<ClassEntry, ClassEntry> m_uniqueMatches;
29 Map<ClassEntry, ClassMatch> m_ambiguousMatchesBySource;
30 Map<ClassEntry, ClassMatch> m_ambiguousMatchesByDest;
31 Set<ClassEntry> m_unmatchedSourceClasses;
32 Set<ClassEntry> m_unmatchedDestClasses;
33
34 public ClassMatches() {
35 this(new ArrayList<>());
36 }
37
38 public ClassMatches(Collection<ClassMatch> matches) {
39 m_matches = matches;
40 m_matchesBySource = Maps.newHashMap();
41 m_matchesByDest = Maps.newHashMap();
42 m_uniqueMatches = HashBiMap.create();
43 m_ambiguousMatchesBySource = Maps.newHashMap();
44 m_ambiguousMatchesByDest = Maps.newHashMap();
45 m_unmatchedSourceClasses = Sets.newHashSet();
46 m_unmatchedDestClasses = Sets.newHashSet();
47
48 for (ClassMatch match : matches) {
49 indexMatch(match);
50 }
51 }
52
53 public void add(ClassMatch match) {
54 m_matches.add(match);
55 indexMatch(match);
56 }
57
58 public void remove(ClassMatch match) {
59 for (ClassEntry sourceClass : match.sourceClasses) {
60 m_matchesBySource.remove(sourceClass);
61 m_uniqueMatches.remove(sourceClass);
62 m_ambiguousMatchesBySource.remove(sourceClass);
63 m_unmatchedSourceClasses.remove(sourceClass);
64 }
65 for (ClassEntry destClass : match.destClasses) {
66 m_matchesByDest.remove(destClass);
67 m_uniqueMatches.inverse().remove(destClass);
68 m_ambiguousMatchesByDest.remove(destClass);
69 m_unmatchedDestClasses.remove(destClass);
70 }
71 m_matches.remove(match);
72 }
73
74 public int size() {
75 return m_matches.size();
76 }
77
78 @Override
79 public Iterator<ClassMatch> iterator() {
80 return m_matches.iterator();
81 }
82
83 private void indexMatch(ClassMatch match) {
84 if (!match.isMatched()) {
85 // unmatched
86 m_unmatchedSourceClasses.addAll(match.sourceClasses);
87 m_unmatchedDestClasses.addAll(match.destClasses);
88 } else {
89 if (match.isAmbiguous()) {
90 // ambiguously matched
91 for (ClassEntry entry : match.sourceClasses) {
92 m_ambiguousMatchesBySource.put(entry, match);
93 }
94 for (ClassEntry entry : match.destClasses) {
95 m_ambiguousMatchesByDest.put(entry, match);
96 }
97 } else {
98 // uniquely matched
99 m_uniqueMatches.put(match.getUniqueSource(), match.getUniqueDest());
100 }
101 }
102 for (ClassEntry entry : match.sourceClasses) {
103 m_matchesBySource.put(entry, match);
104 }
105 for (ClassEntry entry : match.destClasses) {
106 m_matchesByDest.put(entry, match);
107 }
108 }
109
110 public BiMap<ClassEntry, ClassEntry> getUniqueMatches() {
111 return m_uniqueMatches;
112 }
113
114 public Set<ClassEntry> getUnmatchedSourceClasses() {
115 return m_unmatchedSourceClasses;
116 }
117
118 public Set<ClassEntry> getUnmatchedDestClasses() {
119 return m_unmatchedDestClasses;
120 }
121
122 public Set<ClassEntry> getAmbiguouslyMatchedSourceClasses() {
123 return m_ambiguousMatchesBySource.keySet();
124 }
125
126 public ClassMatch getAmbiguousMatchBySource(ClassEntry sourceClass) {
127 return m_ambiguousMatchesBySource.get(sourceClass);
128 }
129
130 public ClassMatch getMatchBySource(ClassEntry sourceClass) {
131 return m_matchesBySource.get(sourceClass);
132 }
133
134 public ClassMatch getMatchByDest(ClassEntry destClass) {
135 return m_matchesByDest.get(destClass);
136 }
137
138 public void removeSource(ClassEntry sourceClass) {
139 ClassMatch match = m_matchesBySource.get(sourceClass);
140 if (match != null) {
141 remove(match);
142 match.sourceClasses.remove(sourceClass);
143 if (!match.sourceClasses.isEmpty() || !match.destClasses.isEmpty()) {
144 add(match);
145 }
146 }
147 }
148
149 public void removeDest(ClassEntry destClass) {
150 ClassMatch match = m_matchesByDest.get(destClass);
151 if (match != null) {
152 remove(match);
153 match.destClasses.remove(destClass);
154 if (!match.sourceClasses.isEmpty() || !match.destClasses.isEmpty()) {
155 add(match);
156 }
157 }
158 }
159}
diff --git a/src/main/java/cuchaz/enigma/convert/ClassMatching.java b/src/main/java/cuchaz/enigma/convert/ClassMatching.java
new file mode 100644
index 0000000..9350ea7
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassMatching.java
@@ -0,0 +1,155 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.BiMap;
14import com.google.common.collect.HashBiMap;
15import com.google.common.collect.Lists;
16import com.google.common.collect.Sets;
17
18import java.util.ArrayList;
19import java.util.Collection;
20import java.util.List;
21import java.util.Map.Entry;
22import java.util.Set;
23
24import cuchaz.enigma.mapping.ClassEntry;
25
26public class ClassMatching {
27
28 private ClassForest m_sourceClasses;
29 private ClassForest m_destClasses;
30 private BiMap<ClassEntry, ClassEntry> m_knownMatches;
31
32 public ClassMatching(ClassIdentifier sourceIdentifier, ClassIdentifier destIdentifier) {
33 m_sourceClasses = new ClassForest(sourceIdentifier);
34 m_destClasses = new ClassForest(destIdentifier);
35 m_knownMatches = HashBiMap.create();
36 }
37
38 public void addKnownMatches(BiMap<ClassEntry, ClassEntry> knownMatches) {
39 m_knownMatches.putAll(knownMatches);
40 }
41
42 public void match(Iterable<ClassEntry> sourceClasses, Iterable<ClassEntry> destClasses) {
43 for (ClassEntry sourceClass : sourceClasses) {
44 if (!m_knownMatches.containsKey(sourceClass)) {
45 m_sourceClasses.add(sourceClass);
46 }
47 }
48 for (ClassEntry destClass : destClasses) {
49 if (!m_knownMatches.containsValue(destClass)) {
50 m_destClasses.add(destClass);
51 }
52 }
53 }
54
55 public Collection<ClassMatch> matches() {
56 List<ClassMatch> matches = Lists.newArrayList();
57 for (Entry<ClassEntry, ClassEntry> entry : m_knownMatches.entrySet()) {
58 matches.add(new ClassMatch(
59 entry.getKey(),
60 entry.getValue()
61 ));
62 }
63 for (ClassIdentity identity : m_sourceClasses.identities()) {
64 matches.add(new ClassMatch(
65 m_sourceClasses.getClasses(identity),
66 m_destClasses.getClasses(identity)
67 ));
68 }
69 for (ClassIdentity identity : m_destClasses.identities()) {
70 if (!m_sourceClasses.containsIdentity(identity)) {
71 matches.add(new ClassMatch(
72 new ArrayList<>(),
73 m_destClasses.getClasses(identity)
74 ));
75 }
76 }
77 return matches;
78 }
79
80 public Collection<ClassEntry> sourceClasses() {
81 Set<ClassEntry> classes = Sets.newHashSet();
82 for (ClassMatch match : matches()) {
83 classes.addAll(match.sourceClasses);
84 }
85 return classes;
86 }
87
88 public Collection<ClassEntry> destClasses() {
89 Set<ClassEntry> classes = Sets.newHashSet();
90 for (ClassMatch match : matches()) {
91 classes.addAll(match.destClasses);
92 }
93 return classes;
94 }
95
96 public BiMap<ClassEntry, ClassEntry> uniqueMatches() {
97 BiMap<ClassEntry, ClassEntry> uniqueMatches = HashBiMap.create();
98 for (ClassMatch match : matches()) {
99 if (match.isMatched() && !match.isAmbiguous()) {
100 uniqueMatches.put(match.getUniqueSource(), match.getUniqueDest());
101 }
102 }
103 return uniqueMatches;
104 }
105
106 public Collection<ClassMatch> ambiguousMatches() {
107 List<ClassMatch> ambiguousMatches = Lists.newArrayList();
108 for (ClassMatch match : matches()) {
109 if (match.isMatched() && match.isAmbiguous()) {
110 ambiguousMatches.add(match);
111 }
112 }
113 return ambiguousMatches;
114 }
115
116 public Collection<ClassEntry> unmatchedSourceClasses() {
117 List<ClassEntry> classes = Lists.newArrayList();
118 for (ClassMatch match : matches()) {
119 if (!match.isMatched() && !match.sourceClasses.isEmpty()) {
120 classes.addAll(match.sourceClasses);
121 }
122 }
123 return classes;
124 }
125
126 public Collection<ClassEntry> unmatchedDestClasses() {
127 List<ClassEntry> classes = Lists.newArrayList();
128 for (ClassMatch match : matches()) {
129 if (!match.isMatched() && !match.destClasses.isEmpty()) {
130 classes.addAll(match.destClasses);
131 }
132 }
133 return classes;
134 }
135
136 @Override
137 public String toString() {
138
139 // count the ambiguous classes
140 int numAmbiguousSource = 0;
141 int numAmbiguousDest = 0;
142 for (ClassMatch match : ambiguousMatches()) {
143 numAmbiguousSource += match.sourceClasses.size();
144 numAmbiguousDest += match.destClasses.size();
145 }
146
147 StringBuilder buf = new StringBuilder();
148 buf.append(String.format("%20s%8s%8s\n", "", "Source", "Dest"));
149 buf.append(String.format("%20s%8d%8d\n", "Classes", sourceClasses().size(), destClasses().size()));
150 buf.append(String.format("%20s%8d%8d\n", "Uniquely matched", uniqueMatches().size(), uniqueMatches().size()));
151 buf.append(String.format("%20s%8d%8d\n", "Ambiguously matched", numAmbiguousSource, numAmbiguousDest));
152 buf.append(String.format("%20s%8d%8d\n", "Unmatched", unmatchedSourceClasses().size(), unmatchedDestClasses().size()));
153 return buf.toString();
154 }
155}
diff --git a/src/main/java/cuchaz/enigma/convert/ClassNamer.java b/src/main/java/cuchaz/enigma/convert/ClassNamer.java
new file mode 100644
index 0000000..e471c7d
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassNamer.java
@@ -0,0 +1,56 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.BiMap;
14import com.google.common.collect.Maps;
15
16import java.util.Map;
17
18import cuchaz.enigma.mapping.ClassEntry;
19
20public class ClassNamer {
21
22 public interface SidedClassNamer {
23 String getName(String name);
24 }
25
26 private Map<String, String> sourceNames;
27 private Map<String, String> destNames;
28
29 public ClassNamer(BiMap<ClassEntry, ClassEntry> mappings) {
30 // convert the identity mappings to name maps
31 this.sourceNames = Maps.newHashMap();
32 this.destNames = Maps.newHashMap();
33 int i = 0;
34 for (Map.Entry<ClassEntry, ClassEntry> entry : mappings.entrySet()) {
35 String name = String.format("M%04d", i++);
36 this.sourceNames.put(entry.getKey().getName(), name);
37 this.destNames.put(entry.getValue().getName(), name);
38 }
39 }
40
41 public String getSourceName(String name) {
42 return this.sourceNames.get(name);
43 }
44
45 public String getDestName(String name) {
46 return this.destNames.get(name);
47 }
48
49 public SidedClassNamer getSourceNamer() {
50 return this::getSourceName;
51 }
52
53 public SidedClassNamer getDestNamer() {
54 return this::getDestName;
55 }
56}
diff --git a/src/main/java/cuchaz/enigma/convert/FieldMatches.java b/src/main/java/cuchaz/enigma/convert/FieldMatches.java
new file mode 100644
index 0000000..0899cd2
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/FieldMatches.java
@@ -0,0 +1,151 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.*;
14
15import java.util.Collection;
16import java.util.Set;
17
18import cuchaz.enigma.mapping.ClassEntry;
19import cuchaz.enigma.mapping.FieldEntry;
20
21
22public class FieldMatches {
23
24 private BiMap<FieldEntry, FieldEntry> m_matches;
25 private Multimap<ClassEntry, FieldEntry> m_matchedSourceFields;
26 private Multimap<ClassEntry, FieldEntry> m_unmatchedSourceFields;
27 private Multimap<ClassEntry, FieldEntry> m_unmatchedDestFields;
28 private Multimap<ClassEntry, FieldEntry> m_unmatchableSourceFields;
29
30 public FieldMatches() {
31 m_matches = HashBiMap.create();
32 m_matchedSourceFields = HashMultimap.create();
33 m_unmatchedSourceFields = HashMultimap.create();
34 m_unmatchedDestFields = HashMultimap.create();
35 m_unmatchableSourceFields = HashMultimap.create();
36 }
37
38 public void addMatch(FieldEntry srcField, FieldEntry destField) {
39 boolean wasAdded = m_matches.put(srcField, destField) == null;
40 assert (wasAdded);
41 wasAdded = m_matchedSourceFields.put(srcField.getClassEntry(), srcField);
42 assert (wasAdded);
43 }
44
45 public void addUnmatchedSourceField(FieldEntry fieldEntry) {
46 boolean wasAdded = m_unmatchedSourceFields.put(fieldEntry.getClassEntry(), fieldEntry);
47 assert (wasAdded);
48 }
49
50 public void addUnmatchedSourceFields(Iterable<FieldEntry> fieldEntries) {
51 for (FieldEntry fieldEntry : fieldEntries) {
52 addUnmatchedSourceField(fieldEntry);
53 }
54 }
55
56 public void addUnmatchedDestField(FieldEntry fieldEntry) {
57 boolean wasAdded = m_unmatchedDestFields.put(fieldEntry.getClassEntry(), fieldEntry);
58 assert (wasAdded);
59 }
60
61 public void addUnmatchedDestFields(Iterable<FieldEntry> fieldEntries) {
62 for (FieldEntry fieldEntry : fieldEntries) {
63 addUnmatchedDestField(fieldEntry);
64 }
65 }
66
67 public void addUnmatchableSourceField(FieldEntry sourceField) {
68 boolean wasAdded = m_unmatchableSourceFields.put(sourceField.getClassEntry(), sourceField);
69 assert (wasAdded);
70 }
71
72 public Set<ClassEntry> getSourceClassesWithUnmatchedFields() {
73 return m_unmatchedSourceFields.keySet();
74 }
75
76 public Collection<ClassEntry> getSourceClassesWithoutUnmatchedFields() {
77 Set<ClassEntry> out = Sets.newHashSet();
78 out.addAll(m_matchedSourceFields.keySet());
79 out.removeAll(m_unmatchedSourceFields.keySet());
80 return out;
81 }
82
83 public Collection<FieldEntry> getUnmatchedSourceFields() {
84 return m_unmatchedSourceFields.values();
85 }
86
87 public Collection<FieldEntry> getUnmatchedSourceFields(ClassEntry sourceClass) {
88 return m_unmatchedSourceFields.get(sourceClass);
89 }
90
91 public Collection<FieldEntry> getUnmatchedDestFields() {
92 return m_unmatchedDestFields.values();
93 }
94
95 public Collection<FieldEntry> getUnmatchedDestFields(ClassEntry destClass) {
96 return m_unmatchedDestFields.get(destClass);
97 }
98
99 public Collection<FieldEntry> getUnmatchableSourceFields() {
100 return m_unmatchableSourceFields.values();
101 }
102
103 public boolean hasSource(FieldEntry fieldEntry) {
104 return m_matches.containsKey(fieldEntry) || m_unmatchedSourceFields.containsValue(fieldEntry);
105 }
106
107 public boolean hasDest(FieldEntry fieldEntry) {
108 return m_matches.containsValue(fieldEntry) || m_unmatchedDestFields.containsValue(fieldEntry);
109 }
110
111 public BiMap<FieldEntry, FieldEntry> matches() {
112 return m_matches;
113 }
114
115 public boolean isMatchedSourceField(FieldEntry sourceField) {
116 return m_matches.containsKey(sourceField);
117 }
118
119 public boolean isMatchedDestField(FieldEntry destField) {
120 return m_matches.containsValue(destField);
121 }
122
123 public void makeMatch(FieldEntry sourceField, FieldEntry destField) {
124 boolean wasRemoved = m_unmatchedSourceFields.remove(sourceField.getClassEntry(), sourceField);
125 assert (wasRemoved);
126 wasRemoved = m_unmatchedDestFields.remove(destField.getClassEntry(), destField);
127 assert (wasRemoved);
128 addMatch(sourceField, destField);
129 }
130
131 public boolean isMatched(FieldEntry sourceField, FieldEntry destField) {
132 FieldEntry match = m_matches.get(sourceField);
133 return match != null && match.equals(destField);
134 }
135
136 public void unmakeMatch(FieldEntry sourceField, FieldEntry destField) {
137 boolean wasRemoved = m_matches.remove(sourceField) != null;
138 assert (wasRemoved);
139 wasRemoved = m_matchedSourceFields.remove(sourceField.getClassEntry(), sourceField);
140 assert (wasRemoved);
141 addUnmatchedSourceField(sourceField);
142 addUnmatchedDestField(destField);
143 }
144
145 public void makeSourceUnmatchable(FieldEntry sourceField) {
146 assert (!isMatchedSourceField(sourceField));
147 boolean wasRemoved = m_unmatchedSourceFields.remove(sourceField.getClassEntry(), sourceField);
148 assert (wasRemoved);
149 addUnmatchableSourceField(sourceField);
150 }
151}
diff --git a/src/main/java/cuchaz/enigma/convert/MappingsConverter.java b/src/main/java/cuchaz/enigma/convert/MappingsConverter.java
new file mode 100644
index 0000000..61b0e7e
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/MappingsConverter.java
@@ -0,0 +1,583 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.*;
14
15import java.util.*;
16import java.util.jar.JarFile;
17
18import cuchaz.enigma.Constants;
19import cuchaz.enigma.Deobfuscator;
20import cuchaz.enigma.analysis.JarIndex;
21import cuchaz.enigma.convert.ClassNamer.SidedClassNamer;
22import cuchaz.enigma.mapping.*;
23import cuchaz.enigma.throwables.MappingConflict;
24
25public class MappingsConverter {
26
27 public static ClassMatches computeClassMatches(JarFile sourceJar, JarFile destJar, Mappings mappings) {
28
29 // index jars
30 System.out.println("Indexing source jar...");
31 JarIndex sourceIndex = new JarIndex();
32 sourceIndex.indexJar(sourceJar, false);
33 System.out.println("Indexing dest jar...");
34 JarIndex destIndex = new JarIndex();
35 destIndex.indexJar(destJar, false);
36
37 // compute the matching
38 ClassMatching matching = computeMatching(sourceJar, sourceIndex, destJar, destIndex, null);
39 return new ClassMatches(matching.matches());
40 }
41
42 public static ClassMatching computeMatching(JarFile sourceJar, JarIndex sourceIndex, JarFile destJar, JarIndex destIndex, BiMap<ClassEntry, ClassEntry> knownMatches) {
43
44 System.out.println("Iteratively matching classes");
45
46 ClassMatching lastMatching = null;
47 int round = 0;
48 SidedClassNamer sourceNamer = null;
49 SidedClassNamer destNamer = null;
50 for (boolean useReferences : Arrays.asList(false, true)) {
51
52 int numUniqueMatchesLastTime = 0;
53 if (lastMatching != null) {
54 numUniqueMatchesLastTime = lastMatching.uniqueMatches().size();
55 }
56
57 while (true) {
58
59 System.out.println("Round " + (++round) + "...");
60
61 // init the matching with identity settings
62 ClassMatching matching = new ClassMatching(
63 new ClassIdentifier(sourceJar, sourceIndex, sourceNamer, useReferences),
64 new ClassIdentifier(destJar, destIndex, destNamer, useReferences)
65 );
66
67 if (knownMatches != null) {
68 matching.addKnownMatches(knownMatches);
69 }
70
71 if (lastMatching == null) {
72 // search all classes
73 matching.match(sourceIndex.getObfClassEntries(), destIndex.getObfClassEntries());
74 } else {
75 // we already know about these matches from last time
76 matching.addKnownMatches(lastMatching.uniqueMatches());
77
78 // search unmatched and ambiguously-matched classes
79 matching.match(lastMatching.unmatchedSourceClasses(), lastMatching.unmatchedDestClasses());
80 for (ClassMatch match : lastMatching.ambiguousMatches()) {
81 matching.match(match.sourceClasses, match.destClasses);
82 }
83 }
84 System.out.println(matching);
85 BiMap<ClassEntry, ClassEntry> uniqueMatches = matching.uniqueMatches();
86
87 // did we match anything new this time?
88 if (uniqueMatches.size() > numUniqueMatchesLastTime) {
89 numUniqueMatchesLastTime = uniqueMatches.size();
90 lastMatching = matching;
91 } else {
92 break;
93 }
94
95 // update the namers
96 ClassNamer namer = new ClassNamer(uniqueMatches);
97 sourceNamer = namer.getSourceNamer();
98 destNamer = namer.getDestNamer();
99 }
100 }
101
102 return lastMatching;
103 }
104
105 public static Mappings newMappings(ClassMatches matches, Mappings oldMappings, Deobfuscator sourceDeobfuscator, Deobfuscator destDeobfuscator)
106 throws MappingConflict {
107 // sort the unique matches by size of inner class chain
108 Multimap<Integer, java.util.Map.Entry<ClassEntry, ClassEntry>> matchesByDestChainSize = HashMultimap.create();
109 for (java.util.Map.Entry<ClassEntry, ClassEntry> match : matches.getUniqueMatches().entrySet()) {
110 int chainSize = destDeobfuscator.getJarIndex().getObfClassChain(match.getValue()).size();
111 matchesByDestChainSize.put(chainSize, match);
112 }
113
114 // build the mappings (in order of small-to-large inner chains)
115 Mappings newMappings = new Mappings();
116 List<Integer> chainSizes = Lists.newArrayList(matchesByDestChainSize.keySet());
117 Collections.sort(chainSizes);
118 for (int chainSize : chainSizes) {
119 for (java.util.Map.Entry<ClassEntry, ClassEntry> match : matchesByDestChainSize.get(chainSize)) {
120
121 // get class info
122 ClassEntry obfSourceClassEntry = match.getKey();
123 ClassEntry obfDestClassEntry = match.getValue();
124 List<ClassEntry> destClassChain = destDeobfuscator.getJarIndex().getObfClassChain(obfDestClassEntry);
125
126 ClassMapping sourceMapping = sourceDeobfuscator.getMappings().getClassByObf(obfSourceClassEntry);
127 if (sourceMapping == null) {
128 // if this class was never deobfuscated, don't try to match it
129 continue;
130 }
131
132 // find out where to make the dest class mapping
133 if (destClassChain.size() == 1) {
134 // not an inner class, add directly to mappings
135 newMappings.addClassMapping(migrateClassMapping(obfDestClassEntry, sourceMapping, matches, false));
136 } else {
137 // inner class, find the outer class mapping
138 ClassMapping destMapping = null;
139 for (int i = 0; i < destClassChain.size() - 1; i++) {
140 ClassEntry destChainClassEntry = destClassChain.get(i);
141 if (destMapping == null) {
142 destMapping = newMappings.getClassByObf(destChainClassEntry);
143 if (destMapping == null) {
144 destMapping = new ClassMapping(destChainClassEntry.getName());
145 newMappings.addClassMapping(destMapping);
146 }
147 } else {
148 destMapping = destMapping.getInnerClassByObfSimple(destChainClassEntry.getInnermostClassName());
149 if (destMapping == null) {
150 destMapping = new ClassMapping(destChainClassEntry.getName());
151 destMapping.addInnerClassMapping(destMapping);
152 }
153 }
154 }
155 destMapping.addInnerClassMapping(migrateClassMapping(obfDestClassEntry, sourceMapping, matches, true));
156 }
157 }
158 }
159 return newMappings;
160 }
161
162 private static ClassMapping migrateClassMapping(ClassEntry newObfClass, ClassMapping oldClassMapping, final ClassMatches matches, boolean useSimpleName) {
163
164 ClassNameReplacer replacer = new ClassNameReplacer() {
165 @Override
166 public String replace(String className) {
167 ClassEntry newClassEntry = matches.getUniqueMatches().get(new ClassEntry(className));
168 if (newClassEntry != null) {
169 return newClassEntry.getName();
170 }
171 return null;
172 }
173 };
174
175 ClassMapping newClassMapping;
176 String deobfName = oldClassMapping.getDeobfName();
177 if (deobfName != null) {
178 if (useSimpleName) {
179 deobfName = new ClassEntry(deobfName).getSimpleName();
180 }
181 newClassMapping = new ClassMapping(newObfClass.getName(), deobfName);
182 } else {
183 newClassMapping = new ClassMapping(newObfClass.getName());
184 }
185
186 // migrate fields
187 for (FieldMapping oldFieldMapping : oldClassMapping.fields()) {
188 if (canMigrate(oldFieldMapping.getObfType(), matches)) {
189 newClassMapping.addFieldMapping(new FieldMapping(oldFieldMapping, replacer));
190 } else {
191 System.out.println(String.format("Can't map field, dropping: %s.%s %s",
192 oldClassMapping.getDeobfName(),
193 oldFieldMapping.getDeobfName(),
194 oldFieldMapping.getObfType()
195 ));
196 }
197 }
198
199 // migrate methods
200 for (MethodMapping oldMethodMapping : oldClassMapping.methods()) {
201 if (canMigrate(oldMethodMapping.getObfSignature(), matches)) {
202 newClassMapping.addMethodMapping(new MethodMapping(oldMethodMapping, replacer));
203 } else {
204 System.out.println(String.format("Can't map method, dropping: %s.%s %s",
205 oldClassMapping.getDeobfName(),
206 oldMethodMapping.getDeobfName(),
207 oldMethodMapping.getObfSignature()
208 ));
209 }
210 }
211
212 return newClassMapping;
213 }
214
215 private static boolean canMigrate(Signature oldObfSignature, ClassMatches classMatches) {
216 for (Type oldObfType : oldObfSignature.types()) {
217 if (!canMigrate(oldObfType, classMatches)) {
218 return false;
219 }
220 }
221 return true;
222 }
223
224 private static boolean canMigrate(Type oldObfType, ClassMatches classMatches) {
225
226 // non classes can be migrated
227 if (!oldObfType.hasClass()) {
228 return true;
229 }
230
231 // non obfuscated classes can be migrated
232 ClassEntry classEntry = oldObfType.getClassEntry();
233 if (!classEntry.getPackageName().equals(Constants.NONE_PACKAGE)) {
234 return true;
235 }
236
237 // obfuscated classes with mappings can be migrated
238 return classMatches.getUniqueMatches().containsKey(classEntry);
239 }
240
241 public static void convertMappings(Mappings mappings, BiMap<ClassEntry, ClassEntry> changes) {
242
243 // sort the changes so classes are renamed in the correct order
244 // ie. if we have the mappings a->b, b->c, we have to apply b->c before a->b
245 LinkedHashMap<ClassEntry, ClassEntry> sortedChanges = Maps.newLinkedHashMap();
246 int numChangesLeft = changes.size();
247 while (!changes.isEmpty()) {
248 Iterator<Map.Entry<ClassEntry, ClassEntry>> iter = changes.entrySet().iterator();
249 while (iter.hasNext()) {
250 Map.Entry<ClassEntry, ClassEntry> change = iter.next();
251 if (changes.containsKey(change.getValue())) {
252 sortedChanges.put(change.getKey(), change.getValue());
253 iter.remove();
254 }
255 }
256
257 // did we remove any changes?
258 if (numChangesLeft - changes.size() > 0) {
259 // keep going
260 numChangesLeft = changes.size();
261 } else {
262 // can't sort anymore. There must be a loop
263 break;
264 }
265 }
266 if (!changes.isEmpty()) {
267 throw new Error("Unable to sort class changes! There must be a cycle.");
268 }
269
270 // convert the mappings in the correct class order
271 for (Map.Entry<ClassEntry, ClassEntry> entry : sortedChanges.entrySet()) {
272 mappings.renameObfClass(entry.getKey().getName(), entry.getValue().getName());
273 }
274 }
275
276 public interface Doer<T extends Entry> {
277 Collection<T> getDroppedEntries(MappingsChecker checker);
278
279 Collection<T> getObfEntries(JarIndex jarIndex);
280
281 Collection<? extends MemberMapping<T>> getMappings(ClassMapping destClassMapping);
282
283 Set<T> filterEntries(Collection<T> obfEntries, T obfSourceEntry, ClassMatches classMatches);
284
285 void setUpdateObfMember(ClassMapping classMapping, MemberMapping<T> memberMapping, T newEntry);
286
287 boolean hasObfMember(ClassMapping classMapping, T obfEntry);
288
289 void removeMemberByObf(ClassMapping classMapping, T obfEntry);
290 }
291
292 public static Doer<FieldEntry> getFieldDoer() {
293 return new Doer<FieldEntry>() {
294
295 @Override
296 public Collection<FieldEntry> getDroppedEntries(MappingsChecker checker) {
297 return checker.getDroppedFieldMappings().keySet();
298 }
299
300 @Override
301 public Collection<FieldEntry> getObfEntries(JarIndex jarIndex) {
302 return jarIndex.getObfFieldEntries();
303 }
304
305 @Override
306 public Collection<? extends MemberMapping<FieldEntry>> getMappings(ClassMapping destClassMapping) {
307 return (Collection<? extends MemberMapping<FieldEntry>>) destClassMapping.fields();
308 }
309
310 @Override
311 public Set<FieldEntry> filterEntries(Collection<FieldEntry> obfDestFields, FieldEntry obfSourceField, ClassMatches classMatches) {
312 Set<FieldEntry> out = Sets.newHashSet();
313 for (FieldEntry obfDestField : obfDestFields) {
314 Type translatedDestType = translate(obfDestField.getType(), classMatches.getUniqueMatches().inverse());
315 if (translatedDestType.equals(obfSourceField.getType())) {
316 out.add(obfDestField);
317 }
318 }
319 return out;
320 }
321
322 @Override
323 public void setUpdateObfMember(ClassMapping classMapping, MemberMapping<FieldEntry> memberMapping, FieldEntry newField) {
324 FieldMapping fieldMapping = (FieldMapping) memberMapping;
325 classMapping.setFieldObfNameAndType(fieldMapping.getObfName(), fieldMapping.getObfType(), newField.getName(), newField.getType());
326 }
327
328 @Override
329 public boolean hasObfMember(ClassMapping classMapping, FieldEntry obfField) {
330 return classMapping.getFieldByObf(obfField.getName(), obfField.getType()) != null;
331 }
332
333 @Override
334 public void removeMemberByObf(ClassMapping classMapping, FieldEntry obfField) {
335 classMapping.removeFieldMapping(classMapping.getFieldByObf(obfField.getName(), obfField.getType()));
336 }
337 };
338 }
339
340 public static Doer<BehaviorEntry> getMethodDoer() {
341 return new Doer<BehaviorEntry>() {
342
343 @Override
344 public Collection<BehaviorEntry> getDroppedEntries(MappingsChecker checker) {
345 return checker.getDroppedMethodMappings().keySet();
346 }
347
348 @Override
349 public Collection<BehaviorEntry> getObfEntries(JarIndex jarIndex) {
350 return jarIndex.getObfBehaviorEntries();
351 }
352
353 @Override
354 public Collection<? extends MemberMapping<BehaviorEntry>> getMappings(ClassMapping destClassMapping) {
355 return (Collection<? extends MemberMapping<BehaviorEntry>>) destClassMapping.methods();
356 }
357
358 @Override
359 public Set<BehaviorEntry> filterEntries(Collection<BehaviorEntry> obfDestFields, BehaviorEntry obfSourceField, ClassMatches classMatches) {
360 Set<BehaviorEntry> out = Sets.newHashSet();
361 for (BehaviorEntry obfDestField : obfDestFields) {
362 Signature translatedDestSignature = translate(obfDestField.getSignature(), classMatches.getUniqueMatches().inverse());
363 if (translatedDestSignature == null && obfSourceField.getSignature() == null) {
364 out.add(obfDestField);
365 } else if (translatedDestSignature == null || obfSourceField.getSignature() == null) {
366 // skip it
367 } else if (translatedDestSignature.equals(obfSourceField.getSignature())) {
368 out.add(obfDestField);
369 }
370 }
371 return out;
372 }
373
374 @Override
375 public void setUpdateObfMember(ClassMapping classMapping, MemberMapping<BehaviorEntry> memberMapping, BehaviorEntry newBehavior) {
376 MethodMapping methodMapping = (MethodMapping) memberMapping;
377 classMapping.setMethodObfNameAndSignature(methodMapping.getObfName(), methodMapping.getObfSignature(), newBehavior.getName(), newBehavior.getSignature());
378 }
379
380 @Override
381 public boolean hasObfMember(ClassMapping classMapping, BehaviorEntry obfBehavior) {
382 return classMapping.getMethodByObf(obfBehavior.getName(), obfBehavior.getSignature()) != null;
383 }
384
385 @Override
386 public void removeMemberByObf(ClassMapping classMapping, BehaviorEntry obfBehavior) {
387 classMapping.removeMethodMapping(classMapping.getMethodByObf(obfBehavior.getName(), obfBehavior.getSignature()));
388 }
389 };
390 }
391
392 public static <T extends Entry> MemberMatches<T> computeMemberMatches(Deobfuscator destDeobfuscator, Mappings destMappings, ClassMatches classMatches, Doer<T> doer) {
393
394 MemberMatches<T> memberMatches = new MemberMatches<T>();
395
396 // unmatched source fields are easy
397 MappingsChecker checker = new MappingsChecker(destDeobfuscator.getJarIndex());
398 checker.dropBrokenMappings(destMappings);
399 for (T destObfEntry : doer.getDroppedEntries(checker)) {
400 T srcObfEntry = translate(destObfEntry, classMatches.getUniqueMatches().inverse());
401 memberMatches.addUnmatchedSourceEntry(srcObfEntry);
402 }
403
404 // get matched fields (anything that's left after the checks/drops is matched(
405 for (ClassMapping classMapping : destMappings.classes()) {
406 collectMatchedFields(memberMatches, classMapping, classMatches, doer);
407 }
408
409 // get unmatched dest fields
410 for (T destEntry : doer.getObfEntries(destDeobfuscator.getJarIndex())) {
411 if (!memberMatches.isMatchedDestEntry(destEntry)) {
412 memberMatches.addUnmatchedDestEntry(destEntry);
413 }
414 }
415
416 System.out.println("Automatching " + memberMatches.getUnmatchedSourceEntries().size() + " unmatched source entries...");
417
418 // go through the unmatched source fields and try to pick out the easy matches
419 for (ClassEntry obfSourceClass : Lists.newArrayList(memberMatches.getSourceClassesWithUnmatchedEntries())) {
420 for (T obfSourceEntry : Lists.newArrayList(memberMatches.getUnmatchedSourceEntries(obfSourceClass))) {
421
422 // get the possible dest matches
423 ClassEntry obfDestClass = classMatches.getUniqueMatches().get(obfSourceClass);
424
425 // filter by type/signature
426 Set<T> obfDestEntries = doer.filterEntries(memberMatches.getUnmatchedDestEntries(obfDestClass), obfSourceEntry, classMatches);
427
428 if (obfDestEntries.size() == 1) {
429 // make the easy match
430 memberMatches.makeMatch(obfSourceEntry, obfDestEntries.iterator().next());
431 } else if (obfDestEntries.isEmpty()) {
432 // no match is possible =(
433 memberMatches.makeSourceUnmatchable(obfSourceEntry);
434 }
435 }
436 }
437
438 System.out.println(String.format("Ended up with %d ambiguous and %d unmatchable source entries",
439 memberMatches.getUnmatchedSourceEntries().size(),
440 memberMatches.getUnmatchableSourceEntries().size()
441 ));
442
443 return memberMatches;
444 }
445
446 private static <T extends Entry> void collectMatchedFields(MemberMatches<T> memberMatches, ClassMapping destClassMapping, ClassMatches classMatches, Doer<T> doer) {
447
448 // get the fields for this class
449 for (MemberMapping<T> destEntryMapping : doer.getMappings(destClassMapping)) {
450 T destObfField = destEntryMapping.getObfEntry(destClassMapping.getObfEntry());
451 T srcObfField = translate(destObfField, classMatches.getUniqueMatches().inverse());
452 memberMatches.addMatch(srcObfField, destObfField);
453 }
454
455 // recurse
456 for (ClassMapping destInnerClassMapping : destClassMapping.innerClasses()) {
457 collectMatchedFields(memberMatches, destInnerClassMapping, classMatches, doer);
458 }
459 }
460
461 @SuppressWarnings("unchecked")
462 private static <T extends Entry> T translate(T in, BiMap<ClassEntry, ClassEntry> map) {
463 if (in instanceof FieldEntry) {
464 return (T) new FieldEntry(
465 map.get(in.getClassEntry()),
466 in.getName(),
467 translate(((FieldEntry) in).getType(), map)
468 );
469 } else if (in instanceof MethodEntry) {
470 return (T) new MethodEntry(
471 map.get(in.getClassEntry()),
472 in.getName(),
473 translate(((MethodEntry) in).getSignature(), map)
474 );
475 } else if (in instanceof ConstructorEntry) {
476 return (T) new ConstructorEntry(
477 map.get(in.getClassEntry()),
478 translate(((ConstructorEntry) in).getSignature(), map)
479 );
480 }
481 throw new Error("Unhandled entry type: " + in.getClass());
482 }
483
484 private static Type translate(Type type, final BiMap<ClassEntry, ClassEntry> map) {
485 return new Type(type, new ClassNameReplacer() {
486 @Override
487 public String replace(String inClassName) {
488 ClassEntry outClassEntry = map.get(new ClassEntry(inClassName));
489 if (outClassEntry == null) {
490 return null;
491 }
492 return outClassEntry.getName();
493 }
494 });
495 }
496
497 private static Signature translate(Signature signature, final BiMap<ClassEntry, ClassEntry> map) {
498 if (signature == null) {
499 return null;
500 }
501 return new Signature(signature, new ClassNameReplacer() {
502 @Override
503 public String replace(String inClassName) {
504 ClassEntry outClassEntry = map.get(new ClassEntry(inClassName));
505 if (outClassEntry == null) {
506 return null;
507 }
508 return outClassEntry.getName();
509 }
510 });
511 }
512
513 public static <T extends Entry> void applyMemberMatches(Mappings mappings, ClassMatches classMatches, MemberMatches<T> memberMatches, Doer<T> doer) {
514 for (ClassMapping classMapping : mappings.classes()) {
515 applyMemberMatches(classMapping, classMatches, memberMatches, doer);
516 }
517 }
518
519 private static <T extends Entry> void applyMemberMatches(ClassMapping classMapping, ClassMatches classMatches, MemberMatches<T> memberMatches, Doer<T> doer) {
520
521 // get the classes
522 ClassEntry obfDestClass = new ClassEntry(classMapping.getObfFullName());
523
524 // make a map of all the renames we need to make
525 Map<T, T> renames = Maps.newHashMap();
526 for (MemberMapping<T> memberMapping : Lists.newArrayList(doer.getMappings(classMapping))) {
527 T obfOldDestEntry = memberMapping.getObfEntry(obfDestClass);
528 T obfSourceEntry = getSourceEntryFromDestMapping(memberMapping, obfDestClass, classMatches);
529
530 // but drop the unmatchable things
531 if (memberMatches.isUnmatchableSourceEntry(obfSourceEntry)) {
532 doer.removeMemberByObf(classMapping, obfOldDestEntry);
533 continue;
534 }
535
536 T obfNewDestEntry = memberMatches.matches().get(obfSourceEntry);
537 if (obfNewDestEntry != null && !obfOldDestEntry.getName().equals(obfNewDestEntry.getName())) {
538 renames.put(obfOldDestEntry, obfNewDestEntry);
539 }
540 }
541
542 if (!renames.isEmpty()) {
543
544 // apply to this class (should never need more than n passes)
545 int numRenamesAppliedThisRound;
546 do {
547 numRenamesAppliedThisRound = 0;
548
549 for (MemberMapping<T> memberMapping : Lists.newArrayList(doer.getMappings(classMapping))) {
550 T obfOldDestEntry = memberMapping.getObfEntry(obfDestClass);
551 T obfNewDestEntry = renames.get(obfOldDestEntry);
552 if (obfNewDestEntry != null) {
553 // make sure this rename won't cause a collision
554 // otherwise, save it for the next round and try again next time
555 if (!doer.hasObfMember(classMapping, obfNewDestEntry)) {
556 doer.setUpdateObfMember(classMapping, memberMapping, obfNewDestEntry);
557 renames.remove(obfOldDestEntry);
558 numRenamesAppliedThisRound++;
559 }
560 }
561 }
562 } while (numRenamesAppliedThisRound > 0);
563
564 if (!renames.isEmpty()) {
565 System.err.println(String.format("WARNING: Couldn't apply all the renames for class %s. %d renames left.",
566 classMapping.getObfFullName(), renames.size()
567 ));
568 for (Map.Entry<T, T> entry : renames.entrySet()) {
569 System.err.println(String.format("\t%s -> %s", entry.getKey().getName(), entry.getValue().getName()));
570 }
571 }
572 }
573
574 // recurse
575 for (ClassMapping innerClassMapping : classMapping.innerClasses()) {
576 applyMemberMatches(innerClassMapping, classMatches, memberMatches, doer);
577 }
578 }
579
580 private static <T extends Entry> T getSourceEntryFromDestMapping(MemberMapping<T> destMemberMapping, ClassEntry obfDestClass, ClassMatches classMatches) {
581 return translate(destMemberMapping.getObfEntry(obfDestClass), classMatches.getUniqueMatches().inverse());
582 }
583}
diff --git a/src/main/java/cuchaz/enigma/convert/MatchesReader.java b/src/main/java/cuchaz/enigma/convert/MatchesReader.java
new file mode 100644
index 0000000..773566d
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/MatchesReader.java
@@ -0,0 +1,109 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.Lists;
14
15import java.io.BufferedReader;
16import java.io.File;
17import java.io.FileReader;
18import java.io.IOException;
19import java.util.Collection;
20import java.util.List;
21
22import cuchaz.enigma.mapping.*;
23
24
25public class MatchesReader {
26
27 public static ClassMatches readClasses(File file)
28 throws IOException {
29 try (BufferedReader in = new BufferedReader(new FileReader(file))) {
30 ClassMatches matches = new ClassMatches();
31 String line = null;
32 while ((line = in.readLine()) != null) {
33 matches.add(readClassMatch(line));
34 }
35 return matches;
36 }
37 }
38
39 private static ClassMatch readClassMatch(String line)
40 throws IOException {
41 String[] sides = line.split(":", 2);
42 return new ClassMatch(readClasses(sides[0]), readClasses(sides[1]));
43 }
44
45 private static Collection<ClassEntry> readClasses(String in) {
46 List<ClassEntry> entries = Lists.newArrayList();
47 for (String className : in.split(",")) {
48 className = className.trim();
49 if (className.length() > 0) {
50 entries.add(new ClassEntry(className));
51 }
52 }
53 return entries;
54 }
55
56 public static <T extends Entry> MemberMatches<T> readMembers(File file)
57 throws IOException {
58 try (BufferedReader in = new BufferedReader(new FileReader(file))) {
59 MemberMatches<T> matches = new MemberMatches<T>();
60 String line = null;
61 while ((line = in.readLine()) != null) {
62 readMemberMatch(matches, line);
63 }
64 return matches;
65 }
66 }
67
68 private static <T extends Entry> void readMemberMatch(MemberMatches<T> matches, String line) {
69 if (line.startsWith("!")) {
70 T source = readEntry(line.substring(1));
71 matches.addUnmatchableSourceEntry(source);
72 } else {
73 String[] parts = line.split(":", 2);
74 T source = readEntry(parts[0]);
75 T dest = readEntry(parts[1]);
76 if (source != null && dest != null) {
77 matches.addMatch(source, dest);
78 } else if (source != null) {
79 matches.addUnmatchedSourceEntry(source);
80 } else if (dest != null) {
81 matches.addUnmatchedDestEntry(dest);
82 }
83 }
84 }
85
86 @SuppressWarnings("unchecked")
87 private static <T extends Entry> T readEntry(String in) {
88 if (in.length() <= 0) {
89 return null;
90 }
91 String[] parts = in.split(" ");
92 if (parts.length == 3 && parts[2].indexOf('(') < 0) {
93 return (T) new FieldEntry(
94 new ClassEntry(parts[0]),
95 parts[1],
96 new Type(parts[2])
97 );
98 } else {
99 assert (parts.length == 2 || parts.length == 3);
100 if (parts.length == 2) {
101 return (T) EntryFactory.getBehaviorEntry(parts[0], parts[1]);
102 } else if (parts.length == 3) {
103 return (T) EntryFactory.getBehaviorEntry(parts[0], parts[1], parts[2]);
104 } else {
105 throw new Error("Malformed behavior entry: " + in);
106 }
107 }
108 }
109}
diff --git a/src/main/java/cuchaz/enigma/convert/MatchesWriter.java b/src/main/java/cuchaz/enigma/convert/MatchesWriter.java
new file mode 100644
index 0000000..baf7929
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/MatchesWriter.java
@@ -0,0 +1,121 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import java.io.File;
14import java.io.FileWriter;
15import java.io.IOException;
16import java.util.Map;
17
18import cuchaz.enigma.mapping.BehaviorEntry;
19import cuchaz.enigma.mapping.ClassEntry;
20import cuchaz.enigma.mapping.Entry;
21import cuchaz.enigma.mapping.FieldEntry;
22
23
24public class MatchesWriter {
25
26 public static void writeClasses(ClassMatches matches, File file)
27 throws IOException {
28 try (FileWriter out = new FileWriter(file)) {
29 for (ClassMatch match : matches) {
30 writeClassMatch(out, match);
31 }
32 }
33 }
34
35 private static void writeClassMatch(FileWriter out, ClassMatch match)
36 throws IOException {
37 writeClasses(out, match.sourceClasses);
38 out.write(":");
39 writeClasses(out, match.destClasses);
40 out.write("\n");
41 }
42
43 private static void writeClasses(FileWriter out, Iterable<ClassEntry> classes)
44 throws IOException {
45 boolean isFirst = true;
46 for (ClassEntry entry : classes) {
47 if (isFirst) {
48 isFirst = false;
49 } else {
50 out.write(",");
51 }
52 out.write(entry.toString());
53 }
54 }
55
56 public static <T extends Entry> void writeMembers(MemberMatches<T> matches, File file)
57 throws IOException {
58 try (FileWriter out = new FileWriter(file)) {
59 for (Map.Entry<T, T> match : matches.matches().entrySet()) {
60 writeMemberMatch(out, match.getKey(), match.getValue());
61 }
62 for (T entry : matches.getUnmatchedSourceEntries()) {
63 writeMemberMatch(out, entry, null);
64 }
65 for (T entry : matches.getUnmatchedDestEntries()) {
66 writeMemberMatch(out, null, entry);
67 }
68 for (T entry : matches.getUnmatchableSourceEntries()) {
69 writeUnmatchableEntry(out, entry);
70 }
71 }
72 }
73
74 private static <T extends Entry> void writeMemberMatch(FileWriter out, T source, T dest)
75 throws IOException {
76 if (source != null) {
77 writeEntry(out, source);
78 }
79 out.write(":");
80 if (dest != null) {
81 writeEntry(out, dest);
82 }
83 out.write("\n");
84 }
85
86 private static <T extends Entry> void writeUnmatchableEntry(FileWriter out, T entry)
87 throws IOException {
88 out.write("!");
89 writeEntry(out, entry);
90 out.write("\n");
91 }
92
93 private static <T extends Entry> void writeEntry(FileWriter out, T entry)
94 throws IOException {
95 if (entry instanceof FieldEntry) {
96 writeField(out, (FieldEntry) entry);
97 } else if (entry instanceof BehaviorEntry) {
98 writeBehavior(out, (BehaviorEntry) entry);
99 }
100 }
101
102 private static void writeField(FileWriter out, FieldEntry fieldEntry)
103 throws IOException {
104 out.write(fieldEntry.getClassName());
105 out.write(" ");
106 out.write(fieldEntry.getName());
107 out.write(" ");
108 out.write(fieldEntry.getType().toString());
109 }
110
111 private static void writeBehavior(FileWriter out, BehaviorEntry behaviorEntry)
112 throws IOException {
113 out.write(behaviorEntry.getClassName());
114 out.write(" ");
115 out.write(behaviorEntry.getName());
116 out.write(" ");
117 if (behaviorEntry.getSignature() != null) {
118 out.write(behaviorEntry.getSignature().toString());
119 }
120 }
121}
diff --git a/src/main/java/cuchaz/enigma/convert/MemberMatches.java b/src/main/java/cuchaz/enigma/convert/MemberMatches.java
new file mode 100644
index 0000000..32850cc
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/MemberMatches.java
@@ -0,0 +1,155 @@
1/*******************************************************************************
2 * Copyright (c) 2015 Jeff Martin.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the GNU Lesser General Public
5 * License v3.0 which accompanies this distribution, and is available at
6 * http://www.gnu.org/licenses/lgpl.html
7 * <p>
8 * Contributors:
9 * Jeff Martin - initial API and implementation
10 ******************************************************************************/
11package cuchaz.enigma.convert;
12
13import com.google.common.collect.*;
14
15import java.util.Collection;
16import java.util.Set;
17
18import cuchaz.enigma.mapping.ClassEntry;
19import cuchaz.enigma.mapping.Entry;
20
21
22public class MemberMatches<T extends Entry> {
23
24 private BiMap<T, T> m_matches;
25 private Multimap<ClassEntry, T> m_matchedSourceEntries;
26 private Multimap<ClassEntry, T> m_unmatchedSourceEntries;
27 private Multimap<ClassEntry, T> m_unmatchedDestEntries;
28 private Multimap<ClassEntry, T> m_unmatchableSourceEntries;
29
30 public MemberMatches() {
31 m_matches = HashBiMap.create();
32 m_matchedSourceEntries = HashMultimap.create();
33 m_unmatchedSourceEntries = HashMultimap.create();
34 m_unmatchedDestEntries = HashMultimap.create();
35 m_unmatchableSourceEntries = HashMultimap.create();
36 }
37
38 public void addMatch(T srcEntry, T destEntry) {
39 boolean wasAdded = m_matches.put(srcEntry, destEntry) == null;
40 assert (wasAdded);
41 wasAdded = m_matchedSourceEntries.put(srcEntry.getClassEntry(), srcEntry);
42 assert (wasAdded);
43 }
44
45 public void addUnmatchedSourceEntry(T sourceEntry) {
46 boolean wasAdded = m_unmatchedSourceEntries.put(sourceEntry.getClassEntry(), sourceEntry);
47 assert (wasAdded);
48 }
49
50 public void addUnmatchedSourceEntries(Iterable<T> sourceEntries) {
51 for (T sourceEntry : sourceEntries) {
52 addUnmatchedSourceEntry(sourceEntry);
53 }
54 }
55
56 public void addUnmatchedDestEntry(T destEntry) {
57 boolean wasAdded = m_unmatchedDestEntries.put(destEntry.getClassEntry(), destEntry);
58 assert (wasAdded);
59 }
60
61 public void addUnmatchedDestEntries(Iterable<T> destEntriesntries) {
62 for (T entry : destEntriesntries) {
63 addUnmatchedDestEntry(entry);
64 }
65 }
66
67 public void addUnmatchableSourceEntry(T sourceEntry) {
68 boolean wasAdded = m_unmatchableSourceEntries.put(sourceEntry.getClassEntry(), sourceEntry);
69 assert (wasAdded);
70 }
71
72 public Set<ClassEntry> getSourceClassesWithUnmatchedEntries() {
73 return m_unmatchedSourceEntries.keySet();
74 }
75
76 public Collection<ClassEntry> getSourceClassesWithoutUnmatchedEntries() {
77 Set<ClassEntry> out = Sets.newHashSet();
78 out.addAll(m_matchedSourceEntries.keySet());
79 out.removeAll(m_unmatchedSourceEntries.keySet());
80 return out;
81 }
82
83 public Collection<T> getUnmatchedSourceEntries() {
84 return m_unmatchedSourceEntries.values();
85 }
86
87 public Collection<T> getUnmatchedSourceEntries(ClassEntry sourceClass) {
88 return m_unmatchedSourceEntries.get(sourceClass);
89 }
90
91 public Collection<T> getUnmatchedDestEntries() {
92 return m_unmatchedDestEntries.values();
93 }
94
95 public Collection<T> getUnmatchedDestEntries(ClassEntry destClass) {
96 return m_unmatchedDestEntries.get(destClass);
97 }
98
99 public Collection<T> getUnmatchableSourceEntries() {
100 return m_unmatchableSourceEntries.values();
101 }
102
103 public boolean hasSource(T sourceEntry) {
104 return m_matches.containsKey(sourceEntry) || m_unmatchedSourceEntries.containsValue(sourceEntry);
105 }
106
107 public boolean hasDest(T destEntry) {
108 return m_matches.containsValue(destEntry) || m_unmatchedDestEntries.containsValue(destEntry);
109 }
110
111 public BiMap<T, T> matches() {
112 return m_matches;
113 }
114
115 public boolean isMatchedSourceEntry(T sourceEntry) {
116 return m_matches.containsKey(sourceEntry);
117 }
118
119 public boolean isMatchedDestEntry(T destEntry) {
120 return m_matches.containsValue(destEntry);
121 }
122
123 public boolean isUnmatchableSourceEntry(T sourceEntry) {
124 return m_unmatchableSourceEntries.containsEntry(sourceEntry.getClassEntry(), sourceEntry);
125 }
126
127 public void makeMatch(T sourceEntry, T destEntry) {
128 boolean wasRemoved = m_unmatchedSourceEntries.remove(sourceEntry.getClassEntry(), sourceEntry);
129 assert (wasRemoved);
130 wasRemoved = m_unmatchedDestEntries.remove(destEntry.getClassEntry(), destEntry);
131 assert (wasRemoved);
132 addMatch(sourceEntry, destEntry);
133 }
134
135 public boolean isMatched(T sourceEntry, T destEntry) {
136 T match = m_matches.get(sourceEntry);
137 return match != null && match.equals(destEntry);
138 }
139
140 public void unmakeMatch(T sourceEntry, T destEntry) {
141 boolean wasRemoved = m_matches.remove(sourceEntry) != null;
142 assert (wasRemoved);
143 wasRemoved = m_matchedSourceEntries.remove(sourceEntry.getClassEntry(), sourceEntry);
144 assert (wasRemoved);
145 addUnmatchedSourceEntry(sourceEntry);
146 addUnmatchedDestEntry(destEntry);
147 }
148
149 public void makeSourceUnmatchable(T sourceEntry) {
150 assert (!isMatchedSourceEntry(sourceEntry));
151 boolean wasRemoved = m_unmatchedSourceEntries.remove(sourceEntry.getClassEntry(), sourceEntry);
152 assert (wasRemoved);
153 addUnmatchableSourceEntry(sourceEntry);
154 }
155}