summaryrefslogtreecommitdiff
path: root/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/IdentifierConverter.java
blob: 9ed3578d3d558b2f53522549f4a3b8b71e493252 (plain)
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
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.java.decompiler.modules.renamer;

import org.jetbrains.java.decompiler.code.CodeConstants;
import org.jetbrains.java.decompiler.main.DecompilerContext;
import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences;
import org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer;
import org.jetbrains.java.decompiler.struct.StructClass;
import org.jetbrains.java.decompiler.struct.StructContext;
import org.jetbrains.java.decompiler.struct.StructField;
import org.jetbrains.java.decompiler.struct.StructMethod;
import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor;
import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor;
import org.jetbrains.java.decompiler.struct.gen.VarType;
import org.jetbrains.java.decompiler.util.VBStyleCollection;

import java.io.IOException;
import java.util.*;

public class IdentifierConverter {

  private StructContext context;

  private IIdentifierRenamer helper;

  private PoolInterceptor interceptor;

  private List<ClassWrapperNode> rootClasses = new ArrayList<ClassWrapperNode>();

  private List<ClassWrapperNode> rootInterfaces = new ArrayList<ClassWrapperNode>();

  private HashMap<String, HashMap<String, String>> interfaceNameMaps = new HashMap<String, HashMap<String, String>>();

  public void rename(StructContext context) {

    try {
      this.context = context;

      String user_class = (String)DecompilerContext.getProperty(IFernflowerPreferences.USER_RENAMER_CLASS);
      if (user_class != null) {
        try {
          helper = (IIdentifierRenamer)IdentifierConverter.class.getClassLoader().loadClass(user_class).newInstance();
        }
        catch (Exception ex) {
          // ignore errors
        }
      }

      if (helper == null) {
        helper = new ConverterHelper();
      }

      interceptor = new PoolInterceptor(helper);

      buildInheritanceTree();

      renameAllClasses();

      renameInterfaces();

      renameClasses();

      DecompilerContext.setPoolInterceptor(interceptor);
      context.reloadContext();
    }
    catch (IOException ex) {
      throw new RuntimeException("Renaming failed!");
    }
  }

  private void renameClasses() {

    List<ClassWrapperNode> lstClasses = getReversePostOrderListIterative(rootClasses);

    HashMap<String, HashMap<String, String>> classNameMaps = new HashMap<String, HashMap<String, String>>();

    for (ClassWrapperNode node : lstClasses) {

      StructClass cl = node.getClassStruct();
      HashMap<String, String> names = new HashMap<String, String>();

      // merge informations on super class
      if (cl.superClass != null) {
        HashMap<String, String> mapClass = classNameMaps.get(cl.superClass.getString());
        if (mapClass != null) {
          names.putAll(mapClass);
        }
      }

      // merge informations on interfaces
      for (String intrName : cl.getInterfaceNames()) {
        HashMap<String, String> mapInt = interfaceNameMaps.get(intrName);
        if (mapInt != null) {
          names.putAll(mapInt);
        }
        else {
          StructClass clintr = context.getClass(intrName);
          if (clintr != null) {
            names.putAll(processExternalInterface(clintr));
          }
        }
      }

      renameClassIdentifiers(cl, names);

      if (!node.getSubclasses().isEmpty()) {
        classNameMaps.put(cl.qualifiedName, names);
      }
    }
  }

  private HashMap<String, String> processExternalInterface(StructClass cl) {

    HashMap<String, String> names = new HashMap<String, String>();

    for (String intrName : cl.getInterfaceNames()) {

      HashMap<String, String> mapInt = interfaceNameMaps.get(intrName);
      if (mapInt != null) {
        names.putAll(mapInt);
      }
      else {
        StructClass clintr = context.getClass(intrName);
        if (clintr != null) {
          names.putAll(processExternalInterface(clintr));
        }
      }
    }

    renameClassIdentifiers(cl, names);

    return names;
  }

  private void renameInterfaces() {

    List<ClassWrapperNode> lstInterfaces = getReversePostOrderListIterative(rootInterfaces);

    HashMap<String, HashMap<String, String>> interfaceNameMaps = new HashMap<String, HashMap<String, String>>();

    // rename methods and fields
    for (ClassWrapperNode node : lstInterfaces) {

      StructClass cl = node.getClassStruct();
      HashMap<String, String> names = new HashMap<String, String>();

      // merge informations on super interfaces
      for (String intrName : cl.getInterfaceNames()) {
        HashMap<String, String> mapInt = interfaceNameMaps.get(intrName);
        if (mapInt != null) {
          names.putAll(mapInt);
        }
      }

      renameClassIdentifiers(cl, names);

      interfaceNameMaps.put(cl.qualifiedName, names);
    }

    this.interfaceNameMaps = interfaceNameMaps;
  }

  private void renameAllClasses() {

    // order not important
    List<ClassWrapperNode> lstAllClasses = new ArrayList<ClassWrapperNode>(getReversePostOrderListIterative(rootInterfaces));
    lstAllClasses.addAll(getReversePostOrderListIterative(rootClasses));

    // rename all interfaces and classes
    for (ClassWrapperNode node : lstAllClasses) {
      renameClass(node.getClassStruct());
    }
  }

  private void renameClass(StructClass cl) {

    if (!cl.isOwn()) {
      return;
    }

    String classOldFullName = cl.qualifiedName;

    // TODO: rename packages
    String clsimplename = ConverterHelper.getSimpleClassName(classOldFullName);
    if (helper.toBeRenamed(IIdentifierRenamer.ELEMENT_CLASS, clsimplename, null, null)) {
      String classNewFullName;

      do {
        classNewFullName = ConverterHelper.replaceSimpleClassName(classOldFullName,
                                                                  helper.getNextClassname(classOldFullName, ConverterHelper
                                                                    .getSimpleClassName(classOldFullName)));
      }
      while (context.getClasses().containsKey(classNewFullName));

      interceptor.addName(classOldFullName, classNewFullName);
    }
  }

  private void renameClassIdentifiers(StructClass cl, HashMap<String, String> names) {

    // all classes are already renamed
    String classOldFullName = cl.qualifiedName;
    String classNewFullName = interceptor.getName(classOldFullName);

    if (classNewFullName == null) {
      classNewFullName = classOldFullName;
    }

    // methods
    HashSet<String> setMethodNames = new HashSet<String>();
    for (StructMethod md : cl.getMethods()) {
      setMethodNames.add(md.getName());
    }

    VBStyleCollection<StructMethod, String> methods = cl.getMethods();
    for (int i = 0; i < methods.size(); i++) {

      StructMethod mt = methods.get(i);
      String key = methods.getKey(i);

      boolean isPrivate = mt.hasModifier(CodeConstants.ACC_PRIVATE);

      String name = mt.getName();
      if (!cl.isOwn() || mt.hasModifier(CodeConstants.ACC_NATIVE)) {
        // external and native methods must not be renamed
        if (!isPrivate) {
          names.put(key, name);
        }
      }
      else if (helper.toBeRenamed(IIdentifierRenamer.ELEMENT_METHOD, classOldFullName, name, mt.getDescriptor())) {
        if (isPrivate || !names.containsKey(key)) {
          do {
            name = helper.getNextMethodname(classOldFullName, name, mt.getDescriptor());
          }
          while (setMethodNames.contains(name));

          if (!isPrivate) {
            names.put(key, name);
          }
        }
        else {
          name = names.get(key);
        }

        interceptor.addName(classOldFullName + " " + mt.getName() + " " + mt.getDescriptor(),
                            classNewFullName + " " + name + " " + buildNewDescriptor(false, mt.getDescriptor()));
      }
    }

    // external fields are not being renamed
    if (!cl.isOwn()) {
      return;
    }

    // fields
    // FIXME: should overloaded fields become the same name?
    HashSet<String> setFieldNames = new HashSet<String>();
    for (StructField fd : cl.getFields()) {
      setFieldNames.add(fd.getName());
    }

    for (StructField fd : cl.getFields()) {
      if (helper.toBeRenamed(IIdentifierRenamer.ELEMENT_FIELD, classOldFullName, fd.getName(), fd.getDescriptor())) {
        String newname;

        do {
          newname = helper.getNextFieldname(classOldFullName, fd.getName(), fd.getDescriptor());
        }
        while (setFieldNames.contains(newname));

        interceptor.addName(classOldFullName + " " + fd.getName() + " " + fd.getDescriptor(),
                            classNewFullName + " " + newname + " " + buildNewDescriptor(true, fd.getDescriptor()));
      }
    }
  }

  private String buildNewDescriptor(boolean isField, String descriptor) {

    boolean updated = false;

    if (isField) {
      FieldDescriptor fd = FieldDescriptor.parseDescriptor(descriptor);

      VarType ftype = fd.type;
      if (ftype.type == CodeConstants.TYPE_OBJECT) {
        String newclname = interceptor.getName(ftype.value);
        if (newclname != null) {
          ftype.value = newclname;
          updated = true;
        }
      }

      if (updated) {
        return fd.getDescriptor();
      }
    }
    else {

      MethodDescriptor md = MethodDescriptor.parseDescriptor(descriptor);
      // params
      for (VarType partype : md.params) {
        if (partype.type == CodeConstants.TYPE_OBJECT) {
          String newclname = interceptor.getName(partype.value);
          if (newclname != null) {
            partype.value = newclname;
            updated = true;
          }
        }
      }

      // return value
      if (md.ret.type == CodeConstants.TYPE_OBJECT) {
        String newclname = interceptor.getName(md.ret.value);
        if (newclname != null) {
          md.ret.value = newclname;
          updated = true;
        }
      }

      if (updated) {
        return md.getDescriptor();
      }
    }

    return descriptor;
  }

  private static List<ClassWrapperNode> getReversePostOrderListIterative(List<ClassWrapperNode> roots) {

    List<ClassWrapperNode> res = new ArrayList<ClassWrapperNode>();

    LinkedList<ClassWrapperNode> stackNode = new LinkedList<ClassWrapperNode>();
    LinkedList<Integer> stackIndex = new LinkedList<Integer>();

    HashSet<ClassWrapperNode> setVisited = new HashSet<ClassWrapperNode>();

    for (ClassWrapperNode root : roots) {
      stackNode.add(root);
      stackIndex.add(0);
    }

    while (!stackNode.isEmpty()) {

      ClassWrapperNode node = stackNode.getLast();
      int index = stackIndex.removeLast();

      setVisited.add(node);

      List<ClassWrapperNode> lstSubs = node.getSubclasses();

      for (; index < lstSubs.size(); index++) {
        ClassWrapperNode sub = lstSubs.get(index);
        if (!setVisited.contains(sub)) {
          stackIndex.add(index + 1);

          stackNode.add(sub);
          stackIndex.add(0);

          break;
        }
      }

      if (index == lstSubs.size()) {
        res.add(0, node);

        stackNode.removeLast();
      }
    }

    return res;
  }


  private void buildInheritanceTree() {

    Map<String, ClassWrapperNode> nodes = new HashMap<String, ClassWrapperNode>();
    Map<String, StructClass> classes = context.getClasses();

    List<ClassWrapperNode> rootClasses = new ArrayList<ClassWrapperNode>();
    List<ClassWrapperNode> rootInterfaces = new ArrayList<ClassWrapperNode>();

    for (StructClass cl : classes.values()) {

      if (!cl.isOwn()) {
        continue;
      }

      LinkedList<StructClass> stack = new LinkedList<StructClass>();
      LinkedList<ClassWrapperNode> stackSubnodes = new LinkedList<ClassWrapperNode>();

      stack.add(cl);
      stackSubnodes.add(null);

      while (!stack.isEmpty()) {

        StructClass clstr = stack.removeFirst();
        ClassWrapperNode child = stackSubnodes.removeFirst();

        ClassWrapperNode node = nodes.get(clstr.qualifiedName);
        boolean isNewNode = (node == null);

        if (isNewNode) {
          nodes.put(clstr.qualifiedName, node = new ClassWrapperNode(clstr));
        }

        if (child != null) {
          node.addSubclass(child);
        }

        if (!isNewNode) {
          break;
        }
        else {
          boolean isInterface = clstr.hasModifier(CodeConstants.ACC_INTERFACE);
          boolean found_parent = false;

          if (isInterface) {
            for (String intrName : clstr.getInterfaceNames()) {
              StructClass clparent = classes.get(intrName);
              if (clparent != null) {
                stack.add(clparent);
                stackSubnodes.add(node);
                found_parent = true;
              }
            }
          }
          else {
            if (clstr.superClass != null) { // null iff java/lang/Object
              StructClass clparent = classes.get(clstr.superClass.getString());

              if (clparent != null) {
                stack.add(clparent);
                stackSubnodes.add(node);
                found_parent = true;
              }
            }
          }

          if (!found_parent) { // no super class or interface
            (isInterface ? rootInterfaces : rootClasses).add(node);
          }
        }
      }
    }

    this.rootClasses = rootClasses;
    this.rootInterfaces = rootInterfaces;
  }
}