View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.bcel.util;
20  
21  import java.io.IOException;
22  import java.io.OutputStream;
23  import java.io.OutputStreamWriter;
24  import java.io.PrintWriter;
25  import java.nio.charset.StandardCharsets;
26  
27  import org.apache.bcel.Const;
28  import org.apache.bcel.Repository;
29  import org.apache.bcel.classfile.ClassParser;
30  import org.apache.bcel.classfile.Code;
31  import org.apache.bcel.classfile.ConstantValue;
32  import org.apache.bcel.classfile.ExceptionTable;
33  import org.apache.bcel.classfile.Field;
34  import org.apache.bcel.classfile.JavaClass;
35  import org.apache.bcel.classfile.Method;
36  import org.apache.bcel.classfile.StackMap;
37  import org.apache.bcel.classfile.StackMapEntry;
38  import org.apache.bcel.classfile.StackMapType;
39  import org.apache.bcel.classfile.Utility;
40  import org.apache.bcel.generic.ArrayType;
41  import org.apache.bcel.generic.ConstantPoolGen;
42  import org.apache.bcel.generic.MethodGen;
43  import org.apache.bcel.generic.Type;
44  import org.apache.commons.lang3.ArrayUtils;
45  import org.apache.commons.lang3.StringUtils;
46  
47  /**
48   * This class takes a given JavaClass object and converts it to a Java program that creates that very class using BCEL.
49   * This gives new users of BCEL a useful example showing how things are done with BCEL. It does not cover all features
50   * of BCEL, but tries to mimic hand-written code as close as possible.
51   */
52  public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor {
53  
54      /**
55       * Enum corresponding to flag source.
56       */
57      public enum FLAGS {
58  
59          /** Unknown flag source. */
60          UNKNOWN,
61  
62          /** Class flag source. */
63          CLASS,
64  
65          /** Method flag source. */
66          METHOD,
67      }
68  
69      // The base package name for imports; assumes Const is at the top level
70      // N.B we use the class so renames will be detected by the compiler/IDE
71      private static final String BASE_PACKAGE = Const.class.getPackage().getName();
72      private static final String CONSTANT_PREFIX = Const.class.getSimpleName() + ".";
73  
74      /**
75       * Checks that a name from the parsed class file is a dotted sequence of valid Java identifiers before it is
76       * emitted in identifier position of the generated source. The class file format allows characters in names (for
77       * example braces, parentheses or newlines) that the Java language does not, so an unchecked name from a crafted
78       * class file could inject arbitrary code into the generated program.
79       *
80       * @param name the class or package name to check.
81       * @return {@code name} if it is safe to emit as a Java identifier.
82       * @throws IllegalArgumentException Thrown if the name is not a dotted sequence of valid Java identifiers.
83       */
84      private static String checkJavaName(final String name) {
85          boolean expectStart = true;
86          for (int i = 0; i < name.length(); i++) {
87              final char ch = name.charAt(i);
88              if (expectStart) {
89                  if (!Character.isJavaIdentifierStart(ch)) {
90                      throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name));
91                  }
92                  expectStart = false;
93              } else if (ch == '.') {
94                  expectStart = true;
95              } else if (!Character.isJavaIdentifierPart(ch)) {
96                  throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name));
97              }
98          }
99          if (expectStart) {
100             throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name));
101         }
102         return name;
103     }
104 
105     private static String[] escape(final String[] names) {
106         if (names == null) {
107             return null;
108         }
109         final String[] escaped = new String[names.length];
110         for (int i = 0; i < names.length; i++) {
111             escaped[i] = names[i] == null ? null : Utility.convertString(names[i]);
112         }
113         return escaped;
114     }
115 
116     // Needs to be accessible from unit test code
117     static JavaClass getJavaClass(final String name) throws ClassNotFoundException, IOException {
118         JavaClass javaClass;
119         if ((javaClass = Repository.lookupClass(name)) == null) {
120             javaClass = new ClassParser(name).parse(); // May throw IOException
121         }
122         return javaClass;
123     }
124 
125     /**
126      * Default main method.
127      *
128      * @param argv command line arguments.
129      * @throws Exception Thrown if an error occurs.
130      */
131     public static void main(final String[] argv) throws Exception {
132         if (argv.length != 1) {
133             System.out.println("Usage: BCELifier className");
134             System.out.println("\tThe class must exist on the classpath");
135             return;
136         }
137         final BCELifier bcelifier = new BCELifier(getJavaClass(argv[0]), System.out);
138         bcelifier.start();
139     }
140 
141     static String printArgumentTypes(final Type[] argTypes) {
142         if (argTypes.length == 0) {
143             return "Type.NO_ARGS";
144         }
145         final StringBuilder args = new StringBuilder();
146         for (int i = 0; i < argTypes.length; i++) {
147             args.append(printType(argTypes[i]));
148             if (i < argTypes.length - 1) {
149                 args.append(", ");
150             }
151         }
152         return "new Type[] { " + args.toString() + " }";
153     }
154 
155     static String printFlags(final int flags) {
156         return printFlags(flags, FLAGS.UNKNOWN);
157     }
158 
159     /**
160      * Return a string with the flag settings
161      *
162      * @param flags The flags field to interpret.
163      * @param location The item type.
164      * @return The formatted string.
165      * @since 6.0 made public
166      */
167     public static String printFlags(final int flags, final FLAGS location) {
168         if (flags == 0) {
169             return "0";
170         }
171         final StringBuilder buf = new StringBuilder();
172         for (int i = 0, pow = 1; pow <= Const.MAX_ACC_FLAG_I; i++) {
173             if ((flags & pow) != 0) {
174                 if (pow == Const.ACC_SYNCHRONIZED && location == FLAGS.CLASS) {
175                     buf.append(CONSTANT_PREFIX).append("ACC_SUPER | ");
176                 } else if (pow == Const.ACC_VOLATILE && location == FLAGS.METHOD) {
177                     buf.append(CONSTANT_PREFIX).append("ACC_BRIDGE | ");
178                 } else if (pow == Const.ACC_TRANSIENT && location == FLAGS.METHOD) {
179                     buf.append(CONSTANT_PREFIX).append("ACC_VARARGS | ");
180                 } else if (i < Const.ACCESS_NAMES_LENGTH) {
181                     buf.append(CONSTANT_PREFIX).append("ACC_").append(StringUtils.toRootUpperCase(Const.getAccessName(i))).append(" | ");
182                 } else {
183                     buf.append(String.format(CONSTANT_PREFIX + "ACC_BIT %x | ", pow));
184                 }
185             }
186             pow <<= 1;
187         }
188         final String str = buf.toString();
189         return str.substring(0, str.length() - 3);
190     }
191 
192     static String printType(final String signature) {
193         final Type type = Type.getType(signature);
194         final byte t = type.getType();
195         if (t <= Const.T_VOID) {
196             return "Type." + StringUtils.toRootUpperCase(Const.getTypeName(t));
197         }
198         if (type.toString().equals("java.lang.String")) {
199             return "Type.STRING";
200         }
201         if (type.toString().equals("java.lang.Object")) {
202             return "Type.OBJECT";
203         }
204         if (type.toString().equals("java.lang.StringBuffer")) {
205             return "Type.STRINGBUFFER";
206         }
207         if (type instanceof ArrayType) {
208             final ArrayType at = (ArrayType) type;
209             return "new ArrayType(" + printType(at.getBasicType()) + ", " + at.getDimensions() + ")";
210         }
211         return "new ObjectType(\"" + Utility.signatureToString(signature, false) + "\")";
212     }
213 
214     static String printType(final Type type) {
215         return printType(type.getSignature());
216     }
217 
218     private final JavaClass clazz;
219 
220     private final PrintWriter printWriter;
221 
222     private final ConstantPoolGen constantPoolGen;
223 
224     /**
225      * Constructs a new instance.
226      *
227      * @param clazz Java class to "decompile".
228      * @param out where to print the Java program in UTF-8.
229      */
230     public BCELifier(final JavaClass clazz, final OutputStream out) {
231         this.clazz = clazz;
232         this.printWriter = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8), false);
233         this.constantPoolGen = new ConstantPoolGen(this.clazz.getConstantPool());
234     }
235 
236     private void printCreate() {
237         printWriter.println("  public void create(OutputStream out) throws IOException {");
238         final Field[] fields = clazz.getFields();
239         if (fields.length > 0) {
240             printWriter.println("    createFields();");
241         }
242         final Method[] methods = clazz.getMethods();
243         for (int i = 0; i < methods.length; i++) {
244             printWriter.println("    createMethod_" + i + "();");
245         }
246         printWriter.println("    _cg.getJavaClass().dump(out);");
247         printWriter.println("  }");
248         printWriter.println();
249     }
250 
251     private void printMain() {
252         final String className = checkJavaName(clazz.getClassName());
253         printWriter.println("  public static void main(String[] args) throws Exception {");
254         printWriter.println("    " + className + "Creator creator = new " + className + "Creator();");
255         printWriter.println("    creator.create(new FileOutputStream(\"" + Utility.convertString(className) + ".class\"));");
256         printWriter.println("  }");
257     }
258 
259     /**
260      * Start Java code generation
261      */
262     public void start() {
263         visitJavaClass(clazz);
264         printWriter.flush();
265     }
266 
267     @Override
268     public void visitField(final Field field) {
269         printWriter.println();
270         printWriter.println("    field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", " + printType(field.getSignature()) + ", \""
271             + Utility.convertString(field.getName()) + "\", _cp);");
272         final ConstantValue cv = field.getConstantValue();
273         if (cv != null) {
274             printWriter.print("    field.setInitValue(");
275             if (field.getType() == Type.CHAR) {
276                 printWriter.print("(char)");
277             }
278             if (field.getType() == Type.SHORT) {
279                 printWriter.print("(short)");
280             }
281             if (field.getType() == Type.BYTE) {
282                 printWriter.print("(byte)");
283             }
284             if (field.getType() == Type.BOOLEAN) {
285                 // A boolean ConstantValue is stored as a CONSTANT_Integer, but FieldGen.setInitValue(int) rejects boolean fields.
286                 // Match HotSpot initialization for noncanonical integer encodings by using the low bit.
287                 printWriter.print((field.getConstantPool().getConstantInteger(cv.getConstantValueIndex()).getBytes() & 1) != 0);
288             } else {
289                 printWriter.print(cv);
290             }
291             if (field.getType() == Type.LONG) {
292                 printWriter.print("L");
293             }
294             if (field.getType() == Type.FLOAT) {
295                 printWriter.print("F");
296             }
297             if (field.getType() == Type.DOUBLE) {
298                 printWriter.print("D");
299             }
300             printWriter.println(");");
301         }
302         printWriter.println("    _cg.addField(field.getField());");
303     }
304 
305     @Override
306     public void visitJavaClass(final JavaClass clazz) {
307         String className = checkJavaName(clazz.getClassName());
308         final String superName = clazz.getSuperclassName();
309         final String packageName = clazz.getPackageName();
310         final String inter = Utility.printArray(escape(clazz.getInterfaceNames()), false, true);
311         if (StringUtils.isNotEmpty(packageName)) {
312             className = className.substring(packageName.length() + 1);
313             printWriter.println("package " + packageName + ";");
314             printWriter.println();
315         }
316         printWriter.println("import " + BASE_PACKAGE + ".generic.*;");
317         printWriter.println("import " + BASE_PACKAGE + ".classfile.*;");
318         printWriter.println("import " + BASE_PACKAGE + ".*;");
319         printWriter.println("import java.io.*;");
320         printWriter.println();
321         printWriter.println("public class " + className + "Creator {");
322         printWriter.println("  private InstructionFactory _factory;");
323         printWriter.println("  private ConstantPoolGen    _cp;");
324         printWriter.println("  private ClassGen           _cg;");
325         printWriter.println();
326         printWriter.println("  public " + className + "Creator() {");
327         printWriter.println("    _cg = new ClassGen(\"" + Utility.convertString(packageName.isEmpty() ? className : packageName + "." + className) + "\", \""
328             + Utility.convertString(superName) + "\", \"" + Utility.convertString(clazz.getSourceFileName()) + "\", "
329             + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new String[] { " + inter + " });");
330         printWriter.println("    _cg.setMajor(" + clazz.getMajor() + ");");
331         printWriter.println("    _cg.setMinor(" + clazz.getMinor() + ");");
332         printWriter.println();
333         printWriter.println("    _cp = _cg.getConstantPool();");
334         printWriter.println("    _factory = new InstructionFactory(_cg, _cp);");
335         printWriter.println("  }");
336         printWriter.println();
337         printCreate();
338         final Field[] fields = clazz.getFields();
339         if (fields.length > 0) {
340             printWriter.println("  private void createFields() {");
341             printWriter.println("    FieldGen field;");
342             for (final Field field : fields) {
343                 field.accept(this);
344             }
345             printWriter.println("  }");
346             printWriter.println();
347         }
348         final Method[] methods = clazz.getMethods();
349         for (int i = 0; i < methods.length; i++) {
350             printWriter.println("  private void createMethod_" + i + "() {");
351             methods[i].accept(this);
352             printWriter.println("  }");
353             printWriter.println();
354         }
355         printMain();
356         printWriter.println("}");
357     }
358 
359     @Override
360     public void visitMethod(final Method method) {
361         final MethodGen mg = new MethodGen(method, clazz.getClassName(), constantPoolGen);
362         printWriter.println("    InstructionList il = new InstructionList();");
363         printWriter.println("    MethodGen method = new MethodGen(" + printFlags(method.getAccessFlags(), FLAGS.METHOD) + ", " + printType(mg.getReturnType())
364             + ", " + printArgumentTypes(mg.getArgumentTypes()) + ", new String[] { " + Utility.printArray(escape(mg.getArgumentNames()), false, true) + " }, \""
365             + Utility.convertString(method.getName()) + "\", \"" + Utility.convertString(clazz.getClassName()) + "\", il, _cp);");
366         final ExceptionTable exceptionTable = method.getExceptionTable();
367         if (exceptionTable != null) {
368             final String[] exceptionNames = exceptionTable.getExceptionNames();
369             for (final String exceptionName : exceptionNames) {
370                 printWriter.print("    method.addException(\"");
371                 printWriter.print(Utility.convertString(exceptionName));
372                 printWriter.println("\");");
373             }
374         }
375         final Code code = method.getCode();
376         if (code != null) {
377             // Preserve this method's compact header setting only for versions that support it; JavaClass.dump selects the class-wide layout.
378             if (code.isCompactCodeHeader() && clazz.getMajor() == Const.MAJOR_1_1 && clazz.getMinor() < Const.MINOR_1_1) {
379                 printWriter.println("    method.setCompactCodeHeader(true);");
380             }
381             final StackMap stackMap = code.getStackMap();
382             if (stackMap != null) {
383                 stackMap.accept(this);
384             }
385         }
386         printWriter.println();
387         final BCELFactory factory = new BCELFactory(mg, printWriter);
388         factory.start();
389         printWriter.println("    method.setMaxStack();");
390         printWriter.println("    method.setMaxLocals();");
391         printWriter.println("    _cg.addMethod(method.getMethod());");
392         printWriter.println("    il.dispose();");
393     }
394 
395     @Override
396     public void visitStackMap(final StackMap stackMap) {
397         super.visitStackMap(stackMap);
398         printWriter.print("    method.addCodeAttribute(");
399         printWriter.print("new StackMap(_cp.addUtf8(\"");
400         printWriter.print(Utility.convertString(stackMap.getName()));
401         printWriter.print("\"), ");
402         printWriter.print(stackMap.getLength());
403         printWriter.print(", ");
404         printWriter.print("new StackMapEntry[] {");
405         final StackMapEntry[] table = stackMap.getStackMap();
406         for (int i = 0; i < table.length; i++) {
407             table[i].accept(this);
408             if (i < table.length - 1) {
409                 printWriter.print(", ");
410             } else {
411                 printWriter.print(" }");
412             }
413         }
414         printWriter.print(", _cp.getConstantPool())");
415         printWriter.println(");");
416     }
417 
418     @Override
419     public void visitStackMapEntry(final StackMapEntry stackMapEntry) {
420         super.visitStackMapEntry(stackMapEntry);
421         printWriter.print("new StackMapEntry(");
422         printWriter.print(stackMapEntry.getFrameType());
423         printWriter.print(", ");
424         printWriter.print(stackMapEntry.getByteCodeOffset());
425         printWriter.print(", ");
426         visitStackMapTypeArray(stackMapEntry.getTypesOfLocals());
427         printWriter.print(", ");
428         visitStackMapTypeArray(stackMapEntry.getTypesOfStackItems());
429         printWriter.print(", _cp.getConstantPool())");
430     }
431 
432     /**
433      * Visits a {@link StackMapType} object.
434      *
435      * @param stackMapType object to visit.
436      * @since 6.7.1
437      */
438     @Override
439     public void visitStackMapType(final StackMapType stackMapType) {
440         super.visitStackMapType(stackMapType);
441         printWriter.print("new StackMapType((byte)");
442         printWriter.print(stackMapType.getType());
443         printWriter.print(", ");
444         if (stackMapType.hasIndex()) {
445             printWriter.print("_cp.addClass(\"");
446             printWriter.print(Utility.convertString(stackMapType.getClassName()));
447             printWriter.print("\")");
448         } else {
449             printWriter.print("-1");
450         }
451         printWriter.print(", _cp.getConstantPool())");
452     }
453 
454     private void visitStackMapTypeArray(final StackMapType[] types) {
455         if (ArrayUtils.isEmpty(types)) {
456             printWriter.print("null"); // null translates to StackMapType.EMPTY_ARRAY
457         } else {
458             printWriter.print("new StackMapType[] {");
459             for (int i = 0; i < types.length; i++) {
460                 types[i].accept(this);
461                 if (i < types.length - 1) {
462                     printWriter.print(", ");
463                 } else {
464                     printWriter.print(" }");
465                 }
466             }
467         }
468     }
469 }