summaryrefslogtreecommitdiff
path: root/src/cuchaz/enigma/bytecode/ClassRenamer.java
blob: d7acd30997515a430623b054440a37608ddec2e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*******************************************************************************
 * Copyright (c) 2014 Jeff Martin.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     Jeff Martin - initial API and implementation
 ******************************************************************************/
package cuchaz.enigma.bytecode;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javassist.CtClass;
import javassist.bytecode.AttributeInfo;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.ByteArray;
import javassist.bytecode.ClassFile;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.ConstPool;
import javassist.bytecode.Descriptor;
import javassist.bytecode.FieldInfo;
import javassist.bytecode.InnerClassesAttribute;
import javassist.bytecode.LocalVariableTypeAttribute;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.SignatureAttribute;
import javassist.bytecode.SignatureAttribute.ClassSignature;
import javassist.bytecode.SignatureAttribute.MethodSignature;
import javassist.bytecode.SignatureAttribute.ObjectType;
import cuchaz.enigma.mapping.ClassEntry;
import cuchaz.enigma.mapping.ClassNameReplacer;
import cuchaz.enigma.mapping.Translator;
import cuchaz.enigma.mapping.Type;

public class ClassRenamer {
	
	private static enum SignatureType {
		Class {
			
			@Override
			public void rename(SignatureAttribute attribute, ReplacerClassMap map) {
				renameClassSignatureAttribute(attribute, map);
			}
		},
		Field {
			
			@Override
			public void rename(SignatureAttribute attribute, ReplacerClassMap map) {
				renameFieldSignatureAttribute(attribute, map);
			}
		},
		Method {
			
			@Override
			public void rename(SignatureAttribute attribute, ReplacerClassMap map) {
				renameMethodSignatureAttribute(attribute, map);
			}
		};
		
		public abstract void rename(SignatureAttribute attribute, ReplacerClassMap map);
	}
	
	private static class ReplacerClassMap extends HashMap<String,String> {
		
		private static final long serialVersionUID = 317915213205066168L;
		
		private ClassNameReplacer m_replacer;
		
		public ReplacerClassMap(ClassNameReplacer replacer) {
			m_replacer = replacer;
		}
		
		@Override
		public String get(Object obj) {
			if (obj instanceof String) {
				return get((String)obj);
			} else if (obj instanceof ObjectType) {
				return get((ObjectType)obj);
			}
			return null;
		}
		
		public String get(String typeName) {
			
			// javassist doesn't give us the class framing, add it
			typeName = "L" + typeName + ";";
			
			String out = getFramed(typeName);
			if (out == null) {
				return null;
			}

			// javassist doesn't want the class framing, so remove it
			out = out.substring(1, out.length() - 1);
			
			return out;
		}
		
		public String getFramed(String typeName) {
			Type type = new Type(typeName);
			Type renamedType = new Type(type, m_replacer);
			if (!type.equals(renamedType)) {
				return renamedType.toString();
			}
			return null;
		}
		
		public String get(ObjectType type) {
			
			// we can deal with the ones that start with a class
			String signature = type.encode();
			/*
			if (signature.startsWith("L") || signature.startsWith("[")) {
				
				// TEMP: skip special characters for now
				if (signature.indexOf('*') >= 0 || signature.indexOf('+') >= 0 || signature.indexOf('-') >= 0) {
					System.out.println("Skipping translating: " + signature);
					return null;
				}
				
				// replace inner class / with $
				int pos = signature.indexOf("$");
				if (pos >= 0) {
					signature = signature.substring(0, pos + 1) + signature.substring(pos, signature.length()).replace('/', '$');
				}
				
				return getFramed(signature);
			} else if (signature.startsWith("T")) {
				// don't need to care about template names
				return null;
			} else {
			*/
				// TEMP
				System.out.println("Skipping translating: " + signature);
				return null;
			//}
		}
	}
	
	public static void renameClasses(CtClass c, final Translator translator) {
		renameClasses(c, new ClassNameReplacer() {
			@Override
			public String replace(String className) {
				ClassEntry entry = translator.translateEntry(new ClassEntry(className));
				if (entry != null) {
					return entry.getName();
				}
				return null;
			}
		});
	}
	
	public static void moveAllClassesOutOfDefaultPackage(CtClass c, final String newPackageName) {
		renameClasses(c, new ClassNameReplacer() {
			@Override
			public String replace(String className) {
				ClassEntry entry = new ClassEntry(className);
				if (entry.isInDefaultPackage()) {
					return newPackageName + "/" + entry.getName();
				}
				return null;
			}
		});
	}
	
	public static void moveAllClassesIntoDefaultPackage(CtClass c, final String oldPackageName) {
		renameClasses(c, new ClassNameReplacer() {
			@Override
			public String replace(String className) {
				ClassEntry entry = new ClassEntry(className);
				if (entry.getPackageName().equals(oldPackageName)) {
					return entry.getSimpleName();
				}
				return null;
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	public static void renameClasses(CtClass c, ClassNameReplacer replacer) {
		
		// sadly, we can't use CtClass.renameClass() because SignatureAttribute.renameClass() is extremely buggy =(
		
		ReplacerClassMap map = new ReplacerClassMap(replacer);
		ClassFile classFile = c.getClassFile();
		
		// rename the constant pool (covers ClassInfo, MethodTypeInfo, and NameAndTypeInfo)
		ConstPool constPool = c.getClassFile().getConstPool();
		constPool.renameClass(map);
		
		// rename class attributes
		renameAttributes(classFile.getAttributes(), map, SignatureType.Class);
		
		// rename methods
		for (MethodInfo methodInfo : (List<MethodInfo>)classFile.getMethods()) {
			methodInfo.setDescriptor(Descriptor.rename(methodInfo.getDescriptor(), map));
			renameAttributes(methodInfo.getAttributes(), map, SignatureType.Method);
		}
		
		// rename fields
		for (FieldInfo fieldInfo : (List<FieldInfo>)classFile.getFields()) {
			fieldInfo.setDescriptor(Descriptor.rename(fieldInfo.getDescriptor(), map));
			renameAttributes(fieldInfo.getAttributes(), map, SignatureType.Field);
		}
		
		// rename the class name itself last
		// NOTE: don't use the map here, because setName() calls the buggy SignatureAttribute.renameClass()
		// we only want to replace exactly this class name
		String newName = replacer.replace(Descriptor.toJvmName(c.getName()));
		if (newName != null) {
			c.setName(Descriptor.toJavaName(newName));
		}
		
		// replace simple names in the InnerClasses attribute too
		InnerClassesAttribute attr = (InnerClassesAttribute)c.getClassFile().getAttribute(InnerClassesAttribute.tag);
		if (attr != null) {
			for (int i = 0; i < attr.tableLength(); i++) {
				
				// get the inner class full name (which has already been translated)
				ClassEntry classEntry = new ClassEntry(Descriptor.toJvmName(attr.innerClass(i)));
				
				if (attr.innerNameIndex(i) != 0) {
					// update the inner name
					attr.setInnerNameIndex(i, constPool.addUtf8Info(classEntry.getInnermostClassName()));
				}
				
				/* DEBUG
				System.out.println(String.format("\tDEOBF: %s-> ATTR: %s,%s,%s", classEntry, attr.outerClass(i), attr.innerClass(i), attr.innerName(i)));
				*/
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	private static void renameAttributes(List<AttributeInfo> attributes, ReplacerClassMap map, SignatureType type) {
		try {
			
			// make the rename class method accessible
			Method renameClassMethod = AttributeInfo.class.getDeclaredMethod("renameClass", Map.class);
			renameClassMethod.setAccessible(true);
			
			for (AttributeInfo attribute : attributes) {
				if (attribute instanceof SignatureAttribute) {
					// this has to be handled specially because SignatureAttribute.renameClass() is buggy as hell
					SignatureAttribute signatureAttribute = (SignatureAttribute)attribute;
					type.rename(signatureAttribute, map);
				} else if (attribute instanceof CodeAttribute) {
					// code attributes have signature attributes too (indirectly)
					CodeAttribute codeAttribute = (CodeAttribute)attribute;
					renameAttributes(codeAttribute.getAttributes(), map, type);
				} else if (attribute instanceof LocalVariableTypeAttribute) {
					// lvt attributes have signature attributes too
					LocalVariableTypeAttribute localVariableAttribute = (LocalVariableTypeAttribute)attribute;
					renameLocalVariableTypeAttribute(localVariableAttribute, map);
				} else {
					renameClassMethod.invoke(attribute, map);
				}
			}
			
		} catch(NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
			throw new Error("Unable to call javassist methods by reflection!", ex);
		}
	}

	private static void renameClassSignatureAttribute(SignatureAttribute attribute, ReplacerClassMap map) {
		try {
			ClassSignature classSignature = SignatureAttribute.toClassSignature(attribute.getSignature());
			// TODO: do class signatures
		} catch (BadBytecode ex) {
			throw new Error("Unable to parse class signature: " + attribute.getSignature(), ex);
		}
	}
	
	private static void renameFieldSignatureAttribute(SignatureAttribute attribute, ReplacerClassMap map) {
		try {
			ObjectType fieldSignature = SignatureAttribute.toFieldSignature(attribute.getSignature());
			String newSignature = map.get(fieldSignature);
			if (newSignature != null) {
				attribute.setSignature(newSignature);
			}
		} catch (BadBytecode ex) {
			throw new Error("Unable to parse field signature: " + attribute.getSignature(), ex);
		}
	}
	
	private static void renameMethodSignatureAttribute(SignatureAttribute attribute, ReplacerClassMap map) {
		try {
			MethodSignature methodSignature = SignatureAttribute.toMethodSignature(attribute.getSignature());
			// TODO: do method signatures
		} catch (BadBytecode ex) {
			throw new Error("Unable to parse method signature: " + attribute.getSignature(), ex);
		}
	}
	
	private static void renameLocalVariableTypeAttribute(LocalVariableTypeAttribute attribute, ReplacerClassMap map) {
		// adapted from LocalVariableAttribute.renameClass()
		ConstPool cp = attribute.getConstPool();
		int n = attribute.tableLength();
		byte[] info = attribute.get();
		for (int i = 0; i < n; ++i) {
			int pos = i * 10 + 2;
			int index = ByteArray.readU16bit(info, pos + 6);
			if (index != 0) {
				String desc = cp.getUtf8Info(index);
				try {
					ObjectType fieldSignature = SignatureAttribute.toFieldSignature(desc);
					String newDesc = map.get(fieldSignature);
					if (newDesc != null) {
						ByteArray.write16bit(cp.addUtf8Info(newDesc), info, pos + 6);
					}
				} catch (BadBytecode ex) {
					throw new Error("Unable to parse field signature: " + desc, ex);
				}
			}
		}
	}
}