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  import java.util.Arrays;
27  import java.util.function.IntFunction;
28  
29  import org.apache.bcel.Const;
30  import org.apache.bcel.Repository;
31  import org.apache.bcel.classfile.Attribute;
32  import org.apache.bcel.classfile.BootstrapMethod;
33  import org.apache.bcel.classfile.BootstrapMethods;
34  import org.apache.bcel.classfile.ClassParser;
35  import org.apache.bcel.classfile.Code;
36  import org.apache.bcel.classfile.Constant;
37  import org.apache.bcel.classfile.ConstantCP;
38  import org.apache.bcel.classfile.ConstantClass;
39  import org.apache.bcel.classfile.ConstantDouble;
40  import org.apache.bcel.classfile.ConstantFloat;
41  import org.apache.bcel.classfile.ConstantInteger;
42  import org.apache.bcel.classfile.ConstantLong;
43  import org.apache.bcel.classfile.ConstantMethodHandle;
44  import org.apache.bcel.classfile.ConstantMethodType;
45  import org.apache.bcel.classfile.ConstantModule;
46  import org.apache.bcel.classfile.ConstantNameAndType;
47  import org.apache.bcel.classfile.ConstantPackage;
48  import org.apache.bcel.classfile.ConstantString;
49  import org.apache.bcel.classfile.ConstantUtf8;
50  import org.apache.bcel.classfile.ConstantValue;
51  import org.apache.bcel.classfile.ExceptionTable;
52  import org.apache.bcel.classfile.Field;
53  import org.apache.bcel.classfile.JavaClass;
54  import org.apache.bcel.classfile.Method;
55  import org.apache.bcel.classfile.StackMap;
56  import org.apache.bcel.classfile.StackMapEntry;
57  import org.apache.bcel.classfile.StackMapType;
58  import org.apache.bcel.classfile.Utility;
59  import org.apache.bcel.generic.ArrayType;
60  import org.apache.bcel.generic.ConstantPoolGen;
61  import org.apache.bcel.generic.MethodGen;
62  import org.apache.bcel.generic.Type;
63  import org.apache.commons.lang3.ArrayUtils;
64  import org.apache.commons.lang3.StringUtils;
65  
66  /**
67   * This class takes a given JavaClass object and converts it to a Java program that creates that very class using BCEL.
68   * This gives new users of BCEL a useful example showing how things are done with BCEL. It does not cover all features
69   * of BCEL, but tries to mimic hand-written code as close as possible.
70   */
71  public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor {
72  
73      /**
74       * Enum corresponding to flag source.
75       */
76      public enum FLAGS {
77  
78          /** Unknown flag source. */
79          UNKNOWN,
80  
81          /** Class flag source. */
82          CLASS,
83  
84          /** Method flag source. */
85          METHOD,
86      }
87  
88      // The base package name for imports; assumes Const is at the top level
89      // N.B we use the class so renames will be detected by the compiler/IDE
90      private static final String BASE_PACKAGE = Const.class.getPackage().getName();
91      private static final String CONSTANT_PREFIX = Const.class.getSimpleName() + ".";
92  
93      // Bound each bootstrap expression so a batch of array assignments stays below the JVM's method-size limit.
94      private static final int MAX_INLINE_BOOTSTRAP_ARGUMENTS = 32;
95  
96      /**
97       * Checks that a name from the parsed class file is a dotted sequence of valid Java identifiers before it is
98       * emitted in identifier position of the generated source. The class file format allows characters in names (for
99       * example braces, parentheses or newlines) that the Java language does not, so an unchecked name from a crafted
100      * class file could inject arbitrary code into the generated program.
101      *
102      * @param name the class or package name to check.
103      * @return {@code name} if it is safe to emit as a Java identifier.
104      * @throws IllegalArgumentException Thrown if the name is not a dotted sequence of valid Java identifiers.
105      */
106     private static String checkJavaName(final String name) {
107         boolean expectStart = true;
108         for (int i = 0; i < name.length(); i++) {
109             final char ch = name.charAt(i);
110             if (expectStart) {
111                 if (!Character.isJavaIdentifierStart(ch)) {
112                     throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name));
113                 }
114                 expectStart = false;
115             } else if (ch == '.') {
116                 expectStart = true;
117             } else if (!Character.isJavaIdentifierPart(ch)) {
118                 throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name));
119             }
120         }
121         if (expectStart) {
122             throw new IllegalArgumentException("Invalid Java identifier in class file: " + Utility.convertString(name));
123         }
124         return name;
125     }
126 
127     private static String[] escape(final String[] names) {
128         if (names == null) {
129             return null;
130         }
131         final String[] escaped = new String[names.length];
132         for (int i = 0; i < names.length; i++) {
133             escaped[i] = names[i] == null ? null : Utility.convertString(names[i]);
134         }
135         return escaped;
136     }
137 
138     // Needs to be accessible from unit test code
139     static JavaClass getJavaClass(final String name) throws ClassNotFoundException, IOException {
140         JavaClass javaClass;
141         if ((javaClass = Repository.lookupClass(name)) == null) {
142             javaClass = new ClassParser(name).parse(); // May throw IOException
143         }
144         return javaClass;
145     }
146 
147     /**
148      * Default main method.
149      *
150      * @param argv command line arguments.
151      * @throws Exception Thrown if an error occurs.
152      */
153     public static void main(final String[] argv) throws Exception {
154         if (argv.length != 1) {
155             System.out.println("Usage: BCELifier className");
156             System.out.println("\tThe class must exist on the classpath");
157             return;
158         }
159         final BCELifier bcelifier = new BCELifier(getJavaClass(argv[0]), System.out);
160         bcelifier.start();
161     }
162 
163     static String printArgumentTypes(final Type[] argTypes) {
164         if (argTypes.length == 0) {
165             return "Type.NO_ARGS";
166         }
167         final StringBuilder args = new StringBuilder();
168         for (int i = 0; i < argTypes.length; i++) {
169             args.append(printType(argTypes[i]));
170             if (i < argTypes.length - 1) {
171                 args.append(", ");
172             }
173         }
174         return "new Type[] { " + args.toString() + " }";
175     }
176 
177     static String printFlags(final int flags) {
178         return printFlags(flags, FLAGS.UNKNOWN);
179     }
180 
181     /**
182      * Return a string with the flag settings
183      *
184      * @param flags The flags field to interpret.
185      * @param location The item type.
186      * @return The formatted string.
187      * @since 6.0 made public
188      */
189     public static String printFlags(final int flags, final FLAGS location) {
190         if (flags == 0) {
191             return "0";
192         }
193         final StringBuilder buf = new StringBuilder();
194         for (int i = 0, pow = 1; pow <= Const.MAX_ACC_FLAG_I; i++) {
195             if ((flags & pow) != 0) {
196                 if (pow == Const.ACC_SYNCHRONIZED && location == FLAGS.CLASS) {
197                     buf.append(CONSTANT_PREFIX).append("ACC_SUPER | ");
198                 } else if (pow == Const.ACC_VOLATILE && location == FLAGS.METHOD) {
199                     buf.append(CONSTANT_PREFIX).append("ACC_BRIDGE | ");
200                 } else if (pow == Const.ACC_TRANSIENT && location == FLAGS.METHOD) {
201                     buf.append(CONSTANT_PREFIX).append("ACC_VARARGS | ");
202                 } else if (i < Const.ACCESS_NAMES_LENGTH) {
203                     buf.append(CONSTANT_PREFIX).append("ACC_").append(StringUtils.toRootUpperCase(Const.getAccessName(i))).append(" | ");
204                 } else {
205                     buf.append(String.format(CONSTANT_PREFIX + "ACC_BIT %x | ", pow));
206                 }
207             }
208             pow <<= 1;
209         }
210         final String str = buf.toString();
211         return str.substring(0, str.length() - 3);
212     }
213 
214     static String printType(final String signature) {
215         final Type type = Type.getType(signature);
216         final byte t = type.getType();
217         if (t <= Const.T_VOID) {
218             return "Type." + StringUtils.toRootUpperCase(Const.getTypeName(t));
219         }
220         if (type.toString().equals("java.lang.String")) {
221             return "Type.STRING";
222         }
223         if (type.toString().equals("java.lang.Object")) {
224             return "Type.OBJECT";
225         }
226         if (type.toString().equals("java.lang.StringBuffer")) {
227             return "Type.STRINGBUFFER";
228         }
229         if (type instanceof ArrayType) {
230             final ArrayType at = (ArrayType) type;
231             return "new ArrayType(" + printType(at.getBasicType()) + ", " + at.getDimensions() + ")";
232         }
233         return "new ObjectType(\"" + Utility.signatureToString(signature, false) + "\")";
234     }
235 
236     static String printType(final Type type) {
237         return printType(type.getSignature());
238     }
239 
240     private final JavaClass clazz;
241 
242     private final PrintWriter printWriter;
243 
244     private final ConstantPoolGen constantPoolGen;
245 
246     private final boolean preserveConstantPool;
247 
248     /**
249      * Constructs a new instance.
250      *
251      * @param clazz Java class to "decompile".
252      * @param out where to print the Java program in UTF-8.
253      */
254     public BCELifier(final JavaClass clazz, final OutputStream out) {
255         this.clazz = clazz;
256         this.printWriter = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8), false);
257         this.constantPoolGen = new ConstantPoolGen(this.clazz.getConstantPool());
258         this.preserveConstantPool = Arrays.stream(clazz.getAttributes()).anyMatch(BootstrapMethods.class::isInstance);
259     }
260 
261     /**
262      * Prints an array factory with initialization split across bounded methods.
263      *
264      * @param name the generated factory method name.
265      * @param type the Java array element type.
266      * @param length the array length.
267      * @param initializer the expression for an element, or null to leave it uninitialized.
268      */
269     private void printArray(final String name, final String type, final int length, final IntFunction<String> initializer) {
270         final int batchSize = 100;
271         printWriter.println("  private static " + type + "[] " + name + "() {");
272         printWriter.println("    " + type + "[] values = new " + type + "[" + length + "];");
273         for (int start = 0; start < length; start += batchSize) {
274             printWriter.println("    " + name + "_" + start + "(values);");
275         }
276         printWriter.println("    return values;");
277         printWriter.println("  }");
278         printWriter.println();
279         for (int start = 0; start < length; start += batchSize) {
280             printWriter.println("  private static void " + name + "_" + start + "(" + type + "[] values) {");
281             for (int i = start; i < Math.min(start + batchSize, length); i++) {
282                 final String expression = initializer.apply(i);
283                 if (expression != null) {
284                     printWriter.println("    values[" + i + "] = " + expression + ";");
285                 }
286             }
287             printWriter.println("  }");
288             printWriter.println();
289         }
290     }
291 
292     /**
293      * Prints bootstrap-table initialization, splitting large tables and argument lists into bounded methods.
294      *
295      * @param attribute the bootstrap-methods attribute to recreate.
296      */
297     private void printBootstrapMethods(final BootstrapMethods attribute) {
298         final BootstrapMethod[] methods = attribute.getBootstrapMethods();
299         printArray("createBootstrapMethods", "BootstrapMethod", methods.length, index -> {
300             final BootstrapMethod method = methods[index];
301             final int[] arguments = method.getBootstrapArguments();
302             final StringBuilder expression = new StringBuilder("new BootstrapMethod(").append(method.getBootstrapMethodRef()).append(", ");
303             if (arguments.length > MAX_INLINE_BOOTSTRAP_ARGUMENTS) {
304                 expression.append("createBootstrapArguments_").append(index).append("()");
305             } else {
306                 expression.append("new int[] {");
307                 for (int i = 0; i < arguments.length; i++) {
308                     if (i > 0) {
309                         expression.append(", ");
310                     }
311                     expression.append(arguments[i]);
312                 }
313                 expression.append('}');
314             }
315             return expression.append(')').toString();
316         });
317         for (int i = 0; i < methods.length; i++) {
318             final int[] arguments = methods[i].getBootstrapArguments();
319             if (arguments.length > MAX_INLINE_BOOTSTRAP_ARGUMENTS) {
320                 printArray("createBootstrapArguments_" + i, "int", arguments.length, index -> Integer.toString(arguments[index]));
321             }
322         }
323     }
324 
325     /**
326      * Prints a constant constructor using the original indices.
327      *
328      * <p>
329      * Bootstrap arguments can refer to any loadable constant, including another dynamic constant.
330      * </p>
331      *
332      * @param constant the constant to recreate.
333      * @return the Java constructor expression.
334      */
335     private String printConstant(final Constant constant) {
336         final String arguments;
337         if (constant instanceof ConstantCP) {
338             final ConstantCP reference = (ConstantCP) constant;
339             // For dynamic constants, classIndex holds the bootstrap-method index.
340             arguments = reference.getClassIndex() + ", " + reference.getNameAndTypeIndex();
341         } else if (constant instanceof ConstantClass) {
342             arguments = Integer.toString(((ConstantClass) constant).getNameIndex());
343         } else if (constant instanceof ConstantDouble) {
344             arguments = "Double.longBitsToDouble(" + Double.doubleToLongBits(((ConstantDouble) constant).getBytes()) + "L)";
345         } else if (constant instanceof ConstantFloat) {
346             arguments = "Float.intBitsToFloat(" + Float.floatToIntBits(((ConstantFloat) constant).getBytes()) + ")";
347         } else if (constant instanceof ConstantInteger) {
348             arguments = Integer.toString(((ConstantInteger) constant).getBytes());
349         } else if (constant instanceof ConstantLong) {
350             arguments = ((ConstantLong) constant).getBytes() + "L";
351         } else if (constant instanceof ConstantMethodHandle) {
352             final ConstantMethodHandle handle = (ConstantMethodHandle) constant;
353             arguments = handle.getReferenceKind() + ", " + handle.getReferenceIndex();
354         } else if (constant instanceof ConstantMethodType) {
355             arguments = Integer.toString(((ConstantMethodType) constant).getDescriptorIndex());
356         } else if (constant instanceof ConstantModule) {
357             arguments = Integer.toString(((ConstantModule) constant).getNameIndex());
358         } else if (constant instanceof ConstantNameAndType) {
359             final ConstantNameAndType nameAndType = (ConstantNameAndType) constant;
360             arguments = nameAndType.getNameIndex() + ", " + nameAndType.getSignatureIndex();
361         } else if (constant instanceof ConstantPackage) {
362             arguments = Integer.toString(((ConstantPackage) constant).getNameIndex());
363         } else if (constant instanceof ConstantString) {
364             arguments = Integer.toString(((ConstantString) constant).getStringIndex());
365         } else if (constant instanceof ConstantUtf8) {
366             arguments = "\"" + Utility.convertString(((ConstantUtf8) constant).getBytes()) + "\"";
367         } else {
368             throw new IllegalArgumentException("Unsupported constant: " + constant);
369         }
370         return "new " + constant.getClass().getSimpleName() + "(" + arguments + ")";
371     }
372 
373     /**
374      * Preserves the constant pool for bootstrap methods so all instruction, method-handle, and bootstrap-argument indices remain valid.
375      */
376     private void printConstantPool() {
377         final Constant[] constants = clazz.getConstantPool().getConstantPool();
378         printWriter.println("  private static ConstantPoolGen createConstantPool() {");
379         printWriter.println("    return new ConstantPoolGen(createConstants());");
380         printWriter.println("  }");
381         printWriter.println();
382         printArray("createConstants", "Constant", constants.length, index -> constants[index] == null ? null : printConstant(constants[index]));
383     }
384 
385     private void printCreate() {
386         printWriter.println("  public void create(OutputStream out) throws IOException {");
387         final Field[] fields = clazz.getFields();
388         if (fields.length > 0) {
389             printWriter.println("    createFields();");
390         }
391         final Method[] methods = clazz.getMethods();
392         for (int i = 0; i < methods.length; i++) {
393             printWriter.println("    createMethod_" + i + "();");
394         }
395         printWriter.println("    _cg.getJavaClass().dump(out);");
396         printWriter.println("  }");
397         printWriter.println();
398     }
399 
400     private void printMain() {
401         final String className = checkJavaName(clazz.getClassName());
402         printWriter.println("  public static void main(String[] args) throws Exception {");
403         printWriter.println("    " + className + "Creator creator = new " + className + "Creator();");
404         printWriter.println("    creator.create(new FileOutputStream(\"" + Utility.convertString(className) + ".class\"));");
405         printWriter.println("  }");
406     }
407 
408     /**
409      * Start Java code generation
410      */
411     public void start() {
412         visitJavaClass(clazz);
413         printWriter.flush();
414     }
415 
416     @Override
417     public void visitBootstrapMethods(final BootstrapMethods bootstrapMethods) {
418         printWriter.println("    _cg.addAttribute(new BootstrapMethods(" + bootstrapMethods.getNameIndex() + ", " + bootstrapMethods.getLength()
419             + ", createBootstrapMethods(), _cp.getConstantPool()));");
420     }
421 
422     @Override
423     public void visitField(final Field field) {
424         printWriter.println();
425         printWriter.println("    field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", " + printType(field.getSignature()) + ", \""
426             + Utility.convertString(field.getName()) + "\", _cp);");
427         final ConstantValue cv = field.getConstantValue();
428         if (cv != null) {
429             printWriter.print("    field.setInitValue(");
430             if (field.getType() == Type.CHAR) {
431                 printWriter.print("(char)");
432             }
433             if (field.getType() == Type.SHORT) {
434                 printWriter.print("(short)");
435             }
436             if (field.getType() == Type.BYTE) {
437                 printWriter.print("(byte)");
438             }
439             if (field.getType() == Type.BOOLEAN) {
440                 // A boolean ConstantValue is stored as a CONSTANT_Integer, but FieldGen.setInitValue(int) rejects boolean fields.
441                 // Match HotSpot initialization for noncanonical integer encodings by using the low bit.
442                 printWriter.print((field.getConstantPool().getConstantInteger(cv.getConstantValueIndex()).getBytes() & 1) != 0);
443             } else {
444                 printWriter.print(cv);
445             }
446             if (field.getType() == Type.LONG) {
447                 printWriter.print("L");
448             }
449             if (field.getType() == Type.FLOAT) {
450                 printWriter.print("F");
451             }
452             if (field.getType() == Type.DOUBLE) {
453                 printWriter.print("D");
454             }
455             printWriter.println(");");
456         }
457         printWriter.println("    _cg.addField(field.getField());");
458     }
459 
460     @Override
461     public void visitJavaClass(final JavaClass clazz) {
462         String className = checkJavaName(clazz.getClassName());
463         final String superName = clazz.getSuperclassName();
464         final String packageName = clazz.getPackageName();
465         final String inter = Utility.printArray(escape(clazz.getInterfaceNames()), false, true);
466         if (StringUtils.isNotEmpty(packageName)) {
467             className = className.substring(packageName.length() + 1);
468             printWriter.println("package " + packageName + ";");
469             printWriter.println();
470         }
471         printWriter.println("import " + BASE_PACKAGE + ".generic.*;");
472         printWriter.println("import " + BASE_PACKAGE + ".classfile.*;");
473         printWriter.println("import " + BASE_PACKAGE + ".*;");
474         printWriter.println("import java.io.*;");
475         printWriter.println();
476         printWriter.println("public class " + className + "Creator {");
477         printWriter.println("  private InstructionFactory _factory;");
478         printWriter.println("  private ConstantPoolGen    _cp;");
479         printWriter.println("  private ClassGen           _cg;");
480         printWriter.println();
481         printWriter.println("  public " + className + "Creator() {");
482         printWriter.println("    _cg = new ClassGen(\"" + Utility.convertString(packageName.isEmpty() ? className : packageName + "." + className) + "\", \""
483             + Utility.convertString(superName) + "\", \"" + Utility.convertString(clazz.getSourceFileName()) + "\", "
484             + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new String[] { " + inter + " }"
485             + (preserveConstantPool ? ", createConstantPool()" : "") + ");");
486         printWriter.println("    _cg.setMajor(" + clazz.getMajor() + ");");
487         printWriter.println("    _cg.setMinor(" + clazz.getMinor() + ");");
488         printWriter.println();
489         printWriter.println("    _cp = _cg.getConstantPool();");
490         printWriter.println("    _factory = new InstructionFactory(_cg, _cp);");
491         for (final Attribute attribute : clazz.getAttributes()) {
492             if (attribute instanceof BootstrapMethods) {
493                 attribute.accept(this);
494             }
495         }
496         printWriter.println("  }");
497         printWriter.println();
498         if (preserveConstantPool) {
499             printConstantPool();
500             for (final Attribute attribute : clazz.getAttributes()) {
501                 if (attribute instanceof BootstrapMethods) {
502                     printBootstrapMethods((BootstrapMethods) attribute);
503                 }
504             }
505         }
506         printCreate();
507         final Field[] fields = clazz.getFields();
508         if (fields.length > 0) {
509             printWriter.println("  private void createFields() {");
510             printWriter.println("    FieldGen field;");
511             for (final Field field : fields) {
512                 field.accept(this);
513             }
514             printWriter.println("  }");
515             printWriter.println();
516         }
517         final Method[] methods = clazz.getMethods();
518         for (int i = 0; i < methods.length; i++) {
519             printWriter.println("  private void createMethod_" + i + "() {");
520             methods[i].accept(this);
521             printWriter.println("  }");
522             printWriter.println();
523         }
524         printMain();
525         printWriter.println("}");
526     }
527 
528     @Override
529     public void visitMethod(final Method method) {
530         final MethodGen mg = new MethodGen(method, clazz.getClassName(), constantPoolGen);
531         printWriter.println("    InstructionList il = new InstructionList();");
532         printWriter.println("    MethodGen method = new MethodGen(" + printFlags(method.getAccessFlags(), FLAGS.METHOD) + ", " + printType(mg.getReturnType())
533             + ", " + printArgumentTypes(mg.getArgumentTypes()) + ", new String[] { " + Utility.printArray(escape(mg.getArgumentNames()), false, true) + " }, \""
534             + Utility.convertString(method.getName()) + "\", \"" + Utility.convertString(clazz.getClassName()) + "\", il, _cp);");
535         final ExceptionTable exceptionTable = method.getExceptionTable();
536         if (exceptionTable != null) {
537             final String[] exceptionNames = exceptionTable.getExceptionNames();
538             for (final String exceptionName : exceptionNames) {
539                 printWriter.print("    method.addException(\"");
540                 printWriter.print(Utility.convertString(exceptionName));
541                 printWriter.println("\");");
542             }
543         }
544         final Code code = method.getCode();
545         if (code != null) {
546             // Preserve this method's compact header setting only for versions that support it; JavaClass.dump selects the class-wide layout.
547             if (code.isCompactCodeHeader() && clazz.getMajor() == Const.MAJOR_1_1 && clazz.getMinor() < Const.MINOR_1_1) {
548                 printWriter.println("    method.setCompactCodeHeader(true);");
549             }
550             final StackMap stackMap = code.getStackMap();
551             if (stackMap != null) {
552                 stackMap.accept(this);
553             }
554         }
555         printWriter.println();
556         final BCELFactory factory = new BCELFactory(mg, printWriter, preserveConstantPool);
557         factory.start();
558         printWriter.println("    method.setMaxStack();");
559         printWriter.println("    method.setMaxLocals();");
560         printWriter.println("    _cg.addMethod(method.getMethod());");
561         printWriter.println("    il.dispose();");
562     }
563 
564     @Override
565     public void visitStackMap(final StackMap stackMap) {
566         super.visitStackMap(stackMap);
567         printWriter.print("    method.addCodeAttribute(");
568         printWriter.print("new StackMap(_cp.addUtf8(\"");
569         printWriter.print(Utility.convertString(stackMap.getName()));
570         printWriter.print("\"), ");
571         printWriter.print(stackMap.getLength());
572         printWriter.print(", ");
573         printWriter.print("new StackMapEntry[] {");
574         final StackMapEntry[] table = stackMap.getStackMap();
575         for (int i = 0; i < table.length; i++) {
576             table[i].accept(this);
577             if (i < table.length - 1) {
578                 printWriter.print(", ");
579             } else {
580                 printWriter.print(" }");
581             }
582         }
583         printWriter.print(", _cp.getConstantPool())");
584         printWriter.println(");");
585     }
586 
587     @Override
588     public void visitStackMapEntry(final StackMapEntry stackMapEntry) {
589         super.visitStackMapEntry(stackMapEntry);
590         printWriter.print("new StackMapEntry(");
591         printWriter.print(stackMapEntry.getFrameType());
592         printWriter.print(", ");
593         printWriter.print(stackMapEntry.getByteCodeOffset());
594         printWriter.print(", ");
595         visitStackMapTypeArray(stackMapEntry.getTypesOfLocals());
596         printWriter.print(", ");
597         visitStackMapTypeArray(stackMapEntry.getTypesOfStackItems());
598         printWriter.print(", _cp.getConstantPool())");
599     }
600 
601     /**
602      * Visits a {@link StackMapType} object.
603      *
604      * @param stackMapType object to visit.
605      * @since 6.7.1
606      */
607     @Override
608     public void visitStackMapType(final StackMapType stackMapType) {
609         super.visitStackMapType(stackMapType);
610         printWriter.print("new StackMapType((byte)");
611         printWriter.print(stackMapType.getType());
612         printWriter.print(", ");
613         if (stackMapType.hasIndex()) {
614             printWriter.print("_cp.addClass(\"");
615             printWriter.print(Utility.convertString(stackMapType.getClassName()));
616             printWriter.print("\")");
617         } else {
618             printWriter.print("-1");
619         }
620         printWriter.print(", _cp.getConstantPool())");
621     }
622 
623     private void visitStackMapTypeArray(final StackMapType[] types) {
624         if (ArrayUtils.isEmpty(types)) {
625             printWriter.print("null"); // null translates to StackMapType.EMPTY_ARRAY
626         } else {
627             printWriter.print("new StackMapType[] {");
628             for (int i = 0; i < types.length; i++) {
629                 types[i].accept(this);
630                 if (i < types.length - 1) {
631                     printWriter.print(", ");
632                 } else {
633                     printWriter.print(" }");
634                 }
635             }
636         }
637     }
638 }