summaryrefslogtreecommitdiff
path: root/src/main/java/cuchaz/enigma/convert
diff options
context:
space:
mode:
authorGravatar lclc982016-06-30 00:49:21 +1000
committerGravatar GitHub2016-06-30 00:49:21 +1000
commit4be005617b3b8c3578cca07c5d085d12916f0d1d (patch)
treedb163431f38703e26da417ef05eaea2b27a498b9 /src/main/java/cuchaz/enigma/convert
parentSome small changes to fix idea importing (diff)
downloadenigma-fork-4be005617b3b8c3578cca07c5d085d12916f0d1d.tar.gz
enigma-fork-4be005617b3b8c3578cca07c5d085d12916f0d1d.tar.xz
enigma-fork-4be005617b3b8c3578cca07c5d085d12916f0d1d.zip
Json format (#2)
* Added new format * Fixed bug * Updated Version
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.java54
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassIdentity.java444
-rw-r--r--src/main/java/cuchaz/enigma/convert/ClassMatch.java88
-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.java582
-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, 2134 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..7123bbf
--- /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 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/main/java/cuchaz/enigma/convert/ClassIdentifier.java b/src/main/java/cuchaz/enigma/convert/ClassIdentifier.java
new file mode 100644
index 0000000..e1153a6
--- /dev/null
+++ b/src/main/java/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 * <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 javassist.CtClass;
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/main/java/cuchaz/enigma/convert/ClassIdentity.java b/src/main/java/cuchaz/enigma/convert/ClassIdentity.java
new file mode 100644
index 0000000..76c48ab
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/ClassIdentity.java
@@ -0,0 +1,444 @@
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 m_classEntry;
40 private SidedClassNamer m_namer;
41 private Multiset<String> m_fields;
42 private Multiset<String> m_methods;
43 private Multiset<String> m_constructors;
44 private String m_staticInitializer;
45 private String m_extends;
46 private Multiset<String> m_implements;
47 private Set<String> m_stringLiterals;
48 private Multiset<String> m_implementations;
49 private Multiset<String> m_references;
50 private String m_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.NonePackage)) {
62 return className;
63 }
64
65 // is this class ourself?
66 if (className.equals(m_classEntry.getName())) {
67 return "CSelf";
68 }
69
70 // try the namer
71 if (m_namer != null) {
72 String newName = m_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 m_namer = namer;
92
93 // stuff from the bytecode
94
95 m_classEntry = EntryFactory.getClassEntry(c);
96 m_fields = HashMultiset.create();
97 for (CtField field : c.getDeclaredFields()) {
98 m_fields.add(scrubType(field.getSignature()));
99 }
100 m_methods = HashMultiset.create();
101 for (CtMethod method : c.getDeclaredMethods()) {
102 m_methods.add(scrubSignature(method.getSignature()) + "0x" + getBehaviorSignature(method));
103 }
104 m_constructors = HashMultiset.create();
105 for (CtConstructor constructor : c.getDeclaredConstructors()) {
106 m_constructors.add(scrubSignature(constructor.getSignature()) + "0x" + getBehaviorSignature(constructor));
107 }
108 m_staticInitializer = "";
109 if (c.getClassInitializer() != null) {
110 m_staticInitializer = getBehaviorSignature(c.getClassInitializer());
111 }
112 m_extends = "";
113 if (c.getClassFile().getSuperclass() != null) {
114 m_extends = scrubClassName(Descriptor.toJvmName(c.getClassFile().getSuperclass()));
115 }
116 m_implements = HashMultiset.create();
117 for (String interfaceName : c.getClassFile().getInterfaces()) {
118 m_implements.add(scrubClassName(Descriptor.toJvmName(interfaceName)));
119 }
120
121 m_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 m_stringLiterals.add(constants.getStringInfo(i));
126 }
127 }
128
129 // stuff from the jar index
130
131 m_implementations = HashMultiset.create();
132 ClassImplementationsTreeNode implementationsNode = index.getClassImplementations(null, m_classEntry);
133 if (implementationsNode != null) {
134 @SuppressWarnings("unchecked")
135 Enumeration<ClassImplementationsTreeNode> implementations = implementationsNode.children();
136 while (implementations.hasMoreElements()) {
137 ClassImplementationsTreeNode node = implementations.nextElement();
138 m_implementations.add(scrubClassName(node.getClassEntry().getName()));
139 }
140 }
141
142 m_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 m_outer = null;
155 if (m_classEntry.isInnerClass()) {
156 m_outer = m_classEntry.getOuterClassName();
157 }
158 }
159
160 private void addReference(EntryReference<? extends Entry, BehaviorEntry> reference) {
161 if (reference.context.getSignature() != null) {
162 m_references.add(String.format("%s_%s",
163 scrubClassName(reference.context.getClassName()),
164 scrubSignature(reference.context.getSignature())
165 ));
166 } else {
167 m_references.add(String.format("%s_<clinit>",
168 scrubClassName(reference.context.getClassName())
169 ));
170 }
171 }
172
173 public ClassEntry getClassEntry() {
174 return m_classEntry;
175 }
176
177 @Override
178 public String toString() {
179 StringBuilder buf = new StringBuilder();
180 buf.append("class: ");
181 buf.append(m_classEntry.getName());
182 buf.append(" ");
183 buf.append(hashCode());
184 buf.append("\n");
185 for (String field : m_fields) {
186 buf.append("\tfield ");
187 buf.append(field);
188 buf.append("\n");
189 }
190 for (String method : m_methods) {
191 buf.append("\tmethod ");
192 buf.append(method);
193 buf.append("\n");
194 }
195 for (String constructor : m_constructors) {
196 buf.append("\tconstructor ");
197 buf.append(constructor);
198 buf.append("\n");
199 }
200 if (m_staticInitializer.length() > 0) {
201 buf.append("\tinitializer ");
202 buf.append(m_staticInitializer);
203 buf.append("\n");
204 }
205 if (m_extends.length() > 0) {
206 buf.append("\textends ");
207 buf.append(m_extends);
208 buf.append("\n");
209 }
210 for (String interfaceName : m_implements) {
211 buf.append("\timplements ");
212 buf.append(interfaceName);
213 buf.append("\n");
214 }
215 for (String implementation : m_implementations) {
216 buf.append("\timplemented by ");
217 buf.append(implementation);
218 buf.append("\n");
219 }
220 for (String reference : m_references) {
221 buf.append("\treference ");
222 buf.append(reference);
223 buf.append("\n");
224 }
225 buf.append("\touter ");
226 buf.append(m_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 m_namer != null && m_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 if (other instanceof ClassIdentity) {
365 return equals((ClassIdentity) other);
366 }
367 return false;
368 }
369
370 public boolean equals(ClassIdentity other) {
371 return m_fields.equals(other.m_fields)
372 && m_methods.equals(other.m_methods)
373 && m_constructors.equals(other.m_constructors)
374 && m_staticInitializer.equals(other.m_staticInitializer)
375 && m_extends.equals(other.m_extends)
376 && m_implements.equals(other.m_implements)
377 && m_implementations.equals(other.m_implementations)
378 && m_references.equals(other.m_references);
379 }
380
381 @Override
382 public int hashCode() {
383 List<Object> objs = Lists.newArrayList();
384 objs.addAll(m_fields);
385 objs.addAll(m_methods);
386 objs.addAll(m_constructors);
387 objs.add(m_staticInitializer);
388 objs.add(m_extends);
389 objs.addAll(m_implements);
390 objs.addAll(m_implementations);
391 objs.addAll(m_references);
392 return Util.combineHashesOrdered(objs);
393 }
394
395 public int getMatchScore(ClassIdentity other) {
396 return 2 * getNumMatches(m_extends, other.m_extends)
397 + 2 * getNumMatches(m_outer, other.m_outer)
398 + 2 * getNumMatches(m_implements, other.m_implements)
399 + getNumMatches(m_stringLiterals, other.m_stringLiterals)
400 + getNumMatches(m_fields, other.m_fields)
401 + getNumMatches(m_methods, other.m_methods)
402 + getNumMatches(m_constructors, other.m_constructors);
403 }
404
405 public int getMaxMatchScore() {
406 return 2 + 2 + 2 * m_implements.size() + m_stringLiterals.size() + m_fields.size() + m_methods.size() + m_constructors.size();
407 }
408
409 public boolean matches(CtClass c) {
410 // just compare declaration counts
411 return m_fields.size() == c.getDeclaredFields().length
412 && m_methods.size() == c.getDeclaredMethods().length
413 && m_constructors.size() == c.getDeclaredConstructors().length;
414 }
415
416 private int getNumMatches(Set<String> a, Set<String> b) {
417 int numMatches = 0;
418 for (String val : a) {
419 if (b.contains(val)) {
420 numMatches++;
421 }
422 }
423 return numMatches;
424 }
425
426 private int getNumMatches(Multiset<String> a, Multiset<String> b) {
427 int numMatches = 0;
428 for (String val : a) {
429 if (b.contains(val)) {
430 numMatches++;
431 }
432 }
433 return numMatches;
434 }
435
436 private int getNumMatches(String a, String b) {
437 if (a == null && b == null) {
438 return 1;
439 } else if (a != null && b != null && a.equals(b)) {
440 return 1;
441 }
442 return 0;
443 }
444}
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..f3530ed
--- /dev/null
+++ b/src/main/java/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 * <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 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/main/java/cuchaz/enigma/convert/ClassMatches.java b/src/main/java/cuchaz/enigma/convert/ClassMatches.java
new file mode 100644
index 0000000..2c5f6a5
--- /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<ClassMatch>());
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..14f8e2a
--- /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<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/main/java/cuchaz/enigma/convert/ClassNamer.java b/src/main/java/cuchaz/enigma/convert/ClassNamer.java
new file mode 100644
index 0000000..f1d9820
--- /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> 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 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..394b8c8
--- /dev/null
+++ b/src/main/java/cuchaz/enigma/convert/MappingsConverter.java
@@ -0,0 +1,582 @@
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.*;
23
24public class MappingsConverter {
25
26 public static ClassMatches computeClassMatches(JarFile sourceJar, JarFile destJar, Mappings mappings) {
27
28 // index jars
29 System.out.println("Indexing source jar...");
30 JarIndex sourceIndex = new JarIndex();
31 sourceIndex.indexJar(sourceJar, false);
32 System.out.println("Indexing dest jar...");
33 JarIndex destIndex = new JarIndex();
34 destIndex.indexJar(destJar, false);
35
36 // compute the matching
37 ClassMatching matching = computeMatching(sourceJar, sourceIndex, destJar, destIndex, null);
38 return new ClassMatches(matching.matches());
39 }
40
41 public static ClassMatching computeMatching(JarFile sourceJar, JarIndex sourceIndex, JarFile destJar, JarIndex destIndex, BiMap<ClassEntry, ClassEntry> knownMatches) {
42
43 System.out.println("Iteratively matching classes");
44
45 ClassMatching lastMatching = null;
46 int round = 0;
47 SidedClassNamer sourceNamer = null;
48 SidedClassNamer destNamer = null;
49 for (boolean useReferences : Arrays.asList(false, true)) {
50
51 int numUniqueMatchesLastTime = 0;
52 if (lastMatching != null) {
53 numUniqueMatchesLastTime = lastMatching.uniqueMatches().size();
54 }
55
56 while (true) {
57
58 System.out.println("Round " + (++round) + "...");
59
60 // init the matching with identity settings
61 ClassMatching matching = new ClassMatching(
62 new ClassIdentifier(sourceJar, sourceIndex, sourceNamer, useReferences),
63 new ClassIdentifier(destJar, destIndex, destNamer, useReferences)
64 );
65
66 if (knownMatches != null) {
67 matching.addKnownMatches(knownMatches);
68 }
69
70 if (lastMatching == null) {
71 // search all classes
72 matching.match(sourceIndex.getObfClassEntries(), destIndex.getObfClassEntries());
73 } else {
74 // we already know about these matches from last time
75 matching.addKnownMatches(lastMatching.uniqueMatches());
76
77 // search unmatched and ambiguously-matched classes
78 matching.match(lastMatching.unmatchedSourceClasses(), lastMatching.unmatchedDestClasses());
79 for (ClassMatch match : lastMatching.ambiguousMatches()) {
80 matching.match(match.sourceClasses, match.destClasses);
81 }
82 }
83 System.out.println(matching);
84 BiMap<ClassEntry, ClassEntry> uniqueMatches = matching.uniqueMatches();
85
86 // did we match anything new this time?
87 if (uniqueMatches.size() > numUniqueMatchesLastTime) {
88 numUniqueMatchesLastTime = uniqueMatches.size();
89 lastMatching = matching;
90 } else {
91 break;
92 }
93
94 // update the namers
95 ClassNamer namer = new ClassNamer(uniqueMatches);
96 sourceNamer = namer.getSourceNamer();
97 destNamer = namer.getDestNamer();
98 }
99 }
100
101 return lastMatching;
102 }
103
104 public static Mappings newMappings(ClassMatches matches, Mappings oldMappings, Deobfuscator sourceDeobfuscator, Deobfuscator destDeobfuscator) {
105
106 // sort the unique matches by size of inner class chain
107 Multimap<Integer, java.util.Map.Entry<ClassEntry, ClassEntry>> matchesByDestChainSize = HashMultimap.create();
108 for (java.util.Map.Entry<ClassEntry, ClassEntry> match : matches.getUniqueMatches().entrySet()) {
109 int chainSize = destDeobfuscator.getJarIndex().getObfClassChain(match.getValue()).size();
110 matchesByDestChainSize.put(chainSize, match);
111 }
112
113 // build the mappings (in order of small-to-large inner chains)
114 Mappings newMappings = new Mappings();
115 List<Integer> chainSizes = Lists.newArrayList(matchesByDestChainSize.keySet());
116 Collections.sort(chainSizes);
117 for (int chainSize : chainSizes) {
118 for (java.util.Map.Entry<ClassEntry, ClassEntry> match : matchesByDestChainSize.get(chainSize)) {
119
120 // get class info
121 ClassEntry obfSourceClassEntry = match.getKey();
122 ClassEntry obfDestClassEntry = match.getValue();
123 List<ClassEntry> destClassChain = destDeobfuscator.getJarIndex().getObfClassChain(obfDestClassEntry);
124
125 ClassMapping sourceMapping = sourceDeobfuscator.getMappings().getClassByObf(obfSourceClassEntry);
126 if (sourceMapping == null) {
127 // if this class was never deobfuscated, don't try to match it
128 continue;
129 }
130
131 // find out where to make the dest class mapping
132 if (destClassChain.size() == 1) {
133 // not an inner class, add directly to mappings
134 newMappings.addClassMapping(migrateClassMapping(obfDestClassEntry, sourceMapping, matches, false));
135 } else {
136 // inner class, find the outer class mapping
137 ClassMapping destMapping = null;
138 for (int i = 0; i < destClassChain.size() - 1; i++) {
139 ClassEntry destChainClassEntry = destClassChain.get(i);
140 if (destMapping == null) {
141 destMapping = newMappings.getClassByObf(destChainClassEntry);
142 if (destMapping == null) {
143 destMapping = new ClassMapping(destChainClassEntry.getName());
144 newMappings.addClassMapping(destMapping);
145 }
146 } else {
147 destMapping = destMapping.getInnerClassByObfSimple(destChainClassEntry.getInnermostClassName());
148 if (destMapping == null) {
149 destMapping = new ClassMapping(destChainClassEntry.getName());
150 destMapping.addInnerClassMapping(destMapping);
151 }
152 }
153 }
154 destMapping.addInnerClassMapping(migrateClassMapping(obfDestClassEntry, sourceMapping, matches, true));
155 }
156 }
157 }
158 return newMappings;
159 }
160
161 private static ClassMapping migrateClassMapping(ClassEntry newObfClass, ClassMapping oldClassMapping, final ClassMatches matches, boolean useSimpleName) {
162
163 ClassNameReplacer replacer = new ClassNameReplacer() {
164 @Override
165 public String replace(String className) {
166 ClassEntry newClassEntry = matches.getUniqueMatches().get(new ClassEntry(className));
167 if (newClassEntry != null) {
168 return newClassEntry.getName();
169 }
170 return null;
171 }
172 };
173
174 ClassMapping newClassMapping;
175 String deobfName = oldClassMapping.getDeobfName();
176 if (deobfName != null) {
177 if (useSimpleName) {
178 deobfName = new ClassEntry(deobfName).getSimpleName();
179 }
180 newClassMapping = new ClassMapping(newObfClass.getName(), deobfName);
181 } else {
182 newClassMapping = new ClassMapping(newObfClass.getName());
183 }
184
185 // migrate fields
186 for (FieldMapping oldFieldMapping : oldClassMapping.fields()) {
187 if (canMigrate(oldFieldMapping.getObfType(), matches)) {
188 newClassMapping.addFieldMapping(new FieldMapping(oldFieldMapping, replacer));
189 } else {
190 System.out.println(String.format("Can't map field, dropping: %s.%s %s",
191 oldClassMapping.getDeobfName(),
192 oldFieldMapping.getDeobfName(),
193 oldFieldMapping.getObfType()
194 ));
195 }
196 }
197
198 // migrate methods
199 for (MethodMapping oldMethodMapping : oldClassMapping.methods()) {
200 if (canMigrate(oldMethodMapping.getObfSignature(), matches)) {
201 newClassMapping.addMethodMapping(new MethodMapping(oldMethodMapping, replacer));
202 } else {
203 System.out.println(String.format("Can't map method, dropping: %s.%s %s",
204 oldClassMapping.getDeobfName(),
205 oldMethodMapping.getDeobfName(),
206 oldMethodMapping.getObfSignature()
207 ));
208 }
209 }
210
211 return newClassMapping;
212 }
213
214 private static boolean canMigrate(Signature oldObfSignature, ClassMatches classMatches) {
215 for (Type oldObfType : oldObfSignature.types()) {
216 if (!canMigrate(oldObfType, classMatches)) {
217 return false;
218 }
219 }
220 return true;
221 }
222
223 private static boolean canMigrate(Type oldObfType, ClassMatches classMatches) {
224
225 // non classes can be migrated
226 if (!oldObfType.hasClass()) {
227 return true;
228 }
229
230 // non obfuscated classes can be migrated
231 ClassEntry classEntry = oldObfType.getClassEntry();
232 if (!classEntry.getPackageName().equals(Constants.NonePackage)) {
233 return true;
234 }
235
236 // obfuscated classes with mappings can be migrated
237 return classMatches.getUniqueMatches().containsKey(classEntry);
238 }
239
240 public static void convertMappings(Mappings mappings, BiMap<ClassEntry, ClassEntry> changes) {
241
242 // sort the changes so classes are renamed in the correct order
243 // ie. if we have the mappings a->b, b->c, we have to apply b->c before a->b
244 LinkedHashMap<ClassEntry, ClassEntry> sortedChanges = Maps.newLinkedHashMap();
245 int numChangesLeft = changes.size();
246 while (!changes.isEmpty()) {
247 Iterator<Map.Entry<ClassEntry, ClassEntry>> iter = changes.entrySet().iterator();
248 while (iter.hasNext()) {
249 Map.Entry<ClassEntry, ClassEntry> change = iter.next();
250 if (changes.containsKey(change.getValue())) {
251 sortedChanges.put(change.getKey(), change.getValue());
252 iter.remove();
253 }
254 }
255
256 // did we remove any changes?
257 if (numChangesLeft - changes.size() > 0) {
258 // keep going
259 numChangesLeft = changes.size();
260 } else {
261 // can't sort anymore. There must be a loop
262 break;
263 }
264 }
265 if (!changes.isEmpty()) {
266 throw new Error("Unable to sort class changes! There must be a cycle.");
267 }
268
269 // convert the mappings in the correct class order
270 for (Map.Entry<ClassEntry, ClassEntry> entry : sortedChanges.entrySet()) {
271 mappings.renameObfClass(entry.getKey().getName(), entry.getValue().getName());
272 }
273 }
274
275 public interface Doer<T extends Entry> {
276 Collection<T> getDroppedEntries(MappingsChecker checker);
277
278 Collection<T> getObfEntries(JarIndex jarIndex);
279
280 Collection<? extends MemberMapping<T>> getMappings(ClassMapping destClassMapping);
281
282 Set<T> filterEntries(Collection<T> obfEntries, T obfSourceEntry, ClassMatches classMatches);
283
284 void setUpdateObfMember(ClassMapping classMapping, MemberMapping<T> memberMapping, T newEntry);
285
286 boolean hasObfMember(ClassMapping classMapping, T obfEntry);
287
288 void removeMemberByObf(ClassMapping classMapping, T obfEntry);
289 }
290
291 public static Doer<FieldEntry> getFieldDoer() {
292 return new Doer<FieldEntry>() {
293
294 @Override
295 public Collection<FieldEntry> getDroppedEntries(MappingsChecker checker) {
296 return checker.getDroppedFieldMappings().keySet();
297 }
298
299 @Override
300 public Collection<FieldEntry> getObfEntries(JarIndex jarIndex) {
301 return jarIndex.getObfFieldEntries();
302 }
303
304 @Override
305 public Collection<? extends MemberMapping<FieldEntry>> getMappings(ClassMapping destClassMapping) {
306 return (Collection<? extends MemberMapping<FieldEntry>>) destClassMapping.fields();
307 }
308
309 @Override
310 public Set<FieldEntry> filterEntries(Collection<FieldEntry> obfDestFields, FieldEntry obfSourceField, ClassMatches classMatches) {
311 Set<FieldEntry> out = Sets.newHashSet();
312 for (FieldEntry obfDestField : obfDestFields) {
313 Type translatedDestType = translate(obfDestField.getType(), classMatches.getUniqueMatches().inverse());
314 if (translatedDestType.equals(obfSourceField.getType())) {
315 out.add(obfDestField);
316 }
317 }
318 return out;
319 }
320
321 @Override
322 public void setUpdateObfMember(ClassMapping classMapping, MemberMapping<FieldEntry> memberMapping, FieldEntry newField) {
323 FieldMapping fieldMapping = (FieldMapping) memberMapping;
324 classMapping.setFieldObfNameAndType(fieldMapping.getObfName(), fieldMapping.getObfType(), newField.getName(), newField.getType());
325 }
326
327 @Override
328 public boolean hasObfMember(ClassMapping classMapping, FieldEntry obfField) {
329 return classMapping.getFieldByObf(obfField.getName(), obfField.getType()) != null;
330 }
331
332 @Override
333 public void removeMemberByObf(ClassMapping classMapping, FieldEntry obfField) {
334 classMapping.removeFieldMapping(classMapping.getFieldByObf(obfField.getName(), obfField.getType()));
335 }
336 };
337 }
338
339 public static Doer<BehaviorEntry> getMethodDoer() {
340 return new Doer<BehaviorEntry>() {
341
342 @Override
343 public Collection<BehaviorEntry> getDroppedEntries(MappingsChecker checker) {
344 return checker.getDroppedMethodMappings().keySet();
345 }
346
347 @Override
348 public Collection<BehaviorEntry> getObfEntries(JarIndex jarIndex) {
349 return jarIndex.getObfBehaviorEntries();
350 }
351
352 @Override
353 public Collection<? extends MemberMapping<BehaviorEntry>> getMappings(ClassMapping destClassMapping) {
354 return (Collection<? extends MemberMapping<BehaviorEntry>>) destClassMapping.methods();
355 }
356
357 @Override
358 public Set<BehaviorEntry> filterEntries(Collection<BehaviorEntry> obfDestFields, BehaviorEntry obfSourceField, ClassMatches classMatches) {
359 Set<BehaviorEntry> out = Sets.newHashSet();
360 for (BehaviorEntry obfDestField : obfDestFields) {
361 Signature translatedDestSignature = translate(obfDestField.getSignature(), classMatches.getUniqueMatches().inverse());
362 if (translatedDestSignature == null && obfSourceField.getSignature() == null) {
363 out.add(obfDestField);
364 } else if (translatedDestSignature == null || obfSourceField.getSignature() == null) {
365 // skip it
366 } else if (translatedDestSignature.equals(obfSourceField.getSignature())) {
367 out.add(obfDestField);
368 }
369 }
370 return out;
371 }
372
373 @Override
374 public void setUpdateObfMember(ClassMapping classMapping, MemberMapping<BehaviorEntry> memberMapping, BehaviorEntry newBehavior) {
375 MethodMapping methodMapping = (MethodMapping) memberMapping;
376 classMapping.setMethodObfNameAndSignature(methodMapping.getObfName(), methodMapping.getObfSignature(), newBehavior.getName(), newBehavior.getSignature());
377 }
378
379 @Override
380 public boolean hasObfMember(ClassMapping classMapping, BehaviorEntry obfBehavior) {
381 return classMapping.getMethodByObf(obfBehavior.getName(), obfBehavior.getSignature()) != null;
382 }
383
384 @Override
385 public void removeMemberByObf(ClassMapping classMapping, BehaviorEntry obfBehavior) {
386 classMapping.removeMethodMapping(classMapping.getMethodByObf(obfBehavior.getName(), obfBehavior.getSignature()));
387 }
388 };
389 }
390
391 public static <T extends Entry> MemberMatches<T> computeMemberMatches(Deobfuscator destDeobfuscator, Mappings destMappings, ClassMatches classMatches, Doer<T> doer) {
392
393 MemberMatches<T> memberMatches = new MemberMatches<T>();
394
395 // unmatched source fields are easy
396 MappingsChecker checker = new MappingsChecker(destDeobfuscator.getJarIndex());
397 checker.dropBrokenMappings(destMappings);
398 for (T destObfEntry : doer.getDroppedEntries(checker)) {
399 T srcObfEntry = translate(destObfEntry, classMatches.getUniqueMatches().inverse());
400 memberMatches.addUnmatchedSourceEntry(srcObfEntry);
401 }
402
403 // get matched fields (anything that's left after the checks/drops is matched(
404 for (ClassMapping classMapping : destMappings.classes()) {
405 collectMatchedFields(memberMatches, classMapping, classMatches, doer);
406 }
407
408 // get unmatched dest fields
409 for (T destEntry : doer.getObfEntries(destDeobfuscator.getJarIndex())) {
410 if (!memberMatches.isMatchedDestEntry(destEntry)) {
411 memberMatches.addUnmatchedDestEntry(destEntry);
412 }
413 }
414
415 System.out.println("Automatching " + memberMatches.getUnmatchedSourceEntries().size() + " unmatched source entries...");
416
417 // go through the unmatched source fields and try to pick out the easy matches
418 for (ClassEntry obfSourceClass : Lists.newArrayList(memberMatches.getSourceClassesWithUnmatchedEntries())) {
419 for (T obfSourceEntry : Lists.newArrayList(memberMatches.getUnmatchedSourceEntries(obfSourceClass))) {
420
421 // get the possible dest matches
422 ClassEntry obfDestClass = classMatches.getUniqueMatches().get(obfSourceClass);
423
424 // filter by type/signature
425 Set<T> obfDestEntries = doer.filterEntries(memberMatches.getUnmatchedDestEntries(obfDestClass), obfSourceEntry, classMatches);
426
427 if (obfDestEntries.size() == 1) {
428 // make the easy match
429 memberMatches.makeMatch(obfSourceEntry, obfDestEntries.iterator().next());
430 } else if (obfDestEntries.isEmpty()) {
431 // no match is possible =(
432 memberMatches.makeSourceUnmatchable(obfSourceEntry);
433 }
434 }
435 }
436
437 System.out.println(String.format("Ended up with %d ambiguous and %d unmatchable source entries",
438 memberMatches.getUnmatchedSourceEntries().size(),
439 memberMatches.getUnmatchableSourceEntries().size()
440 ));
441
442 return memberMatches;
443 }
444
445 private static <T extends Entry> void collectMatchedFields(MemberMatches<T> memberMatches, ClassMapping destClassMapping, ClassMatches classMatches, Doer<T> doer) {
446
447 // get the fields for this class
448 for (MemberMapping<T> destEntryMapping : doer.getMappings(destClassMapping)) {
449 T destObfField = destEntryMapping.getObfEntry(destClassMapping.getObfEntry());
450 T srcObfField = translate(destObfField, classMatches.getUniqueMatches().inverse());
451 memberMatches.addMatch(srcObfField, destObfField);
452 }
453
454 // recurse
455 for (ClassMapping destInnerClassMapping : destClassMapping.innerClasses()) {
456 collectMatchedFields(memberMatches, destInnerClassMapping, classMatches, doer);
457 }
458 }
459
460 @SuppressWarnings("unchecked")
461 private static <T extends Entry> T translate(T in, BiMap<ClassEntry, ClassEntry> map) {
462 if (in instanceof FieldEntry) {
463 return (T) new FieldEntry(
464 map.get(in.getClassEntry()),
465 in.getName(),
466 translate(((FieldEntry) in).getType(), map)
467 );
468 } else if (in instanceof MethodEntry) {
469 return (T) new MethodEntry(
470 map.get(in.getClassEntry()),
471 in.getName(),
472 translate(((MethodEntry) in).getSignature(), map)
473 );
474 } else if (in instanceof ConstructorEntry) {
475 return (T) new ConstructorEntry(
476 map.get(in.getClassEntry()),
477 translate(((ConstructorEntry) in).getSignature(), map)
478 );
479 }
480 throw new Error("Unhandled entry type: " + in.getClass());
481 }
482
483 private static Type translate(Type type, final BiMap<ClassEntry, ClassEntry> map) {
484 return new Type(type, new ClassNameReplacer() {
485 @Override
486 public String replace(String inClassName) {
487 ClassEntry outClassEntry = map.get(new ClassEntry(inClassName));
488 if (outClassEntry == null) {
489 return null;
490 }
491 return outClassEntry.getName();
492 }
493 });
494 }
495
496 private static Signature translate(Signature signature, final BiMap<ClassEntry, ClassEntry> map) {
497 if (signature == null) {
498 return null;
499 }
500 return new Signature(signature, new ClassNameReplacer() {
501 @Override
502 public String replace(String inClassName) {
503 ClassEntry outClassEntry = map.get(new ClassEntry(inClassName));
504 if (outClassEntry == null) {
505 return null;
506 }
507 return outClassEntry.getName();
508 }
509 });
510 }
511
512 public static <T extends Entry> void applyMemberMatches(Mappings mappings, ClassMatches classMatches, MemberMatches<T> memberMatches, Doer<T> doer) {
513 for (ClassMapping classMapping : mappings.classes()) {
514 applyMemberMatches(classMapping, classMatches, memberMatches, doer);
515 }
516 }
517
518 private static <T extends Entry> void applyMemberMatches(ClassMapping classMapping, ClassMatches classMatches, MemberMatches<T> memberMatches, Doer<T> doer) {
519
520 // get the classes
521 ClassEntry obfDestClass = classMapping.getObfEntry();
522
523 // make a map of all the renames we need to make
524 Map<T, T> renames = Maps.newHashMap();
525 for (MemberMapping<T> memberMapping : Lists.newArrayList(doer.getMappings(classMapping))) {
526 T obfOldDestEntry = memberMapping.getObfEntry(obfDestClass);
527 T obfSourceEntry = getSourceEntryFromDestMapping(memberMapping, obfDestClass, classMatches);
528
529 // but drop the unmatchable things
530 if (memberMatches.isUnmatchableSourceEntry(obfSourceEntry)) {
531 doer.removeMemberByObf(classMapping, obfOldDestEntry);
532 continue;
533 }
534
535 T obfNewDestEntry = memberMatches.matches().get(obfSourceEntry);
536 if (obfNewDestEntry != null && !obfOldDestEntry.getName().equals(obfNewDestEntry.getName())) {
537 renames.put(obfOldDestEntry, obfNewDestEntry);
538 }
539 }
540
541 if (!renames.isEmpty()) {
542
543 // apply to this class (should never need more than n passes)
544 int numRenamesAppliedThisRound;
545 do {
546 numRenamesAppliedThisRound = 0;
547
548 for (MemberMapping<T> memberMapping : Lists.newArrayList(doer.getMappings(classMapping))) {
549 T obfOldDestEntry = memberMapping.getObfEntry(obfDestClass);
550 T obfNewDestEntry = renames.get(obfOldDestEntry);
551 if (obfNewDestEntry != null) {
552 // make sure this rename won't cause a collision
553 // otherwise, save it for the next round and try again next time
554 if (!doer.hasObfMember(classMapping, obfNewDestEntry)) {
555 doer.setUpdateObfMember(classMapping, memberMapping, obfNewDestEntry);
556 renames.remove(obfOldDestEntry);
557 numRenamesAppliedThisRound++;
558 }
559 }
560 }
561 } while (numRenamesAppliedThisRound > 0);
562
563 if (!renames.isEmpty()) {
564 System.err.println(String.format("WARNING: Couldn't apply all the renames for class %s. %d renames left.",
565 classMapping.getObfFullName(), renames.size()
566 ));
567 for (Map.Entry<T, T> entry : renames.entrySet()) {
568 System.err.println(String.format("\t%s -> %s", entry.getKey().getName(), entry.getValue().getName()));
569 }
570 }
571 }
572
573 // recurse
574 for (ClassMapping innerClassMapping : classMapping.innerClasses()) {
575 applyMemberMatches(innerClassMapping, classMatches, memberMatches, doer);
576 }
577 }
578
579 private static <T extends Entry> T getSourceEntryFromDestMapping(MemberMapping<T> destMemberMapping, ClassEntry obfDestClass, ClassMatches classMatches) {
580 return translate(destMemberMapping.getObfEntry(obfDestClass), classMatches.getUniqueMatches().inverse());
581 }
582}
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}