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