Utility.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  *  Unless required by applicable law or agreed to in writing, software
  12.  *  distributed under the License is distributed on an "AS IS" BASIS,
  13.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  *  See the License for the specific language governing permissions and
  15.  *  limitations under the License.
  16.  */

  17. package org.apache.bcel.classfile;

  18. import java.io.ByteArrayInputStream;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.CharArrayReader;
  21. import java.io.CharArrayWriter;
  22. import java.io.FilterReader;
  23. import java.io.FilterWriter;
  24. import java.io.IOException;
  25. import java.io.PrintStream;
  26. import java.io.PrintWriter;
  27. import java.io.Reader;
  28. import java.io.Writer;
  29. import java.util.ArrayList;
  30. import java.util.Arrays;
  31. import java.util.List;
  32. import java.util.Locale;
  33. import java.util.zip.GZIPInputStream;
  34. import java.util.zip.GZIPOutputStream;

  35. import org.apache.bcel.Const;
  36. import org.apache.bcel.util.ByteSequence;
  37. import org.apache.commons.lang3.ArrayFill;
  38. import org.apache.commons.lang3.ArrayUtils;

  39. /**
  40.  * Utility functions that do not really belong to any class in particular.
  41.  */
  42. // @since 6.0 methods are no longer final
  43. public abstract class Utility {

  44.     /**
  45.      * Decode characters into bytes. Used by <a href="Utility.html#decode(java.lang.String, boolean)">decode()</a>
  46.      */
  47.     private static final class JavaReader extends FilterReader {

  48.         public JavaReader(final Reader in) {
  49.             super(in);
  50.         }

  51.         @Override
  52.         public int read() throws IOException {
  53.             final int b = in.read();
  54.             if (b != ESCAPE_CHAR) {
  55.                 return b;
  56.             }
  57.             final int i = in.read();
  58.             if (i < 0) {
  59.                 return -1;
  60.             }
  61.             if (i >= '0' && i <= '9' || i >= 'a' && i <= 'f') { // Normal escape
  62.                 final int j = in.read();
  63.                 if (j < 0) {
  64.                     return -1;
  65.                 }
  66.                 final char[] tmp = {(char) i, (char) j};
  67.                 return Integer.parseInt(new String(tmp), 16);
  68.             }
  69.             return MAP_CHAR[i];
  70.         }

  71.         @Override
  72.         public int read(final char[] cbuf, final int off, final int len) throws IOException {
  73.             for (int i = 0; i < len; i++) {
  74.                 cbuf[off + i] = (char) read();
  75.             }
  76.             return len;
  77.         }
  78.     }

  79.     /**
  80.      * Encode bytes into valid Java identifier characters. Used by
  81.      * <a href="Utility.html#encode(byte[], boolean)">encode()</a>
  82.      */
  83.     private static final class JavaWriter extends FilterWriter {

  84.         public JavaWriter(final Writer out) {
  85.             super(out);
  86.         }

  87.         @Override
  88.         public void write(final char[] cbuf, final int off, final int len) throws IOException {
  89.             for (int i = 0; i < len; i++) {
  90.                 write(cbuf[off + i]);
  91.             }
  92.         }

  93.         @Override
  94.         public void write(final int b) throws IOException {
  95.             if (isJavaIdentifierPart((char) b) && b != ESCAPE_CHAR) {
  96.                 out.write(b);
  97.             } else {
  98.                 out.write(ESCAPE_CHAR); // Escape character
  99.                 // Special escape
  100.                 if (b >= 0 && b < FREE_CHARS) {
  101.                     out.write(CHAR_MAP[b]);
  102.                 } else { // Normal escape
  103.                     final char[] tmp = Integer.toHexString(b).toCharArray();
  104.                     if (tmp.length == 1) {
  105.                         out.write('0');
  106.                         out.write(tmp[0]);
  107.                     } else {
  108.                         out.write(tmp[0]);
  109.                         out.write(tmp[1]);
  110.                     }
  111.                 }
  112.             }
  113.         }

  114.         @Override
  115.         public void write(final String str, final int off, final int len) throws IOException {
  116.             write(str.toCharArray(), off, len);
  117.         }
  118.     }

  119.     /*
  120.      * How many chars have been consumed during parsing in typeSignatureToString(). Read by methodSignatureToString(). Set
  121.      * by side effect, but only internally.
  122.      */
  123.     private static final ThreadLocal<Integer> CONSUMER_CHARS = ThreadLocal.withInitial(() -> Integer.valueOf(0));

  124.     /*
  125.      * The 'WIDE' instruction is used in the byte code to allow 16-bit wide indices for local variables. This opcode
  126.      * precedes an 'ILOAD', e.g.. The opcode immediately following takes an extra byte which is combined with the following
  127.      * byte to form a 16-bit value.
  128.      */
  129.     private static boolean wide;

  130.     // A-Z, g-z, _, $
  131.     private static final int FREE_CHARS = 48;

  132.     private static final int[] CHAR_MAP = new int[FREE_CHARS];

  133.     private static final int[] MAP_CHAR = new int[256]; // Reverse map

  134.     private static final char ESCAPE_CHAR = '$';

  135.     static {
  136.         int j = 0;
  137.         for (int i = 'A'; i <= 'Z'; i++) {
  138.             CHAR_MAP[j] = i;
  139.             MAP_CHAR[i] = j;
  140.             j++;
  141.         }
  142.         for (int i = 'g'; i <= 'z'; i++) {
  143.             CHAR_MAP[j] = i;
  144.             MAP_CHAR[i] = j;
  145.             j++;
  146.         }
  147.         CHAR_MAP[j] = '$';
  148.         MAP_CHAR['$'] = j;
  149.         j++;
  150.         CHAR_MAP[j] = '_';
  151.         MAP_CHAR['_'] = j;
  152.     }

  153.     /**
  154.      * Convert bit field of flags into string such as 'static final'.
  155.      *
  156.      * @param accessFlags Access flags
  157.      * @return String representation of flags
  158.      */
  159.     public static String accessToString(final int accessFlags) {
  160.         return accessToString(accessFlags, false);
  161.     }

  162.     /**
  163.      * Convert bit field of flags into string such as 'static final'.
  164.      *
  165.      * Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized".
  166.      * This is because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'.
  167.      *
  168.      * @param accessFlags Access flags
  169.      * @param forClass access flags are for class qualifiers ?
  170.      * @return String representation of flags
  171.      */
  172.     public static String accessToString(final int accessFlags, final boolean forClass) {
  173.         final StringBuilder buf = new StringBuilder();
  174.         int p = 0;
  175.         for (int i = 0; p < Const.MAX_ACC_FLAG_I; i++) { // Loop through known flags
  176.             p = pow2(i);
  177.             if ((accessFlags & p) != 0) {
  178.                 /*
  179.                  * Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized".
  180.                  * This is because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'.
  181.                  */
  182.                 if (forClass && (p == Const.ACC_SUPER || p == Const.ACC_INTERFACE)) {
  183.                     continue;
  184.                 }
  185.                 buf.append(Const.getAccessName(i)).append(" ");
  186.             }
  187.         }
  188.         return buf.toString().trim();
  189.     }

  190.     /**
  191.      * Convert (signed) byte to (unsigned) short value, i.e., all negative values become positive.
  192.      */
  193.     private static short byteToShort(final byte b) {
  194.         return b < 0 ? (short) (256 + b) : (short) b;
  195.     }

  196.     /**
  197.      * @param accessFlags the class flags
  198.      *
  199.      * @return "class" or "interface", depending on the ACC_INTERFACE flag
  200.      */
  201.     public static String classOrInterface(final int accessFlags) {
  202.         return (accessFlags & Const.ACC_INTERFACE) != 0 ? "interface" : "class";
  203.     }

  204.     /**
  205.      * @return 'flag' with bit 'i' set to 0
  206.      */
  207.     public static int clearBit(final int flag, final int i) {
  208.         final int bit = pow2(i);
  209.         return (flag & bit) == 0 ? flag : flag ^ bit;
  210.     }

  211.     public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length) {
  212.         return codeToString(code, constantPool, index, length, true);
  213.     }

  214.     /**
  215.      * Disassemble a byte array of JVM byte codes starting from code line 'index' and return the disassembled string
  216.      * representation. Decode only 'num' opcodes (including their operands), use -1 if you want to decompile everything.
  217.      *
  218.      * @param code byte code array
  219.      * @param constantPool Array of constants
  220.      * @param index offset in 'code' array <EM>(number of opcodes, not bytes!)</EM>
  221.      * @param length number of opcodes to decompile, -1 for all
  222.      * @param verbose be verbose, e.g. print constant pool index
  223.      * @return String representation of byte codes
  224.      */
  225.     public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length, final boolean verbose) {
  226.         final StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient // CHECKSTYLE IGNORE MagicNumber
  227.         try (ByteSequence stream = new ByteSequence(code)) {
  228.             for (int i = 0; i < index; i++) {
  229.                 codeToString(stream, constantPool, verbose);
  230.             }
  231.             for (int i = 0; stream.available() > 0; i++) {
  232.                 if (length < 0 || i < length) {
  233.                     final String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
  234.                     buf.append(indices).append(codeToString(stream, constantPool, verbose)).append('\n');
  235.                 }
  236.             }
  237.         } catch (final IOException e) {
  238.             throw new ClassFormatException("Byte code error: " + buf.toString(), e);
  239.         }
  240.         return buf.toString();
  241.     }

  242.     public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool) throws IOException {
  243.         return codeToString(bytes, constantPool, true);
  244.     }

  245.     /**
  246.      * Disassemble a stream of byte codes and return the string representation.
  247.      *
  248.      * @param bytes stream of bytes
  249.      * @param constantPool Array of constants
  250.      * @param verbose be verbose, e.g. print constant pool index
  251.      * @return String representation of byte code
  252.      *
  253.      * @throws IOException if a failure from reading from the bytes argument occurs
  254.      */
  255.     public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool, final boolean verbose) throws IOException {
  256.         final short opcode = (short) bytes.readUnsignedByte();
  257.         int defaultOffset = 0;
  258.         int low;
  259.         int high;
  260.         int npairs;
  261.         int index;
  262.         int vindex;
  263.         int constant;
  264.         int[] match;
  265.         int[] jumpTable;
  266.         int noPadBytes = 0;
  267.         int offset;
  268.         final StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode));
  269.         /*
  270.          * Special case: Skip (0-3) padding bytes, i.e., the following bytes are 4-byte-aligned
  271.          */
  272.         if (opcode == Const.TABLESWITCH || opcode == Const.LOOKUPSWITCH) {
  273.             final int remainder = bytes.getIndex() % 4;
  274.             noPadBytes = remainder == 0 ? 0 : 4 - remainder;
  275.             for (int i = 0; i < noPadBytes; i++) {
  276.                 byte b;
  277.                 if ((b = bytes.readByte()) != 0) {
  278.                     System.err.println("Warning: Padding byte != 0 in " + Const.getOpcodeName(opcode) + ":" + b);
  279.                 }
  280.             }
  281.             // Both cases have a field default_offset in common
  282.             defaultOffset = bytes.readInt();
  283.         }
  284.         switch (opcode) {
  285.         /*
  286.          * Table switch has variable length arguments.
  287.          */
  288.         case Const.TABLESWITCH:
  289.             low = bytes.readInt();
  290.             high = bytes.readInt();
  291.             offset = bytes.getIndex() - 12 - noPadBytes - 1;
  292.             defaultOffset += offset;
  293.             buf.append("\tdefault = ").append(defaultOffset).append(", low = ").append(low).append(", high = ").append(high).append("(");
  294.             jumpTable = new int[high - low + 1];
  295.             for (int i = 0; i < jumpTable.length; i++) {
  296.                 jumpTable[i] = offset + bytes.readInt();
  297.                 buf.append(jumpTable[i]);
  298.                 if (i < jumpTable.length - 1) {
  299.                     buf.append(", ");
  300.                 }
  301.             }
  302.             buf.append(")");
  303.             break;
  304.         /*
  305.          * Lookup switch has variable length arguments.
  306.          */
  307.         case Const.LOOKUPSWITCH: {
  308.             npairs = bytes.readInt();
  309.             offset = bytes.getIndex() - 8 - noPadBytes - 1;
  310.             match = new int[npairs];
  311.             jumpTable = new int[npairs];
  312.             defaultOffset += offset;
  313.             buf.append("\tdefault = ").append(defaultOffset).append(", npairs = ").append(npairs).append(" (");
  314.             for (int i = 0; i < npairs; i++) {
  315.                 match[i] = bytes.readInt();
  316.                 jumpTable[i] = offset + bytes.readInt();
  317.                 buf.append("(").append(match[i]).append(", ").append(jumpTable[i]).append(")");
  318.                 if (i < npairs - 1) {
  319.                     buf.append(", ");
  320.                 }
  321.             }
  322.             buf.append(")");
  323.         }
  324.             break;
  325.         /*
  326.          * Two address bytes + offset from start of byte stream form the jump target
  327.          */
  328.         case Const.GOTO:
  329.         case Const.IFEQ:
  330.         case Const.IFGE:
  331.         case Const.IFGT:
  332.         case Const.IFLE:
  333.         case Const.IFLT:
  334.         case Const.JSR:
  335.         case Const.IFNE:
  336.         case Const.IFNONNULL:
  337.         case Const.IFNULL:
  338.         case Const.IF_ACMPEQ:
  339.         case Const.IF_ACMPNE:
  340.         case Const.IF_ICMPEQ:
  341.         case Const.IF_ICMPGE:
  342.         case Const.IF_ICMPGT:
  343.         case Const.IF_ICMPLE:
  344.         case Const.IF_ICMPLT:
  345.         case Const.IF_ICMPNE:
  346.             buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readShort());
  347.             break;
  348.         /*
  349.          * 32-bit wide jumps
  350.          */
  351.         case Const.GOTO_W:
  352.         case Const.JSR_W:
  353.             buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readInt());
  354.             break;
  355.         /*
  356.          * Index byte references local variable (register)
  357.          */
  358.         case Const.ALOAD:
  359.         case Const.ASTORE:
  360.         case Const.DLOAD:
  361.         case Const.DSTORE:
  362.         case Const.FLOAD:
  363.         case Const.FSTORE:
  364.         case Const.ILOAD:
  365.         case Const.ISTORE:
  366.         case Const.LLOAD:
  367.         case Const.LSTORE:
  368.         case Const.RET:
  369.             if (wide) {
  370.                 vindex = bytes.readUnsignedShort();
  371.                 wide = false; // Clear flag
  372.             } else {
  373.                 vindex = bytes.readUnsignedByte();
  374.             }
  375.             buf.append("\t\t%").append(vindex);
  376.             break;
  377.         /*
  378.          * Remember wide byte which is used to form a 16-bit address in the following instruction. Relies on that the method is
  379.          * called again with the following opcode.
  380.          */
  381.         case Const.WIDE:
  382.             wide = true;
  383.             buf.append("\t(wide)");
  384.             break;
  385.         /*
  386.          * Array of basic type.
  387.          */
  388.         case Const.NEWARRAY:
  389.             buf.append("\t\t<").append(Const.getTypeName(bytes.readByte())).append(">");
  390.             break;
  391.         /*
  392.          * Access object/class fields.
  393.          */
  394.         case Const.GETFIELD:
  395.         case Const.GETSTATIC:
  396.         case Const.PUTFIELD:
  397.         case Const.PUTSTATIC:
  398.             index = bytes.readUnsignedShort();
  399.             buf.append("\t\t").append(constantPool.constantToString(index, Const.CONSTANT_Fieldref)).append(verbose ? " (" + index + ")" : "");
  400.             break;
  401.         /*
  402.          * Operands are references to classes in constant pool
  403.          */
  404.         case Const.NEW:
  405.         case Const.CHECKCAST:
  406.             buf.append("\t");
  407.             index = bytes.readUnsignedShort();
  408.             buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
  409.             break;
  410.         case Const.INSTANCEOF:
  411.             index = bytes.readUnsignedShort();
  412.             buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
  413.             break;
  414.         /*
  415.          * Operands are references to methods in constant pool
  416.          */
  417.         case Const.INVOKESPECIAL:
  418.         case Const.INVOKESTATIC:
  419.             index = bytes.readUnsignedShort();
  420.             final Constant c = constantPool.getConstant(index);
  421.             // With Java8 operand may be either a CONSTANT_Methodref
  422.             // or a CONSTANT_InterfaceMethodref. (markro)
  423.             buf.append("\t").append(constantPool.constantToString(index, c.getTag())).append(verbose ? " (" + index + ")" : "");
  424.             break;
  425.         case Const.INVOKEVIRTUAL:
  426.             index = bytes.readUnsignedShort();
  427.             buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_Methodref)).append(verbose ? " (" + index + ")" : "");
  428.             break;
  429.         case Const.INVOKEINTERFACE:
  430.             index = bytes.readUnsignedShort();
  431.             final int nargs = bytes.readUnsignedByte(); // historical, redundant
  432.             buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InterfaceMethodref)).append(verbose ? " (" + index + ")\t" : "")
  433.                 .append(nargs).append("\t").append(bytes.readUnsignedByte()); // Last byte is a reserved space
  434.             break;
  435.         case Const.INVOKEDYNAMIC:
  436.             index = bytes.readUnsignedShort();
  437.             buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InvokeDynamic)).append(verbose ? " (" + index + ")\t" : "")
  438.                 .append(bytes.readUnsignedByte()) // Thrid byte is a reserved space
  439.                 .append(bytes.readUnsignedByte()); // Last byte is a reserved space
  440.             break;
  441.         /*
  442.          * Operands are references to items in constant pool
  443.          */
  444.         case Const.LDC_W:
  445.         case Const.LDC2_W:
  446.             index = bytes.readUnsignedShort();
  447.             buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
  448.                 .append(verbose ? " (" + index + ")" : "");
  449.             break;
  450.         case Const.LDC:
  451.             index = bytes.readUnsignedByte();
  452.             buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
  453.                 .append(verbose ? " (" + index + ")" : "");
  454.             break;
  455.         /*
  456.          * Array of references.
  457.          */
  458.         case Const.ANEWARRAY:
  459.             index = bytes.readUnsignedShort();
  460.             buf.append("\t\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">")
  461.                 .append(verbose ? " (" + index + ")" : "");
  462.             break;
  463.         /*
  464.          * Multidimensional array of references.
  465.          */
  466.         case Const.MULTIANEWARRAY: {
  467.             index = bytes.readUnsignedShort();
  468.             final int dimensions = bytes.readUnsignedByte();
  469.             buf.append("\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">\t").append(dimensions)
  470.                 .append(verbose ? " (" + index + ")" : "");
  471.         }
  472.             break;
  473.         /*
  474.          * Increment local variable.
  475.          */
  476.         case Const.IINC:
  477.             if (wide) {
  478.                 vindex = bytes.readUnsignedShort();
  479.                 constant = bytes.readShort();
  480.                 wide = false;
  481.             } else {
  482.                 vindex = bytes.readUnsignedByte();
  483.                 constant = bytes.readByte();
  484.             }
  485.             buf.append("\t\t%").append(vindex).append("\t").append(constant);
  486.             break;
  487.         default:
  488.             if (Const.getNoOfOperands(opcode) > 0) {
  489.                 for (int i = 0; i < Const.getOperandTypeCount(opcode); i++) {
  490.                     buf.append("\t\t");
  491.                     switch (Const.getOperandType(opcode, i)) {
  492.                     case Const.T_BYTE:
  493.                         buf.append(bytes.readByte());
  494.                         break;
  495.                     case Const.T_SHORT:
  496.                         buf.append(bytes.readShort());
  497.                         break;
  498.                     case Const.T_INT:
  499.                         buf.append(bytes.readInt());
  500.                         break;
  501.                     default: // Never reached
  502.                         throw new IllegalStateException("Unreachable default case reached!");
  503.                     }
  504.                 }
  505.             }
  506.         }
  507.         return buf.toString();
  508.     }

  509.     /**
  510.      * Shorten long class names, <em>java/lang/String</em> becomes <em>String</em>.
  511.      *
  512.      * @param str The long class name
  513.      * @return Compacted class name
  514.      */
  515.     public static String compactClassName(final String str) {
  516.         return compactClassName(str, true);
  517.     }

  518.     /**
  519.      * Shorten long class names, <em>java/lang/String</em> becomes <em>java.lang.String</em>, e.g.. If <em>chopit</em> is
  520.      * <em>true</em> the prefix <em>java.lang</em> is also removed.
  521.      *
  522.      * @param str The long class name
  523.      * @param chopit flag that determines whether chopping is executed or not
  524.      * @return Compacted class name
  525.      */
  526.     public static String compactClassName(final String str, final boolean chopit) {
  527.         return compactClassName(str, "java.lang.", chopit);
  528.     }

  529.     /**
  530.      * Shorten long class name <em>str</em>, i.e., chop off the <em>prefix</em>, if the class name starts with this string
  531.      * and the flag <em>chopit</em> is true. Slashes <em>/</em> are converted to dots <em>.</em>.
  532.      *
  533.      * @param str The long class name
  534.      * @param prefix The prefix the get rid off
  535.      * @param chopit flag that determines whether chopping is executed or not
  536.      * @return Compacted class name
  537.      */
  538.     public static String compactClassName(String str, final String prefix, final boolean chopit) {
  539.         final int len = prefix.length();
  540.         str = pathToPackage(str); // Is '/' on all systems, even DOS
  541.         // If string starts with 'prefix' and contains no further dots
  542.         if (chopit && str.startsWith(prefix) && str.substring(len).indexOf('.') == -1) {
  543.             str = str.substring(len);
  544.         }
  545.         return str;
  546.     }

  547.     /**
  548.      * Escape all occurrences of newline chars '\n', quotes \", etc.
  549.      */
  550.     public static String convertString(final String label) {
  551.         final char[] ch = label.toCharArray();
  552.         final StringBuilder buf = new StringBuilder();
  553.         for (final char element : ch) {
  554.             switch (element) {
  555.             case '\n':
  556.                 buf.append("\\n");
  557.                 break;
  558.             case '\r':
  559.                 buf.append("\\r");
  560.                 break;
  561.             case '\"':
  562.                 buf.append("\\\"");
  563.                 break;
  564.             case '\'':
  565.                 buf.append("\\'");
  566.                 break;
  567.             case '\\':
  568.                 buf.append("\\\\");
  569.                 break;
  570.             default:
  571.                 buf.append(element);
  572.                 break;
  573.             }
  574.         }
  575.         return buf.toString();
  576.     }

  577.     private static int countBrackets(final String brackets) {
  578.         final char[] chars = brackets.toCharArray();
  579.         int count = 0;
  580.         boolean open = false;
  581.         for (final char c : chars) {
  582.             switch (c) {
  583.             case '[':
  584.                 if (open) {
  585.                     throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
  586.                 }
  587.                 open = true;
  588.                 break;
  589.             case ']':
  590.                 if (!open) {
  591.                     throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
  592.                 }
  593.                 open = false;
  594.                 count++;
  595.                 break;
  596.             default:
  597.                 // Don't care
  598.                 break;
  599.             }
  600.         }
  601.         if (open) {
  602.             throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
  603.         }
  604.         return count;
  605.     }

  606.     /**
  607.      * Decode a string back to a byte array.
  608.      *
  609.      * @param s the string to convert
  610.      * @param uncompress use gzip to uncompress the stream of bytes
  611.      *
  612.      * @throws IOException if there's a gzip exception
  613.      */
  614.     public static byte[] decode(final String s, final boolean uncompress) throws IOException {
  615.         byte[] bytes;
  616.         try (JavaReader jr = new JavaReader(new CharArrayReader(s.toCharArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
  617.             int ch;
  618.             while ((ch = jr.read()) >= 0) {
  619.                 bos.write(ch);
  620.             }
  621.             bytes = bos.toByteArray();
  622.         }
  623.         if (uncompress) {
  624.             final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
  625.             final byte[] tmp = new byte[bytes.length * 3]; // Rough estimate
  626.             int count = 0;
  627.             int b;
  628.             while ((b = gis.read()) >= 0) {
  629.                 tmp[count++] = (byte) b;
  630.             }
  631.             bytes = Arrays.copyOf(tmp, count);
  632.         }
  633.         return bytes;
  634.     }

  635.     /**
  636.      * Encode byte array it into Java identifier string, i.e., a string that only contains the following characters: (a, ...
  637.      * z, A, ... Z, 0, ... 9, _, $). The encoding algorithm itself is not too clever: if the current byte's ASCII value
  638.      * already is a valid Java identifier part, leave it as it is. Otherwise it writes the escape character($) followed by:
  639.      *
  640.      * <ul>
  641.      * <li>the ASCII value as a hexadecimal string, if the value is not in the range 200..247</li>
  642.      * <li>a Java identifier char not used in a lowercase hexadecimal string, if the value is in the range 200..247</li>
  643.      * </ul>
  644.      *
  645.      * <p>
  646.      * This operation inflates the original byte array by roughly 40-50%
  647.      * </p>
  648.      *
  649.      * @param bytes the byte array to convert
  650.      * @param compress use gzip to minimize string
  651.      *
  652.      * @throws IOException if there's a gzip exception
  653.      */
  654.     public static String encode(byte[] bytes, final boolean compress) throws IOException {
  655.         if (compress) {
  656.             try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos)) {
  657.                 gos.write(bytes, 0, bytes.length);
  658.                 gos.close();
  659.                 bytes = baos.toByteArray();
  660.             }
  661.         }
  662.         final CharArrayWriter caw = new CharArrayWriter();
  663.         try (JavaWriter jw = new JavaWriter(caw)) {
  664.             for (final byte b : bytes) {
  665.                 final int in = b & 0x000000ff; // Normalize to unsigned
  666.                 jw.write(in);
  667.             }
  668.         }
  669.         return caw.toString();
  670.     }

  671.     /**
  672.      * Fillup char with up to length characters with char 'fill' and justify it left or right.
  673.      *
  674.      * @param str string to format
  675.      * @param length length of desired string
  676.      * @param leftJustify format left or right
  677.      * @param fill fill character
  678.      * @return formatted string
  679.      */
  680.     public static String fillup(final String str, final int length, final boolean leftJustify, final char fill) {
  681.         final int len = length - str.length();
  682.         final char[] buf = ArrayFill.fill(new char[Math.max(len, 0)], fill);
  683.         if (leftJustify) {
  684.             return str + new String(buf);
  685.         }
  686.         return new String(buf) + str;
  687.     }

  688.     /**
  689.      * Return a string for an integer justified left or right and filled up with 'fill' characters if necessary.
  690.      *
  691.      * @param i integer to format
  692.      * @param length length of desired string
  693.      * @param leftJustify format left or right
  694.      * @param fill fill character
  695.      * @return formatted int
  696.      */
  697.     public static String format(final int i, final int length, final boolean leftJustify, final char fill) {
  698.         return fillup(Integer.toString(i), length, leftJustify, fill);
  699.     }

  700.     /**
  701.      * WARNING:
  702.      *
  703.      * There is some nomenclature confusion through much of the BCEL code base with respect to the terms Descriptor and
  704.      * Signature. For the offical definitions see:
  705.      *
  706.      * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3"> Descriptors in The Java
  707.      *      Virtual Machine Specification</a>
  708.      *
  709.      * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.9.1"> Signatures in The Java
  710.      *      Virtual Machine Specification</a>
  711.      *
  712.      *      In brief, a descriptor is a string representing the type of a field or method. Signatures are similar, but more
  713.      *      complex. Signatures are used to encode declarations written in the Java programming language that use types
  714.      *      outside the type system of the Java Virtual Machine. They are used to describe the type of any class, interface,
  715.      *      constructor, method or field whose declaration uses type variables or parameterized types.
  716.      *
  717.      *      To parse a descriptor, call typeSignatureToString. To parse a signature, call signatureToString.
  718.      *
  719.      *      Note that if the signature string is a single, non-generic item, the call to signatureToString reduces to a call
  720.      *      to typeSignatureToString. Also note, that if you only wish to parse the first item in a longer signature string,
  721.      *      you should call typeSignatureToString directly.
  722.      */

  723.     /**
  724.      * Parse Java type such as "char", or "java.lang.String[]" and return the signature in byte code format, e.g. "C" or
  725.      * "[Ljava/lang/String;" respectively.
  726.      *
  727.      * @param type Java type
  728.      * @return byte code signature
  729.      */
  730.     public static String getSignature(String type) {
  731.         final StringBuilder buf = new StringBuilder();
  732.         final char[] chars = type.toCharArray();
  733.         boolean charFound = false;
  734.         boolean delim = false;
  735.         int index = -1;
  736.         loop: for (int i = 0; i < chars.length; i++) {
  737.             switch (chars[i]) {
  738.             case ' ':
  739.             case '\t':
  740.             case '\n':
  741.             case '\r':
  742.             case '\f':
  743.                 if (charFound) {
  744.                     delim = true;
  745.                 }
  746.                 break;
  747.             case '[':
  748.                 if (!charFound) {
  749.                     throw new IllegalArgumentException("Illegal type: " + type);
  750.                 }
  751.                 index = i;
  752.                 break loop;
  753.             default:
  754.                 charFound = true;
  755.                 if (!delim) {
  756.                     buf.append(chars[i]);
  757.                 }
  758.             }
  759.         }
  760.         int brackets = 0;
  761.         if (index > 0) {
  762.             brackets = countBrackets(type.substring(index));
  763.         }
  764.         type = buf.toString();
  765.         buf.setLength(0);
  766.         for (int i = 0; i < brackets; i++) {
  767.             buf.append('[');
  768.         }
  769.         boolean found = false;
  770.         for (int i = Const.T_BOOLEAN; i <= Const.T_VOID && !found; i++) {
  771.             if (Const.getTypeName(i).equals(type)) {
  772.                 found = true;
  773.                 buf.append(Const.getShortTypeName(i));
  774.             }
  775.         }
  776.         if (!found) {
  777.             buf.append('L').append(packageToPath(type)).append(';');
  778.         }
  779.         return buf.toString();
  780.     }

  781.     /**
  782.      * @param ch the character to test if it's part of an identifier
  783.      *
  784.      * @return true, if character is one of (a, ... z, A, ... Z, 0, ... 9, _)
  785.      */
  786.     public static boolean isJavaIdentifierPart(final char ch) {
  787.         return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '_';
  788.     }

  789.     /**
  790.      * @return true, if bit 'i' in 'flag' is set
  791.      */
  792.     public static boolean isSet(final int flag, final int i) {
  793.         return (flag & pow2(i)) != 0;
  794.     }

  795.     /**
  796.      * Converts argument list portion of method signature to string with all class names compacted.
  797.      *
  798.      * @param signature Method signature
  799.      * @return String Array of argument types
  800.      * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
  801.      */
  802.     public static String[] methodSignatureArgumentTypes(final String signature) throws ClassFormatException {
  803.         return methodSignatureArgumentTypes(signature, true);
  804.     }

  805.     /**
  806.      * Converts argument list portion of method signature to string.
  807.      *
  808.      * @param signature Method signature
  809.      * @param chopit flag that determines whether chopping is executed or not
  810.      * @return String Array of argument types
  811.      * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
  812.      */
  813.     public static String[] methodSignatureArgumentTypes(final String signature, final boolean chopit) throws ClassFormatException {
  814.         final List<String> vec = new ArrayList<>();
  815.         int index;
  816.         try {
  817.             // Skip any type arguments to read argument declarations between '(' and ')'
  818.             index = signature.indexOf('(') + 1;
  819.             if (index <= 0) {
  820.                 throw new InvalidMethodSignatureException(signature);
  821.             }
  822.             while (signature.charAt(index) != ')') {
  823.                 vec.add(typeSignatureToString(signature.substring(index), chopit));
  824.                 // corrected concurrent private static field acess
  825.                 index += unwrap(CONSUMER_CHARS); // update position
  826.             }
  827.         } catch (final StringIndexOutOfBoundsException e) { // Should never occur
  828.             throw new InvalidMethodSignatureException(signature, e);
  829.         }
  830.         return vec.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
  831.     }

  832.     /**
  833.      * Converts return type portion of method signature to string with all class names compacted.
  834.      *
  835.      * @param signature Method signature
  836.      * @return String representation of method return type
  837.      * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
  838.      */
  839.     public static String methodSignatureReturnType(final String signature) throws ClassFormatException {
  840.         return methodSignatureReturnType(signature, true);
  841.     }

  842.     /**
  843.      * Converts return type portion of method signature to string.
  844.      *
  845.      * @param signature Method signature
  846.      * @param chopit flag that determines whether chopping is executed or not
  847.      * @return String representation of method return type
  848.      * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
  849.      */
  850.     public static String methodSignatureReturnType(final String signature, final boolean chopit) throws ClassFormatException {
  851.         int index;
  852.         String type;
  853.         try {
  854.             // Read return type after ')'
  855.             index = signature.lastIndexOf(')') + 1;
  856.             if (index <= 0) {
  857.                 throw new InvalidMethodSignatureException(signature);
  858.             }
  859.             type = typeSignatureToString(signature.substring(index), chopit);
  860.         } catch (final StringIndexOutOfBoundsException e) { // Should never occur
  861.             throw new InvalidMethodSignatureException(signature, e);
  862.         }
  863.         return type;
  864.     }

  865.     /**
  866.      * Converts method signature to string with all class names compacted.
  867.      *
  868.      * @param signature to convert
  869.      * @param name of method
  870.      * @param access flags of method
  871.      * @return Human readable signature
  872.      */
  873.     public static String methodSignatureToString(final String signature, final String name, final String access) {
  874.         return methodSignatureToString(signature, name, access, true);
  875.     }

  876.     /**
  877.      * Converts method signature to string.
  878.      *
  879.      * @param signature to convert
  880.      * @param name of method
  881.      * @param access flags of method
  882.      * @param chopit flag that determines whether chopping is executed or not
  883.      * @return Human readable signature
  884.      */
  885.     public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit) {
  886.         return methodSignatureToString(signature, name, access, chopit, null);
  887.     }

  888.     /**
  889.      * This method converts a method signature string into a Java type declaration like 'void main(String[])' and throws a
  890.      * 'ClassFormatException' when the parsed type is invalid.
  891.      *
  892.      * @param signature Method signature
  893.      * @param name Method name
  894.      * @param access Method access rights
  895.      * @param chopit flag that determines whether chopping is executed or not
  896.      * @param vars the LocalVariableTable for the method
  897.      * @return Java type declaration
  898.      * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
  899.      */
  900.     public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit,
  901.         final LocalVariableTable vars) throws ClassFormatException {
  902.         final StringBuilder buf = new StringBuilder("(");
  903.         String type;
  904.         int index;
  905.         int varIndex = access.contains("static") ? 0 : 1;
  906.         try {
  907.             // Skip any type arguments to read argument declarations between '(' and ')'
  908.             index = signature.indexOf('(') + 1;
  909.             if (index <= 0) {
  910.                 throw new InvalidMethodSignatureException(signature);
  911.             }
  912.             while (signature.charAt(index) != ')') {
  913.                 final String paramType = typeSignatureToString(signature.substring(index), chopit);
  914.                 buf.append(paramType);
  915.                 if (vars != null) {
  916.                     final LocalVariable l = vars.getLocalVariable(varIndex, 0);
  917.                     if (l != null) {
  918.                         buf.append(" ").append(l.getName());
  919.                     }
  920.                 } else {
  921.                     buf.append(" arg").append(varIndex);
  922.                 }
  923.                 if ("double".equals(paramType) || "long".equals(paramType)) {
  924.                     varIndex += 2;
  925.                 } else {
  926.                     varIndex++;
  927.                 }
  928.                 buf.append(", ");
  929.                 // corrected concurrent private static field acess
  930.                 index += unwrap(CONSUMER_CHARS); // update position
  931.             }
  932.             index++; // update position
  933.             // Read return type after ')'
  934.             type = typeSignatureToString(signature.substring(index), chopit);
  935.         } catch (final StringIndexOutOfBoundsException e) { // Should never occur
  936.             throw new InvalidMethodSignatureException(signature, e);
  937.         }
  938.         // ignore any throws information in the signature
  939.         if (buf.length() > 1) {
  940.             buf.setLength(buf.length() - 2);
  941.         }
  942.         buf.append(")");
  943.         return access + (!access.isEmpty() ? " " : "") + // May be an empty string
  944.             type + " " + name + buf.toString();
  945.     }

  946.     /**
  947.      * Converts string containing the method return and argument types to a byte code method signature.
  948.      *
  949.      * @param ret Return type of method
  950.      * @param argv Types of method arguments
  951.      * @return Byte code representation of method signature
  952.      *
  953.      * @throws ClassFormatException if the signature is for Void
  954.      */
  955.     public static String methodTypeToSignature(final String ret, final String[] argv) throws ClassFormatException {
  956.         final StringBuilder buf = new StringBuilder("(");
  957.         String str;
  958.         if (argv != null) {
  959.             for (final String element : argv) {
  960.                 str = getSignature(element);
  961.                 if (str.endsWith("V")) {
  962.                     throw new ClassFormatException("Invalid type: " + element);
  963.                 }
  964.                 buf.append(str);
  965.             }
  966.         }
  967.         str = getSignature(ret);
  968.         buf.append(")").append(str);
  969.         return buf.toString();
  970.     }

  971.     /**
  972.      * Converts '.'s to '/'s.
  973.      *
  974.      * @param name Source
  975.      * @return converted value
  976.      * @since 6.7.0
  977.      */
  978.     public static String packageToPath(final String name) {
  979.         return name.replace('.', '/');
  980.     }

  981.     /**
  982.      * Converts a path to a package name.
  983.      *
  984.      * @param str the source path.
  985.      * @return a package name.
  986.      * @since 6.6.0
  987.      */
  988.     public static String pathToPackage(final String str) {
  989.         return str.replace('/', '.');
  990.     }

  991.     private static int pow2(final int n) {
  992.         return 1 << n;
  993.     }

  994.     public static String printArray(final Object[] obj) {
  995.         return printArray(obj, true);
  996.     }

  997.     public static String printArray(final Object[] obj, final boolean braces) {
  998.         return printArray(obj, braces, false);
  999.     }

  1000.     public static String printArray(final Object[] obj, final boolean braces, final boolean quote) {
  1001.         if (obj == null) {
  1002.             return null;
  1003.         }
  1004.         final StringBuilder buf = new StringBuilder();
  1005.         if (braces) {
  1006.             buf.append('{');
  1007.         }
  1008.         for (int i = 0; i < obj.length; i++) {
  1009.             if (obj[i] != null) {
  1010.                 buf.append(quote ? "\"" : "").append(obj[i]).append(quote ? "\"" : "");
  1011.             } else {
  1012.                 buf.append("null");
  1013.             }
  1014.             if (i < obj.length - 1) {
  1015.                 buf.append(", ");
  1016.             }
  1017.         }
  1018.         if (braces) {
  1019.             buf.append('}');
  1020.         }
  1021.         return buf.toString();
  1022.     }

  1023.     public static void printArray(final PrintStream out, final Object[] obj) {
  1024.         out.println(printArray(obj, true));
  1025.     }

  1026.     public static void printArray(final PrintWriter out, final Object[] obj) {
  1027.         out.println(printArray(obj, true));
  1028.     }

  1029.     /**
  1030.      * Replace all occurrences of <em>old</em> in <em>str</em> with <em>new</em>.
  1031.      *
  1032.      * @param str String to permute
  1033.      * @param old String to be replaced
  1034.      * @param new_ Replacement string
  1035.      * @return new String object
  1036.      */
  1037.     public static String replace(String str, final String old, final String new_) {
  1038.         int index;
  1039.         int oldIndex;
  1040.         try {
  1041.             if (str.contains(old)) { // 'old' found in str
  1042.                 final StringBuilder buf = new StringBuilder();
  1043.                 oldIndex = 0; // String start offset
  1044.                 // While we have something to replace
  1045.                 while ((index = str.indexOf(old, oldIndex)) != -1) {
  1046.                     buf.append(str, oldIndex, index); // append prefix
  1047.                     buf.append(new_); // append replacement
  1048.                     oldIndex = index + old.length(); // Skip 'old'.length chars
  1049.                 }
  1050.                 buf.append(str.substring(oldIndex)); // append rest of string
  1051.                 str = buf.toString();
  1052.             }
  1053.         } catch (final StringIndexOutOfBoundsException e) { // Should not occur
  1054.             System.err.println(e);
  1055.         }
  1056.         return str;
  1057.     }

  1058.     /**
  1059.      * Map opcode names to opcode numbers. E.g., return Constants.ALOAD for "aload"
  1060.      */
  1061.     public static short searchOpcode(String name) {
  1062.         name = name.toLowerCase(Locale.ENGLISH);
  1063.         for (short i = 0; i < Const.OPCODE_NAMES_LENGTH; i++) {
  1064.             if (Const.getOpcodeName(i).equals(name)) {
  1065.                 return i;
  1066.             }
  1067.         }
  1068.         return -1;
  1069.     }

  1070.     /**
  1071.      * @return 'flag' with bit 'i' set to 1
  1072.      */
  1073.     public static int setBit(final int flag, final int i) {
  1074.         return flag | pow2(i);
  1075.     }

  1076.     /**
  1077.      * Converts a signature to a string with all class names compacted. Class, Method and Type signatures are supported.
  1078.      * Enum and Interface signatures are not supported.
  1079.      *
  1080.      * @param signature signature to convert
  1081.      * @return String containg human readable signature
  1082.      */
  1083.     public static String signatureToString(final String signature) {
  1084.         return signatureToString(signature, true);
  1085.     }

  1086.     /**
  1087.      * Converts a signature to a string. Class, Method and Type signatures are supported. Enum and Interface signatures are
  1088.      * not supported.
  1089.      *
  1090.      * @param signature signature to convert
  1091.      * @param chopit flag that determines whether chopping is executed or not
  1092.      * @return String containg human readable signature
  1093.      */
  1094.     public static String signatureToString(final String signature, final boolean chopit) {
  1095.         String type = "";
  1096.         String typeParams = "";
  1097.         int index = 0;
  1098.         if (signature.charAt(0) == '<') {
  1099.             // we have type paramters
  1100.             typeParams = typeParamTypesToString(signature, chopit);
  1101.             index += unwrap(CONSUMER_CHARS); // update position
  1102.         }
  1103.         if (signature.charAt(index) == '(') {
  1104.             // We have a Method signature.
  1105.             // add types of arguments
  1106.             type = typeParams + typeSignaturesToString(signature.substring(index), chopit, ')');
  1107.             index += unwrap(CONSUMER_CHARS); // update position
  1108.             // add return type
  1109.             type += typeSignatureToString(signature.substring(index), chopit);
  1110.             index += unwrap(CONSUMER_CHARS); // update position
  1111.             // ignore any throws information in the signature
  1112.             return type;
  1113.         }
  1114.         // Could be Class or Type...
  1115.         type = typeSignatureToString(signature.substring(index), chopit);
  1116.         index += unwrap(CONSUMER_CHARS); // update position
  1117.         if (typeParams.isEmpty() && index == signature.length()) {
  1118.             // We have a Type signature.
  1119.             return type;
  1120.         }
  1121.         // We have a Class signature.
  1122.         final StringBuilder typeClass = new StringBuilder(typeParams);
  1123.         typeClass.append(" extends ");
  1124.         typeClass.append(type);
  1125.         if (index < signature.length()) {
  1126.             typeClass.append(" implements ");
  1127.             typeClass.append(typeSignatureToString(signature.substring(index), chopit));
  1128.             index += unwrap(CONSUMER_CHARS); // update position
  1129.         }
  1130.         while (index < signature.length()) {
  1131.             typeClass.append(", ");
  1132.             typeClass.append(typeSignatureToString(signature.substring(index), chopit));
  1133.             index += unwrap(CONSUMER_CHARS); // update position
  1134.         }
  1135.         return typeClass.toString();
  1136.     }

  1137.     /**
  1138.      * Convert bytes into hexadecimal string
  1139.      *
  1140.      * @param bytes an array of bytes to convert to hexadecimal
  1141.      *
  1142.      * @return bytes as hexadecimal string, e.g. 00 fa 12 ...
  1143.      */
  1144.     public static String toHexString(final byte[] bytes) {
  1145.         final StringBuilder buf = new StringBuilder();
  1146.         for (int i = 0; i < bytes.length; i++) {
  1147.             final short b = byteToShort(bytes[i]);
  1148.             final String hex = Integer.toHexString(b);
  1149.             if (b < 0x10) {
  1150.                 buf.append('0');
  1151.             }
  1152.             buf.append(hex);
  1153.             if (i < bytes.length - 1) {
  1154.                 buf.append(' ');
  1155.             }
  1156.         }
  1157.         return buf.toString();
  1158.     }

  1159.     /**
  1160.      * Return type of method signature as a byte value as defined in <em>Constants</em>
  1161.      *
  1162.      * @param signature in format described above
  1163.      * @return type of method signature
  1164.      * @see Const
  1165.      *
  1166.      * @throws ClassFormatException if signature is not a method signature
  1167.      */
  1168.     public static byte typeOfMethodSignature(final String signature) throws ClassFormatException {
  1169.         int index;
  1170.         try {
  1171.             if (signature.charAt(0) != '(') {
  1172.                 throw new InvalidMethodSignatureException(signature);
  1173.             }
  1174.             index = signature.lastIndexOf(')') + 1;
  1175.             return typeOfSignature(signature.substring(index));
  1176.         } catch (final StringIndexOutOfBoundsException e) {
  1177.             throw new InvalidMethodSignatureException(signature, e);
  1178.         }
  1179.     }

  1180.     /**
  1181.      * Return type of signature as a byte value as defined in <em>Constants</em>
  1182.      *
  1183.      * @param signature in format described above
  1184.      * @return type of signature
  1185.      * @see Const
  1186.      *
  1187.      * @throws ClassFormatException if signature isn't a known type
  1188.      */
  1189.     public static byte typeOfSignature(final String signature) throws ClassFormatException {
  1190.         try {
  1191.             switch (signature.charAt(0)) {
  1192.             case 'B':
  1193.                 return Const.T_BYTE;
  1194.             case 'C':
  1195.                 return Const.T_CHAR;
  1196.             case 'D':
  1197.                 return Const.T_DOUBLE;
  1198.             case 'F':
  1199.                 return Const.T_FLOAT;
  1200.             case 'I':
  1201.                 return Const.T_INT;
  1202.             case 'J':
  1203.                 return Const.T_LONG;
  1204.             case 'L':
  1205.             case 'T':
  1206.                 return Const.T_REFERENCE;
  1207.             case '[':
  1208.                 return Const.T_ARRAY;
  1209.             case 'V':
  1210.                 return Const.T_VOID;
  1211.             case 'Z':
  1212.                 return Const.T_BOOLEAN;
  1213.             case 'S':
  1214.                 return Const.T_SHORT;
  1215.             case '!':
  1216.             case '+':
  1217.             case '*':
  1218.                 return typeOfSignature(signature.substring(1));
  1219.             default:
  1220.                 throw new InvalidMethodSignatureException(signature);
  1221.             }
  1222.         } catch (final StringIndexOutOfBoundsException e) {
  1223.             throw new InvalidMethodSignatureException(signature, e);
  1224.         }
  1225.     }

  1226.     /**
  1227.      * Converts a type parameter list signature to a string.
  1228.      *
  1229.      * @param signature signature to convert
  1230.      * @param chopit flag that determines whether chopping is executed or not
  1231.      * @return String containg human readable signature
  1232.      */
  1233.     private static String typeParamTypesToString(final String signature, final boolean chopit) {
  1234.         // The first character is guranteed to be '<'
  1235.         final StringBuilder typeParams = new StringBuilder("<");
  1236.         int index = 1; // skip the '<'
  1237.         // get the first TypeParameter
  1238.         typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
  1239.         index += unwrap(CONSUMER_CHARS); // update position
  1240.         // are there more TypeParameters?
  1241.         while (signature.charAt(index) != '>') {
  1242.             typeParams.append(", ");
  1243.             typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
  1244.             index += unwrap(CONSUMER_CHARS); // update position
  1245.         }
  1246.         wrap(CONSUMER_CHARS, index + 1); // account for the '>' char
  1247.         return typeParams.append(">").toString();
  1248.     }

  1249.     /**
  1250.      * Converts a type parameter signature to a string.
  1251.      *
  1252.      * @param signature signature to convert
  1253.      * @param chopit flag that determines whether chopping is executed or not
  1254.      * @return String containg human readable signature
  1255.      */
  1256.     private static String typeParamTypeToString(final String signature, final boolean chopit) {
  1257.         int index = signature.indexOf(':');
  1258.         if (index <= 0) {
  1259.             throw new ClassFormatException("Invalid type parameter signature: " + signature);
  1260.         }
  1261.         // get the TypeParameter identifier
  1262.         final StringBuilder typeParam = new StringBuilder(signature.substring(0, index));
  1263.         index++; // account for the ':'
  1264.         if (signature.charAt(index) != ':') {
  1265.             // we have a class bound
  1266.             typeParam.append(" extends ");
  1267.             typeParam.append(typeSignatureToString(signature.substring(index), chopit));
  1268.             index += unwrap(CONSUMER_CHARS); // update position
  1269.         }
  1270.         // look for interface bounds
  1271.         while (signature.charAt(index) == ':') {
  1272.             index++; // skip over the ':'
  1273.             typeParam.append(" & ");
  1274.             typeParam.append(typeSignatureToString(signature.substring(index), chopit));
  1275.             index += unwrap(CONSUMER_CHARS); // update position
  1276.         }
  1277.         wrap(CONSUMER_CHARS, index);
  1278.         return typeParam.toString();
  1279.     }

  1280.     /**
  1281.      * Converts a list of type signatures to a string.
  1282.      *
  1283.      * @param signature signature to convert
  1284.      * @param chopit flag that determines whether chopping is executed or not
  1285.      * @param term character indicating the end of the list
  1286.      * @return String containg human readable signature
  1287.      */
  1288.     private static String typeSignaturesToString(final String signature, final boolean chopit, final char term) {
  1289.         // The first character will be an 'open' that matches the 'close' contained in term.
  1290.         final StringBuilder typeList = new StringBuilder(signature.substring(0, 1));
  1291.         int index = 1; // skip the 'open' character
  1292.         // get the first Type in the list
  1293.         if (signature.charAt(index) != term) {
  1294.             typeList.append(typeSignatureToString(signature.substring(index), chopit));
  1295.             index += unwrap(CONSUMER_CHARS); // update position
  1296.         }
  1297.         // are there more types in the list?
  1298.         while (signature.charAt(index) != term) {
  1299.             typeList.append(", ");
  1300.             typeList.append(typeSignatureToString(signature.substring(index), chopit));
  1301.             index += unwrap(CONSUMER_CHARS); // update position
  1302.         }
  1303.         wrap(CONSUMER_CHARS, index + 1); // account for the term char
  1304.         return typeList.append(term).toString();
  1305.     }

  1306.     /**
  1307.      *
  1308.      * This method converts a type signature string into a Java type declaration such as 'String[]' and throws a
  1309.      * 'ClassFormatException' when the parsed type is invalid.
  1310.      *
  1311.      * @param signature type signature
  1312.      * @param chopit flag that determines whether chopping is executed or not
  1313.      * @return string containing human readable type signature
  1314.      * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
  1315.      * @since 6.4.0
  1316.      */
  1317.     public static String typeSignatureToString(final String signature, final boolean chopit) throws ClassFormatException {
  1318.         // corrected concurrent private static field acess
  1319.         wrap(CONSUMER_CHARS, 1); // This is the default, read just one char like 'B'
  1320.         try {
  1321.             switch (signature.charAt(0)) {
  1322.             case 'B':
  1323.                 return "byte";
  1324.             case 'C':
  1325.                 return "char";
  1326.             case 'D':
  1327.                 return "double";
  1328.             case 'F':
  1329.                 return "float";
  1330.             case 'I':
  1331.                 return "int";
  1332.             case 'J':
  1333.                 return "long";
  1334.             case 'T': { // TypeVariableSignature
  1335.                 final int index = signature.indexOf(';'); // Look for closing ';'
  1336.                 if (index < 0) {
  1337.                     throw new ClassFormatException("Invalid type variable signature: " + signature);
  1338.                 }
  1339.                 // corrected concurrent private static field acess
  1340.                 wrap(CONSUMER_CHARS, index + 1); // "Tblabla;" 'T' and ';' are removed
  1341.                 return compactClassName(signature.substring(1, index), chopit);
  1342.             }
  1343.             case 'L': { // Full class name
  1344.                 // should this be a while loop? can there be more than
  1345.                 // one generic clause? (markro)
  1346.                 int fromIndex = signature.indexOf('<'); // generic type?
  1347.                 if (fromIndex < 0) {
  1348.                     fromIndex = 0;
  1349.                 } else {
  1350.                     fromIndex = signature.indexOf('>', fromIndex);
  1351.                     if (fromIndex < 0) {
  1352.                         throw new ClassFormatException("Invalid signature: " + signature);
  1353.                     }
  1354.                 }
  1355.                 final int index = signature.indexOf(';', fromIndex); // Look for closing ';'
  1356.                 if (index < 0) {
  1357.                     throw new ClassFormatException("Invalid signature: " + signature);
  1358.                 }

  1359.                 // check to see if there are any TypeArguments
  1360.                 final int bracketIndex = signature.substring(0, index).indexOf('<');
  1361.                 if (bracketIndex < 0) {
  1362.                     // just a class identifier
  1363.                     wrap(CONSUMER_CHARS, index + 1); // "Lblabla;" 'L' and ';' are removed
  1364.                     return compactClassName(signature.substring(1, index), chopit);
  1365.                 }
  1366.                 // but make sure we are not looking past the end of the current item
  1367.                 fromIndex = signature.indexOf(';');
  1368.                 if (fromIndex < 0) {
  1369.                     throw new ClassFormatException("Invalid signature: " + signature);
  1370.                 }
  1371.                 if (fromIndex < bracketIndex) {
  1372.                     // just a class identifier
  1373.                     wrap(CONSUMER_CHARS, fromIndex + 1); // "Lblabla;" 'L' and ';' are removed
  1374.                     return compactClassName(signature.substring(1, fromIndex), chopit);
  1375.                 }

  1376.                 // we have TypeArguments; build up partial result
  1377.                 // as we recurse for each TypeArgument
  1378.                 final StringBuilder type = new StringBuilder(compactClassName(signature.substring(1, bracketIndex), chopit)).append("<");
  1379.                 int consumedChars = bracketIndex + 1; // Shadows global var

  1380.                 // check for wildcards
  1381.                 if (signature.charAt(consumedChars) == '+') {
  1382.                     type.append("? extends ");
  1383.                     consumedChars++;
  1384.                 } else if (signature.charAt(consumedChars) == '-') {
  1385.                     type.append("? super ");
  1386.                     consumedChars++;
  1387.                 }

  1388.                 // get the first TypeArgument
  1389.                 if (signature.charAt(consumedChars) == '*') {
  1390.                     type.append("?");
  1391.                     consumedChars++;
  1392.                 } else {
  1393.                     type.append(typeSignatureToString(signature.substring(consumedChars), chopit));
  1394.                     // update our consumed count by the number of characters the for type argument
  1395.                     consumedChars = unwrap(CONSUMER_CHARS) + consumedChars;
  1396.                     wrap(CONSUMER_CHARS, consumedChars);
  1397.                 }

  1398.                 // are there more TypeArguments?
  1399.                 while (signature.charAt(consumedChars) != '>') {
  1400.                     type.append(", ");
  1401.                     // check for wildcards
  1402.                     if (signature.charAt(consumedChars) == '+') {
  1403.                         type.append("? extends ");
  1404.                         consumedChars++;
  1405.                     } else if (signature.charAt(consumedChars) == '-') {
  1406.                         type.append("? super ");
  1407.                         consumedChars++;
  1408.                     }
  1409.                     if (signature.charAt(consumedChars) == '*') {
  1410.                         type.append("?");
  1411.                         consumedChars++;
  1412.                     } else {
  1413.                         type.append(typeSignatureToString(signature.substring(consumedChars), chopit));
  1414.                         // update our consumed count by the number of characters the for type argument
  1415.                         consumedChars = unwrap(CONSUMER_CHARS) + consumedChars;
  1416.                         wrap(CONSUMER_CHARS, consumedChars);
  1417.                     }
  1418.                 }

  1419.                 // process the closing ">"
  1420.                 consumedChars++;
  1421.                 type.append(">");

  1422.                 if (signature.charAt(consumedChars) == '.') {
  1423.                     // we have a ClassTypeSignatureSuffix
  1424.                     type.append(".");
  1425.                     // convert SimpleClassTypeSignature to fake ClassTypeSignature
  1426.                     // and then recurse to parse it
  1427.                     type.append(typeSignatureToString("L" + signature.substring(consumedChars + 1), chopit));
  1428.                     // update our consumed count by the number of characters the for type argument
  1429.                     // note that this count includes the "L" we added, but that is ok
  1430.                     // as it accounts for the "." we didn't consume
  1431.                     consumedChars = unwrap(CONSUMER_CHARS) + consumedChars;
  1432.                     wrap(CONSUMER_CHARS, consumedChars);
  1433.                     return type.toString();
  1434.                 }
  1435.                 if (signature.charAt(consumedChars) != ';') {
  1436.                     throw new ClassFormatException("Invalid signature: " + signature);
  1437.                 }
  1438.                 wrap(CONSUMER_CHARS, consumedChars + 1); // remove final ";"
  1439.                 return type.toString();
  1440.             }
  1441.             case 'S':
  1442.                 return "short";
  1443.             case 'Z':
  1444.                 return "boolean";
  1445.             case '[': { // Array declaration
  1446.                 int n;
  1447.                 StringBuilder brackets;
  1448.                 String type;
  1449.                 int consumedChars; // Shadows global var
  1450.                 brackets = new StringBuilder(); // Accumulate []'s
  1451.                 // Count opening brackets and look for optional size argument
  1452.                 for (n = 0; signature.charAt(n) == '['; n++) {
  1453.                     brackets.append("[]");
  1454.                 }
  1455.                 consumedChars = n; // Remember value
  1456.                 // The rest of the string denotes a '<field_type>'
  1457.                 type = typeSignatureToString(signature.substring(n), chopit);
  1458.                 // corrected concurrent private static field acess
  1459.                 // consumed_chars += consumed_chars; is replaced by:
  1460.                 final int temp = unwrap(CONSUMER_CHARS) + consumedChars;
  1461.                 wrap(CONSUMER_CHARS, temp);
  1462.                 return type + brackets.toString();
  1463.             }
  1464.             case 'V':
  1465.                 return "void";
  1466.             default:
  1467.                 throw new ClassFormatException("Invalid signature: '" + signature + "'");
  1468.             }
  1469.         } catch (final StringIndexOutOfBoundsException e) { // Should never occur
  1470.             throw new ClassFormatException("Invalid signature: " + signature, e);
  1471.         }
  1472.     }

  1473.     private static int unwrap(final ThreadLocal<Integer> tl) {
  1474.         return tl.get().intValue();
  1475.     }

  1476.     private static void wrap(final ThreadLocal<Integer> tl, final int value) {
  1477.         tl.set(Integer.valueOf(value));
  1478.     }

  1479. }