summaryrefslogtreecommitdiff
path: root/src/main/java/cuchaz/enigma/bytecode/ClassRenamer.java
blob: 944e486bc6cb8111aaf530e53ed3efb68c80a8c4 (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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*******************************************************************************
 * Copyright (c) 2015 Jeff Martin.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public
 * License v3.0 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Contributors:
 * Jeff Martin - initial API and implementation
 ******************************************************************************/
package cuchaz.enigma.bytecode;

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

import cuchaz.enigma.mapping.ClassEntry;
import cuchaz.enigma.mapping.ClassNameReplacer;
import cuchaz.enigma.mapping.Translator;
import javassist.CtClass;
import javassist.bytecode.*;
import javassist.bytecode.SignatureAttribute.*;

public class ClassRenamer {

    private enum SignatureType {
        Class {
            @Override
            public String rename(String signature, ReplacerClassMap map) {
                return renameClassSignature(signature, map);
            }
        },
        Field {
            @Override
            public String rename(String signature, ReplacerClassMap map) {
                return renameFieldSignature(signature, map);
            }
        },
        Method {
            @Override
            public String rename(String signature, ReplacerClassMap map) {
                return renameMethodSignature(signature, map);
            }
        };

        public abstract String rename(String signature, ReplacerClassMap map);
    }

    private static class ReplacerClassMap extends HashMap<String, String> {

        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);
            }
            return null;
        }

        public String get(String className) {
            return m_replacer.replace(className);
        }
    }

    public static void renameClasses(CtClass c, final Translator translator) {
        renameClasses(c, 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, className -> {
            ClassEntry entry = new ClassEntry(className);
            if (entry.isInDefaultPackage()) {
                return newPackageName + "/" + entry.getName();
            }
            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 = renameClassName(c.getName(), map);
        if (newName != null) {
            c.setName(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;
                    String newSignature = type.rename(signatureAttribute.getSignature(), map);
                    if (newSignature != null) {
                        signatureAttribute.setSignature(newSignature);
                    }
                } 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 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 signature = cp.getUtf8Info(index);
                String newSignature = renameLocalVariableSignature(signature, map);
                if (newSignature != null) {
                    ByteArray.write16bit(cp.addUtf8Info(newSignature), info, pos + 6);
                }
            }
        }
    }

    private static String renameLocalVariableSignature(String signature, ReplacerClassMap map) {

        // for some reason, signatures with . in them don't count as field signatures
        // looks like anonymous classes delimit with . in stead of $
        // convert the . to $, but keep track of how many we replace
        // we need to put them back after we translate
        int start = signature.lastIndexOf('$') + 1;
        int numConverted = 0;
        StringBuilder buf = new StringBuilder(signature);
        for (int i = buf.length() - 1; i >= start; i--) {
            char c = buf.charAt(i);
            if (c == '.') {
                buf.setCharAt(i, '$');
                numConverted++;
            }
        }
        signature = buf.toString();

        // translate
        String newSignature = renameFieldSignature(signature, map);
        if (newSignature != null) {

            // put the delimiters back
            buf = new StringBuilder(newSignature);
            for (int i = buf.length() - 1; i >= 0 && numConverted > 0; i--) {
                char c = buf.charAt(i);
                if (c == '$') {
                    buf.setCharAt(i, '.');
                    numConverted--;
                }
            }
            assert (numConverted == 0);
            newSignature = buf.toString();

            return newSignature;
        }

        return null;
    }

    private static String renameClassSignature(String signature, ReplacerClassMap map) {
        try {
            ClassSignature type = renameType(SignatureAttribute.toClassSignature(signature), map);
            if (type != null) {
                return type.encode();
            }
            return null;
        } catch (BadBytecode ex) {
            throw new Error("Can't parse field signature: " + signature);
        }
    }

    private static String renameFieldSignature(String signature, ReplacerClassMap map) {
        try {
            ObjectType type = renameType(SignatureAttribute.toFieldSignature(signature), map);
            if (type != null) {
                return type.encode();
            }
            return null;
        } catch (BadBytecode ex) {
            throw new Error("Can't parse class signature: " + signature);
        }
    }

    private static String renameMethodSignature(String signature, ReplacerClassMap map) {
        try {
            MethodSignature type = renameType(SignatureAttribute.toMethodSignature(signature), map);
            if (type != null) {
                return type.encode();
            }
            return null;
        } catch (BadBytecode ex) {
            throw new Error("Can't parse method signature: " + signature);
        }
    }

    private static ClassSignature renameType(ClassSignature type, ReplacerClassMap map) {

        TypeParameter[] typeParamTypes = type.getParameters();
        if (typeParamTypes != null) {
            typeParamTypes = Arrays.copyOf(typeParamTypes, typeParamTypes.length);
            for (int i = 0; i < typeParamTypes.length; i++) {
                TypeParameter newParamType = renameType(typeParamTypes[i], map);
                if (newParamType != null) {
                    typeParamTypes[i] = newParamType;
                }
            }
        }

        ClassType superclassType = type.getSuperClass();
        if (superclassType != ClassType.OBJECT) {
            ClassType newSuperclassType = renameType(superclassType, map);
            if (newSuperclassType != null) {
                superclassType = newSuperclassType;
            }
        }

        ClassType[] interfaceTypes = type.getInterfaces();
        if (interfaceTypes != null) {
            interfaceTypes = Arrays.copyOf(interfaceTypes, interfaceTypes.length);
            for (int i = 0; i < interfaceTypes.length; i++) {
                ClassType newInterfaceType = renameType(interfaceTypes[i], map);
                if (newInterfaceType != null) {
                    interfaceTypes[i] = newInterfaceType;
                }
            }
        }

        return new ClassSignature(typeParamTypes, superclassType, interfaceTypes);
    }

    private static MethodSignature renameType(MethodSignature type, ReplacerClassMap map) {

        TypeParameter[] typeParamTypes = type.getTypeParameters();
        if (typeParamTypes != null) {
            typeParamTypes = Arrays.copyOf(typeParamTypes, typeParamTypes.length);
            for (int i = 0; i < typeParamTypes.length; i++) {
                TypeParameter newParamType = renameType(typeParamTypes[i], map);
                if (newParamType != null) {
                    typeParamTypes[i] = newParamType;
                }
            }
        }

        Type[] paramTypes = type.getParameterTypes();
        if (paramTypes != null) {
            paramTypes = Arrays.copyOf(paramTypes, paramTypes.length);
            for (int i = 0; i < paramTypes.length; i++) {
                Type newParamType = renameType(paramTypes[i], map);
                if (newParamType != null) {
                    paramTypes[i] = newParamType;
                }
            }
        }

        Type returnType = type.getReturnType();
        if (returnType != null) {
            Type newReturnType = renameType(returnType, map);
            if (newReturnType != null) {
                returnType = newReturnType;
            }
        }

        ObjectType[] exceptionTypes = type.getExceptionTypes();
        if (exceptionTypes != null) {
            exceptionTypes = Arrays.copyOf(exceptionTypes, exceptionTypes.length);
            for (int i = 0; i < exceptionTypes.length; i++) {
                ObjectType newExceptionType = renameType(exceptionTypes[i], map);
                if (newExceptionType != null) {
                    exceptionTypes[i] = newExceptionType;
                }
            }
        }

        return new MethodSignature(typeParamTypes, paramTypes, returnType, exceptionTypes);
    }

    private static Type renameType(Type type, ReplacerClassMap map) {
        if (type instanceof ObjectType) {
            return renameType((ObjectType) type, map);
        } else if (type instanceof BaseType) {
            return renameType((BaseType) type, map);
        } else {
            throw new Error("Don't know how to rename type " + type.getClass());
        }
    }

    private static ObjectType renameType(ObjectType type, ReplacerClassMap map) {
        if (type instanceof ArrayType) {
            return renameType((ArrayType) type, map);
        } else if (type instanceof ClassType) {
            return renameType((ClassType) type, map);
        } else if (type instanceof TypeVariable) {
            return renameType((TypeVariable) type, map);
        } else {
            throw new Error("Don't know how to rename type " + type.getClass());
        }
    }

    private static BaseType renameType(BaseType type, ReplacerClassMap map) {
        // don't have to rename primitives
        return null;
    }

    private static TypeVariable renameType(TypeVariable type, ReplacerClassMap map) {
        // don't have to rename template args
        return null;
    }

    private static ClassType renameType(ClassType type, ReplacerClassMap map) {

        // translate type args
        TypeArgument[] args = type.getTypeArguments();
        if (args != null) {
            args = Arrays.copyOf(args, args.length);
            for (int i = 0; i < args.length; i++) {
                TypeArgument newType = renameType(args[i], map);
                if (newType != null) {
                    args[i] = newType;
                }
            }
        }

        if (type instanceof NestedClassType) {
            NestedClassType nestedType = (NestedClassType) type;

            // translate the name
            String name = getClassName(type);
            String newName = map.get(name);
            if (newName != null) {
                name = new ClassEntry(newName).getInnermostClassName();
            }

            // translate the parent class too
            ClassType parent = renameType(nestedType.getDeclaringClass(), map);
            if (parent == null) {
                parent = nestedType.getDeclaringClass();
            }

            return new NestedClassType(parent, name, args);
        } else {

            // translate the name
            String name = type.getName();
            String newName = renameClassName(name, map);
            if (newName != null) {
                name = newName;
            }

            return new ClassType(name, args);
        }
    }

    private static String getClassName(ClassType type) {
        if (type instanceof NestedClassType) {
            NestedClassType nestedType = (NestedClassType) type;
            return getClassName(nestedType.getDeclaringClass()) + "$" + Descriptor.toJvmName(type.getName().replace('.', '$'));
        } else {
            return Descriptor.toJvmName(type.getName());
        }
    }

    private static String renameClassName(String name, ReplacerClassMap map) {
        String newName = map.get(Descriptor.toJvmName(name));
        if (newName != null) {
            return Descriptor.toJavaName(newName);
        }
        return null;
    }

    private static TypeArgument renameType(TypeArgument type, ReplacerClassMap map) {
        ObjectType subType = type.getType();
        if (subType != null) {
            ObjectType newSubType = renameType(subType, map);
            if (newSubType != null) {
                switch (type.getKind()) {
                    case ' ':
                        return new TypeArgument(newSubType);
                    case '+':
                        return TypeArgument.subclassOf(newSubType);
                    case '-':
                        return TypeArgument.superOf(newSubType);
                    default:
                        throw new Error("Unknown type kind: " + type.getKind());
                }
            }
        }
        return null;
    }

    private static ArrayType renameType(ArrayType type, ReplacerClassMap map) {
        Type newSubType = renameType(type.getComponentType(), map);
        if (newSubType != null) {
            return new ArrayType(type.getDimension(), newSubType);
        }
        return null;
    }

    private static TypeParameter renameType(TypeParameter type, ReplacerClassMap map) {

        ObjectType superclassType = type.getClassBound();
        if (superclassType != null) {
            ObjectType newSuperclassType = renameType(superclassType, map);
            if (newSuperclassType != null) {
                superclassType = newSuperclassType;
            }
        }

        ObjectType[] interfaceTypes = type.getInterfaceBound();
        if (interfaceTypes != null) {
            interfaceTypes = Arrays.copyOf(interfaceTypes, interfaceTypes.length);
            for (int i = 0; i < interfaceTypes.length; i++) {
                ObjectType newInterfaceType = renameType(interfaceTypes[i], map);
                if (newInterfaceType != null) {
                    interfaceTypes[i] = newInterfaceType;
                }
            }
        }

        return new TypeParameter(type.getName(), superclassType, interfaceTypes);
    }
}