    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 *  Unless required by applicable law or agreed to in writing, software
    012 *  distributed under the License is distributed on an "AS IS" BASIS,
    013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 *  See the License for the specific language governing permissions and
    015 *  limitations under the License.
    016 */
    017
    018package org.apache.bcel.classfile;
    019
    020import java.io.ByteArrayInputStream;
    021import java.io.ByteArrayOutputStream;
    022import java.io.CharArrayReader;
    023import java.io.CharArrayWriter;
    024import java.io.FilterReader;
    025import java.io.FilterWriter;
    026import java.io.IOException;
    027import java.io.PrintStream;
    028import java.io.PrintWriter;
    029import java.io.Reader;
    030import java.io.Writer;
    031import java.util.ArrayList;
    032import java.util.Arrays;
    033import java.util.List;
    034import java.util.Locale;
    035import java.util.zip.GZIPInputStream;
    036import java.util.zip.GZIPOutputStream;
    037
    038import org.apache.bcel.Const;
    039import org.apache.bcel.util.ByteSequence;
    040import org.apache.commons.lang3.ArrayUtils;
    041
    042/**
    043 * Utility functions that do not really belong to any class in particular.
    044 */
    045// @since 6.0 methods are no longer final
    046public abstract class Utility {
    047
    048    /**
    049     * Decode characters into bytes. Used by <a href="Utility.html#decode(java.lang.String, boolean)">decode()</a>
    050     */
    051    private static final class JavaReader extends FilterReader {
    052
    053        public JavaReader(final Reader in) {
    054            super(in);
    055        }
    056
    057        @Override
    058        public int read() throws IOException {
    059            final int b = in.read();
    060            if (b != ESCAPE_CHAR) {
    061                return b;
    062            }
    063            final int i = in.read();
    064            if (i < 0) {
    065                return -1;
    066            }
    067            if (i >= '0' && i <= '9' || i >= 'a' && i <= 'f') { // Normal escape
    068                final int j = in.read();
    069                if (j < 0) {
    070                    return -1;
    071                }
    072                final char[] tmp = {(char) i, (char) j};
    073                return Integer.parseInt(new String(tmp), 16);
    074            }
    075            return MAP_CHAR[i];
    076        }
    077
    078        @Override
    079        public int read(final char[] cbuf, final int off, final int len) throws IOException {
    080            for (int i = 0; i < len; i++) {
    081                cbuf[off + i] = (char) read();
    082            }
    083            return len;
    084        }
    085    }
    086
    087    /**
    088     * Encode bytes into valid Java identifier characters. Used by
    089     * <a href="Utility.html#encode(byte[], boolean)">encode()</a>
    090     */
    091    private static final class JavaWriter extends FilterWriter {
    092
    093        public JavaWriter(final Writer out) {
    094            super(out);
    095        }
    096
    097        @Override
    098        public void write(final char[] cbuf, final int off, final int len) throws IOException {
    099            for (int i = 0; i < len; i++) {
    100                write(cbuf[off + i]);
    101            }
    102        }
    103
    104        @Override
    105        public void write(final int b) throws IOException {
    106            if (isJavaIdentifierPart((char) b) && b != ESCAPE_CHAR) {
    107                out.write(b);
    108            } else {
    109                out.write(ESCAPE_CHAR); // Escape character
    110                // Special escape
    111                if (b >= 0 && b < FREE_CHARS) {
    112                    out.write(CHAR_MAP[b]);
    113                } else { // Normal escape
    114                    final char[] tmp = Integer.toHexString(b).toCharArray();
    115                    if (tmp.length == 1) {
    116                        out.write('0');
    117                        out.write(tmp[0]);
    118                    } else {
    119                        out.write(tmp[0]);
    120                        out.write(tmp[1]);
    121                    }
    122                }
    123            }
    124        }
    125
    126        @Override
    127        public void write(final String str, final int off, final int len) throws IOException {
    128            write(str.toCharArray(), off, len);
    129        }
    130    }
    131
    132    /*
    133     * How many chars have been consumed during parsing in typeSignatureToString(). Read by methodSignatureToString(). Set
    134     * by side effect, but only internally.
    135     */
    136    private static final ThreadLocal<Integer> CONSUMER_CHARS = ThreadLocal.withInitial(() -> Integer.valueOf(0));
    137
    138    /*
    139     * The 'WIDE' instruction is used in the byte code to allow 16-bit wide indices for local variables. This opcode
    140     * precedes an 'ILOAD', e.g.. The opcode immediately following takes an extra byte which is combined with the following
    141     * byte to form a 16-bit value.
    142     */
    143    private static boolean wide;
    144
    145    // A-Z, g-z, _, $
    146    private static final int FREE_CHARS = 48;
    147
    148    private static final int[] CHAR_MAP = new int[FREE_CHARS];
    149
    150    private static final int[] MAP_CHAR = new int[256]; // Reverse map
    151
    152    private static final char ESCAPE_CHAR = '$';
    153
    154    static {
    155        int j = 0;
    156        for (int i = 'A'; i <= 'Z'; i++) {
    157            CHAR_MAP[j] = i;
    158            MAP_CHAR[i] = j;
    159            j++;
    160        }
    161        for (int i = 'g'; i <= 'z'; i++) {
    162            CHAR_MAP[j] = i;
    163            MAP_CHAR[i] = j;
    164            j++;
    165        }
    166        CHAR_MAP[j] = '$';
    167        MAP_CHAR['$'] = j;
    168        j++;
    169        CHAR_MAP[j] = '_';
    170        MAP_CHAR['_'] = j;
    171    }
    172
    173    /**
    174     * Convert bit field of flags into string such as 'static final'.
    175     *
    176     * @param accessFlags Access flags
    177     * @return String representation of flags
    178     */
    179    public static String accessToString(final int accessFlags) {
    180        return accessToString(accessFlags, false);
    181    }
    182
    183    /**
    184     * Convert bit field of flags into string such as 'static final'.
    185     *
    186     * Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized".
    187     * This is because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'.
    188     *
    189     * @param accessFlags Access flags
    190     * @param forClass access flags are for class qualifiers ?
    191     * @return String representation of flags
    192     */
    193    public static String accessToString(final int accessFlags, final boolean forClass) {
    194        final StringBuilder buf = new StringBuilder();
    195        int p = 0;
    196        for (int i = 0; p < Const.MAX_ACC_FLAG_I; i++) { // Loop through known flags
    197            p = pow2(i);
    198            if ((accessFlags & p) != 0) {
    199                /*
    200                 * Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized".
    201                 * This is because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'.
    202                 */
    203                if (forClass && (p == Const.ACC_SUPER || p == Const.ACC_INTERFACE)) {
    204                    continue;
    205                }
    206                buf.append(Const.getAccessName(i)).append(" ");
    207            }
    208        }
    209        return buf.toString().trim();
    210    }
    211
    212    /**
    213     * Convert (signed) byte to (unsigned) short value, i.e., all negative values become positive.
    214     */
    215    private static short byteToShort(final byte b) {
    216        return b < 0 ? (short) (256 + b) : (short) b;
    217    }
    218
    219    /**
    220     * @param accessFlags the class flags
    221     *
    222     * @return "class" or "interface", depending on the ACC_INTERFACE flag
    223     */
    224    public static String classOrInterface(final int accessFlags) {
    225        return (accessFlags & Const.ACC_INTERFACE) != 0 ? "interface" : "class";
    226    }
    227
    228    /**
    229     * @return 'flag' with bit 'i' set to 0
    230     */
    231    public static int clearBit(final int flag, final int i) {
    232        final int bit = pow2(i);
    233        return (flag & bit) == 0 ? flag : flag ^ bit;
    234    }
    235
    236    public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length) {
    237        return codeToString(code, constantPool, index, length, true);
    238    }
    239
    240    /**
    241     * Disassemble a byte array of JVM byte codes starting from code line 'index' and return the disassembled string
    242     * representation. Decode only 'num' opcodes (including their operands), use -1 if you want to decompile everything.
    243     *
    244     * @param code byte code array
    245     * @param constantPool Array of constants
    246     * @param index offset in 'code' array <EM>(number of opcodes, not bytes!)</EM>
    247     * @param length number of opcodes to decompile, -1 for all
    248     * @param verbose be verbose, e.g. print constant pool index
    249     * @return String representation of byte codes
    250     */
    251    public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length, final boolean verbose) {
    252        final StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient // CHECKSTYLE IGNORE MagicNumber
    253        try (ByteSequence stream = new ByteSequence(code)) {
    254            for (int i = 0; i < index; i++) {
    255                codeToString(stream, constantPool, verbose);
    256            }
    257            for (int i = 0; stream.available() > 0; i++) {
    258                if (length < 0 || i < length) {
    259                    final String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
    260                    buf.append(indices).append(codeToString(stream, constantPool, verbose)).append('\n');
    261                }
    262            }
    263        } catch (final IOException e) {
    264            throw new ClassFormatException("Byte code error: " + buf.toString(), e);
    265        }
    266        return buf.toString();
    267    }
    268
    269    public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool) throws IOException {
    270        return codeToString(bytes, constantPool, true);
    271    }
    272
    273    /**
    274     * Disassemble a stream of byte codes and return the string representation.
    275     *
    276     * @param bytes stream of bytes
    277     * @param constantPool Array of constants
    278     * @param verbose be verbose, e.g. print constant pool index
    279     * @return String representation of byte code
    280     *
    281     * @throws IOException if a failure from reading from the bytes argument occurs
    282     */
    283    public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool, final boolean verbose) throws IOException {
    284        final short opcode = (short) bytes.readUnsignedByte();
    285        int defaultOffset = 0;
    286        int low;
    287        int high;
    288        int npairs;
    289        int index;
    290        int vindex;
    291        int constant;
    292        int[] match;
    293        int[] jumpTable;
    294        int noPadBytes = 0;
    295        int offset;
    296        final StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode));
    297        /*
    298         * Special case: Skip (0-3) padding bytes, i.e., the following bytes are 4-byte-aligned
    299         */
    300        if (opcode == Const.TABLESWITCH || opcode == Const.LOOKUPSWITCH) {
    301            final int remainder = bytes.getIndex() % 4;
    302            noPadBytes = remainder == 0 ? 0 : 4 - remainder;
    303            for (int i = 0; i < noPadBytes; i++) {
    304                byte b;
    305                if ((b = bytes.readByte()) != 0) {
    306                    System.err.println("Warning: Padding byte != 0 in " + Const.getOpcodeName(opcode) + ":" + b);
    307                }
    308            }
    309            // Both cases have a field default_offset in common
    310            defaultOffset = bytes.readInt();
    311        }
    312        switch (opcode) {
    313        /*
    314         * Table switch has variable length arguments.
    315         */
    316        case Const.TABLESWITCH:
    317            low = bytes.readInt();
    318            high = bytes.readInt();
    319            offset = bytes.getIndex() - 12 - noPadBytes - 1;
    320            defaultOffset += offset;
    321            buf.append("\tdefault = ").append(defaultOffset).append(", low = ").append(low).append(", high = ").append(high).append("(");
    322            jumpTable = new int[high - low + 1];
    323            for (int i = 0; i < jumpTable.length; i++) {
    324                jumpTable[i] = offset + bytes.readInt();
    325                buf.append(jumpTable[i]);
    326                if (i < jumpTable.length - 1) {
    327                    buf.append(", ");
    328                }
    329            }
    330            buf.append(")");
    331            break;
    332        /*
    333         * Lookup switch has variable length arguments.
    334         */
    335        case Const.LOOKUPSWITCH: {
    336            npairs = bytes.readInt();
    337            offset = bytes.getIndex() - 8 - noPadBytes - 1;
    338            match = new int[npairs];
    339            jumpTable = new int[npairs];
    340            defaultOffset += offset;
    341            buf.append("\tdefault = ").append(defaultOffset).append(", npairs = ").append(npairs).append(" (");
    342            for (int i = 0; i < npairs; i++) {
    343                match[i] = bytes.readInt();
    344                jumpTable[i] = offset + bytes.readInt();
    345                buf.append("(").append(match[i]).append(", ").append(jumpTable[i]).append(")");
    346                if (i < npairs - 1) {
    347                    buf.append(", ");
    348                }
    349            }
    350            buf.append(")");
    351        }
    352            break;
    353        /*
    354         * Two address bytes + offset from start of byte stream form the jump target
    355         */
    356        case Const.GOTO:
    357        case Const.IFEQ:
    358        case Const.IFGE:
    359        case Const.IFGT:
    360        case Const.IFLE:
    361        case Const.IFLT:
    362        case Const.JSR:
    363        case Const.IFNE:
    364        case Const.IFNONNULL:
    365        case Const.IFNULL:
    366        case Const.IF_ACMPEQ:
    367        case Const.IF_ACMPNE:
    368        case Const.IF_ICMPEQ:
    369        case Const.IF_ICMPGE:
    370        case Const.IF_ICMPGT:
    371        case Const.IF_ICMPLE:
    372        case Const.IF_ICMPLT:
    373        case Const.IF_ICMPNE:
    374            buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readShort());
    375            break;
    376        /*
    377         * 32-bit wide jumps
    378         */
    379        case Const.GOTO_W:
    380        case Const.JSR_W:
    381            buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readInt());
    382            break;
    383        /*
    384         * Index byte references local variable (register)
    385         */
    386        case Const.ALOAD:
    387        case Const.ASTORE:
    388        case Const.DLOAD:
    389        case Const.DSTORE:
    390        case Const.FLOAD:
    391        case Const.FSTORE:
    392        case Const.ILOAD:
    393        case Const.ISTORE:
    394        case Const.LLOAD:
    395        case Const.LSTORE:
    396        case Const.RET:
    397            if (wide) {
    398                vindex = bytes.readUnsignedShort();
    399                wide = false; // Clear flag
    400            } else {
    401                vindex = bytes.readUnsignedByte();
    402            }
    403            buf.append("\t\t%").append(vindex);
    404            break;
    405        /*
    406         * Remember wide byte which is used to form a 16-bit address in the following instruction. Relies on that the method is
    407         * called again with the following opcode.
    408         */
    409        case Const.WIDE:
    410            wide = true;
    411            buf.append("\t(wide)");
    412            break;
    413        /*
    414         * Array of basic type.
    415         */
    416        case Const.NEWARRAY:
    417            buf.append("\t\t<").append(Const.getTypeName(bytes.readByte())).append(">");
    418            break;
    419        /*
    420         * Access object/class fields.
    421         */
    422        case Const.GETFIELD:
    423        case Const.GETSTATIC:
    424        case Const.PUTFIELD:
    425        case Const.PUTSTATIC:
    426            index = bytes.readUnsignedShort();
    427            buf.append("\t\t").append(constantPool.constantToString(index, Const.CONSTANT_Fieldref)).append(verbose ? " (" + index + ")" : "");
    428            break;
    429        /*
    430         * Operands are references to classes in constant pool
    431         */
    432        case Const.NEW:
    433        case Const.CHECKCAST:
    434            buf.append("\t");
    435            index = bytes.readUnsignedShort();
    436            buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
    437            break;
    438        case Const.INSTANCEOF:
    439            index = bytes.readUnsignedShort();
    440            buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
    441            break;
    442        /*
    443         * Operands are references to methods in constant pool
    444         */
    445        case Const.INVOKESPECIAL:
    446        case Const.INVOKESTATIC:
    447            index = bytes.readUnsignedShort();
    448            final Constant c = constantPool.getConstant(index);
    449            // With Java8 operand may be either a CONSTANT_Methodref
    450            // or a CONSTANT_InterfaceMethodref. (markro)
    451            buf.append("\t").append(constantPool.constantToString(index, c.getTag())).append(verbose ? " (" + index + ")" : "");
    452            break;
    453        case Const.INVOKEVIRTUAL:
    454            index = bytes.readUnsignedShort();
    455            buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_Methodref)).append(verbose ? " (" + index + ")" : "");
    456            break;
    457        case Const.INVOKEINTERFACE:
    458            index = bytes.readUnsignedShort();
    459            final int nargs = bytes.readUnsignedByte(); // historical, redundant
    460            buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InterfaceMethodref)).append(verbose ? " (" + index + ")\t" : "")
    461                .append(nargs).append("\t").append(bytes.readUnsignedByte()); // Last byte is a reserved space
    462            break;
    463        case Const.INVOKEDYNAMIC:
    464            index = bytes.readUnsignedShort();
    465            buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InvokeDynamic)).append(verbose ? " (" + index + ")\t" : "")
    466                .append(bytes.readUnsignedByte()) // Thrid byte is a reserved space
    467                .append(bytes.readUnsignedByte()); // Last byte is a reserved space
    468            break;
    469        /*
    470         * Operands are references to items in constant pool
    471         */
    472        case Const.LDC_W:
    473        case Const.LDC2_W:
    474            index = bytes.readUnsignedShort();
    475            buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
    476                .append(verbose ? " (" + index + ")" : "");
    477            break;
    478        case Const.LDC:
    479            index = bytes.readUnsignedByte();
    480            buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
    481                .append(verbose ? " (" + index + ")" : "");
    482            break;
    483        /*
    484         * Array of references.
    485         */
    486        case Const.ANEWARRAY:
    487            index = bytes.readUnsignedShort();
    488            buf.append("\t\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">")
    489                .append(verbose ? " (" + index + ")" : "");
    490            break;
    491        /*
    492         * Multidimensional array of references.
    493         */
    494        case Const.MULTIANEWARRAY: {
    495            index = bytes.readUnsignedShort();
    496            final int dimensions = bytes.readUnsignedByte();
    497            buf.append("\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">\t").append(dimensions)
    498                .append(verbose ? " (" + index + ")" : "");
    499        }
    500            break;
    501        /*
    502         * Increment local variable.
    503         */
    504        case Const.IINC:
    505            if (wide) {
    506                vindex = bytes.readUnsignedShort();
    507                constant = bytes.readShort();
    508                wide = false;
    509            } else {
    510                vindex = bytes.readUnsignedByte();
    511                constant = bytes.readByte();
    512            }
    513            buf.append("\t\t%").append(vindex).append("\t").append(constant);
    514            break;
    515        default:
    516            if (Const.getNoOfOperands(opcode) > 0) {
    517                for (int i = 0; i < Const.getOperandTypeCount(opcode); i++) {
    518                    buf.append("\t\t");
    519                    switch (Const.getOperandType(opcode, i)) {
    520                    case Const.T_BYTE:
    521                        buf.append(bytes.readByte());
    522                        break;
    523                    case Const.T_SHORT:
    524                        buf.append(bytes.readShort());
    525                        break;
    526                    case Const.T_INT:
    527                        buf.append(bytes.readInt());
    528                        break;
    529                    default: // Never reached
    530                        throw new IllegalStateException("Unreachable default case reached!");
    531                    }
    532                }
    533            }
    534        }
    535        return buf.toString();
    536    }
    537
    538    /**
    539     * Shorten long class names, <em>java/lang/String</em> becomes <em>String</em>.
    540     *
    541     * @param str The long class name
    542     * @return Compacted class name
    543     */
    544    public static String compactClassName(final String str) {
    545        return compactClassName(str, true);
    546    }
    547
    548    /**
    549     * Shorten long class names, <em>java/lang/String</em> becomes <em>java.lang.String</em>, e.g.. If <em>chopit</em> is
    550     * <em>true</em> the prefix <em>java.lang</em> is also removed.
    551     *
    552     * @param str The long class name
    553     * @param chopit flag that determines whether chopping is executed or not
    554     * @return Compacted class name
    555     */
    556    public static String compactClassName(final String str, final boolean chopit) {
    557        return compactClassName(str, "java.lang.", chopit);
    558    }
    559
    560    /**
    561     * Shorten long class name <em>str</em>, i.e., chop off the <em>prefix</em>, if the class name starts with this string
    562     * and the flag <em>chopit</em> is true. Slashes <em>/</em> are converted to dots <em>.</em>.
    563     *
    564     * @param str The long class name
    565     * @param prefix The prefix the get rid off
    566     * @param chopit flag that determines whether chopping is executed or not
    567     * @return Compacted class name
    568     */
    569    public static String compactClassName(String str, final String prefix, final boolean chopit) {
    570        final int len = prefix.length();
    571        str = pathToPackage(str); // Is '/' on all systems, even DOS
    572        // If string starts with 'prefix' and contains no further dots
    573        if (chopit && str.startsWith(prefix) && str.substring(len).indexOf('.') == -1) {
    574            str = str.substring(len);
    575        }
    576        return str;
    577    }
    578
    579    /**
    580     * Escape all occurrences of newline chars '\n', quotes \", etc.
    581     */
    582    public static String convertString(final String label) {
    583        final char[] ch = label.toCharArray();
    584        final StringBuilder buf = new StringBuilder();
    585        for (final char element : ch) {
    586            switch (element) {
    587            case '\n':
    588                buf.append("\\n");
    589                break;
    590            case '\r':
    591                buf.append("\\r");
    592                break;
    593            case '\"':
    594                buf.append("\\\"");
    595                break;
    596            case '\'':
    597                buf.append("\\'");
    598                break;
    599            case '\\':
    600                buf.append("\\\\");
    601                break;
    602            default:
    603                buf.append(element);
    604                break;
    605            }
    606        }
    607        return buf.toString();
    608    }
    609
    610    private static int countBrackets(final String brackets) {
    611        final char[] chars = brackets.toCharArray();
    612        int count = 0;
    613        boolean open = false;
    614        for (final char c : chars) {
    615            switch (c) {
    616            case '[':
    617                if (open) {
    618                    throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
    619                }
    620                open = true;
    621                break;
    622            case ']':
    623                if (!open) {
    624                    throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
    625                }
    626                open = false;
    627                count++;
    628                break;
    629            default:
    630                // Don't care
    631                break;
    632            }
    633        }
    634        if (open) {
    635            throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
    636        }
    637        return count;
    638    }
    639
    640    /**
    641     * Decode a string back to a byte array.
    642     *
    643     * @param s the string to convert
    644     * @param uncompress use gzip to uncompress the stream of bytes
    645     *
    646     * @throws IOException if there's a gzip exception
    647     */
    648    public static byte[] decode(final String s, final boolean uncompress) throws IOException {
    649        byte[] bytes;
    650        try (JavaReader jr = new JavaReader(new CharArrayReader(s.toCharArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    651            int ch;
    652            while ((ch = jr.read()) >= 0) {
    653                bos.write(ch);
    654            }
    655            bytes = bos.toByteArray();
    656        }
    657        if (uncompress) {
    658            final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
    659            final byte[] tmp = new byte[bytes.length * 3]; // Rough estimate
    660            int count = 0;
    661            int b;
    662            while ((b = gis.read()) >= 0) {
    663                tmp[count++] = (byte) b;
    664            }
    665            bytes = Arrays.copyOf(tmp, count);
    666        }
    667        return bytes;
    668    }
    669
    670    /**
    671     * Encode byte array it into Java identifier string, i.e., a string that only contains the following characters: (a, ...
    672     * z, A, ... Z, 0, ... 9, _, $). The encoding algorithm itself is not too clever: if the current byte's ASCII value
    673     * already is a valid Java identifier part, leave it as it is. Otherwise it writes the escape character($) followed by:
    674     *
    675     * <ul>
    676     * <li>the ASCII value as a hexadecimal string, if the value is not in the range 200..247</li>
    677     * <li>a Java identifier char not used in a lowercase hexadecimal string, if the value is in the range 200..247</li>
    678     * </ul>
    679     *
    680     * <p>
    681     * This operation inflates the original byte array by roughly 40-50%
    682     * </p>
    683     *
    684     * @param bytes the byte array to convert
    685     * @param compress use gzip to minimize string
    686     *
    687     * @throws IOException if there's a gzip exception
    688     */
    689    public static String encode(byte[] bytes, final boolean compress) throws IOException {
    690        if (compress) {
    691            try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos)) {
    692                gos.write(bytes, 0, bytes.length);
    693                gos.close();
    694                bytes = baos.toByteArray();
    695            }
    696        }
    697        final CharArrayWriter caw = new CharArrayWriter();
    698        try (JavaWriter jw = new JavaWriter(caw)) {
    699            for (final byte b : bytes) {
    700                final int in = b & 0x000000ff; // Normalize to unsigned
    701                jw.write(in);
    702            }
    703        }
    704        return caw.toString();
    705    }
    706
    707    /**
    708     * Fillup char with up to length characters with char 'fill' and justify it left or right.
    709     *
    710     * @param str string to format
    711     * @param length length of desired string
    712     * @param leftJustify format left or right
    713     * @param fill fill character
    714     * @return formatted string
    715     */
    716    public static String fillup(final String str, final int length, final boolean leftJustify, final char fill) {
    717        final int len = length - str.length();
    718        final char[] buf = new char[Math.max(len, 0)];
    719        Arrays.fill(buf, fill);
    720        if (leftJustify) {
    721            return str + new String(buf);
    722        }
    723        return new String(buf) + str;
    724    }
    725
    726    /**
    727     * Return a string for an integer justified left or right and filled up with 'fill' characters if necessary.
    728     *
    729     * @param i integer to format
    730     * @param length length of desired string
    731     * @param leftJustify format left or right
    732     * @param fill fill character
    733     * @return formatted int
    734     */
    735    public static String format(final int i, final int length, final boolean leftJustify, final char fill) {
    736        return fillup(Integer.toString(i), length, leftJustify, fill);
    737    }
    738
    739    /**
    740     * WARNING:
    741     *
    742     * There is some nomenclature confusion through much of the BCEL code base with respect to the terms Descriptor and
    743     * Signature. For the offical definitions see:
    744     *
    745     * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3"> Descriptors in The Java
    746     *      Virtual Machine Specification</a>
    747     *
    748     * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.9.1"> Signatures in The Java
    749     *      Virtual Machine Specification</a>
    750     *
    751     *      In brief, a descriptor is a string representing the type of a field or method. Signatures are similar, but more
    752     *      complex. Signatures are used to encode declarations written in the Java programming language that use types
    753     *      outside the type system of the Java Virtual Machine. They are used to describe the type of any class, interface,
    754     *      constructor, method or field whose declaration uses type variables or parameterized types.
    755     *
    756     *      To parse a descriptor, call typeSignatureToString. To parse a signature, call signatureToString.
    757     *
    758     *      Note that if the signature string is a single, non-generic item, the call to signatureToString reduces to a call
    759     *      to typeSignatureToString. Also note, that if you only wish to parse the first item in a longer signature string,
    760     *      you should call typeSignatureToString directly.
    761     */
    762
    763    /**
    764     * Parse Java type such as "char", or "java.lang.String[]" and return the signature in byte code format, e.g. "C" or
    765     * "[Ljava/lang/String;" respectively.
    766     *
    767     * @param type Java type
    768     * @return byte code signature
    769     */
    770    public static String getSignature(String type) {
    771        final StringBuilder buf = new StringBuilder();
    772        final char[] chars = type.toCharArray();
    773        boolean charFound = false;
    774        boolean delim = false;
    775        int index = -1;
    776        loop: for (int i = 0; i < chars.length; i++) {
    777            switch (chars[i]) {
    778            case ' ':
    779            case '\t':
    780            case '\n':
    781            case '\r':
    782            case '\f':
    783                if (charFound) {
    784                    delim = true;
    785                }
    786                break;
    787            case '[':
    788                if (!charFound) {
    789                    throw new IllegalArgumentException("Illegal type: " + type);
    790                }
    791                index = i;
    792                break loop;
    793            default:
    794                charFound = true;
    795                if (!delim) {
    796                    buf.append(chars[i]);
    797                }
    798            }
    799        }
    800        int brackets = 0;
    801        if (index > 0) {
    802            brackets = countBrackets(type.substring(index));
    803        }
    804        type = buf.toString();
    805        buf.setLength(0);
    806        for (int i = 0; i < brackets; i++) {
    807            buf.append('[');
    808        }
    809        boolean found = false;
    810        for (int i = Const.T_BOOLEAN; i <= Const.T_VOID && !found; i++) {
    811            if (Const.getTypeName(i).equals(type)) {
    812                found = true;
    813                buf.append(Const.getShortTypeName(i));
    814            }
    815        }
    816        if (!found) {
    817            buf.append('L').append(packageToPath(type)).append(';');
    818        }
    819        return buf.toString();
    820    }
    821
    822    /**
    823     * @param ch the character to test if it's part of an identifier
    824     *
    825     * @return true, if character is one of (a, ... z, A, ... Z, 0, ... 9, _)
    826     */
    827    public static boolean isJavaIdentifierPart(final char ch) {
    828        return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '_';
    829    }
    830
    831    /**
    832     * @return true, if bit 'i' in 'flag' is set
    833     */
    834    public static boolean isSet(final int flag, final int i) {
    835        return (flag & pow2(i)) != 0;
    836    }
    837
    838    /**
    839     * Converts argument list portion of method signature to string with all class names compacted.
    840     *
    841     * @param signature Method signature
    842     * @return String Array of argument types
    843     * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
    844     */
    845    public static String[] methodSignatureArgumentTypes(final String signature) throws ClassFormatException {
    846        return methodSignatureArgumentTypes(signature, true);
    847    }
    848
    849    /**
    850     * Converts argument list portion of method signature to string.
    851     *
    852     * @param signature Method signature
    853     * @param chopit flag that determines whether chopping is executed or not
    854     * @return String Array of argument types
    855     * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
    856     */
    857    public static String[] methodSignatureArgumentTypes(final String signature, final boolean chopit) throws ClassFormatException {
    858        final List<String> vec = new ArrayList<>();
    859        int index;
    860        try {
    861            // Skip any type arguments to read argument declarations between '(' and ')'
    862            index = signature.indexOf('(') + 1;
    863            if (index <= 0) {
    864                throw new InvalidMethodSignatureException(signature);
    865            }
    866            while (signature.charAt(index) != ')') {
    867                vec.add(typeSignatureToString(signature.substring(index), chopit));
    868                // corrected concurrent private static field acess
    869                index += unwrap(CONSUMER_CHARS); // update position
    870            }
    871        } catch (final StringIndexOutOfBoundsException e) { // Should never occur
    872            throw new InvalidMethodSignatureException(signature, e);
    873        }
    874        return vec.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
    875    }
    876
    877    /**
    878     * Converts return type portion of method signature to string with all class names compacted.
    879     *
    880     * @param signature Method signature
    881     * @return String representation of method return type
    882     * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
    883     */
    884    public static String methodSignatureReturnType(final String signature) throws ClassFormatException {
    885        return methodSignatureReturnType(signature, true);
    886    }
    887
    888    /**
    889     * Converts return type portion of method signature to string.
    890     *
    891     * @param signature Method signature
    892     * @param chopit flag that determines whether chopping is executed or not
    893     * @return String representation of method return type
    894     * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
    895     */
    896    public static String methodSignatureReturnType(final String signature, final boolean chopit) throws ClassFormatException {
    897        int index;
    898        String type;
    899        try {
    900            // Read return type after ')'
    901            index = signature.lastIndexOf(')') + 1;
    902            if (index <= 0) {
    903                throw new InvalidMethodSignatureException(signature);
    904            }
    905            type = typeSignatureToString(signature.substring(index), chopit);
    906        } catch (final StringIndexOutOfBoundsException e) { // Should never occur
    907            throw new InvalidMethodSignatureException(signature, e);
    908        }
    909        return type;
    910    }
    911
    912    /**
    913     * Converts method signature to string with all class names compacted.
    914     *
    915     * @param signature to convert
    916     * @param name of method
    917     * @param access flags of method
    918     * @return Human readable signature
    919     */
    920    public static String methodSignatureToString(final String signature, final String name, final String access) {
    921        return methodSignatureToString(signature, name, access, true);
    922    }
    923
    924    /**
    925     * Converts method signature to string.
    926     *
    927     * @param signature to convert
    928     * @param name of method
    929     * @param access flags of method
    930     * @param chopit flag that determines whether chopping is executed or not
    931     * @return Human readable signature
    932     */
    933    public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit) {
    934        return methodSignatureToString(signature, name, access, chopit, null);
    935    }
    936
    937    /**
    938     * This method converts a method signature string into a Java type declaration like 'void main(String[])' and throws a
    939     * 'ClassFormatException' when the parsed type is invalid.
    940     *
    941     * @param signature Method signature
    942     * @param name Method name
    943     * @param access Method access rights
    944     * @param chopit flag that determines whether chopping is executed or not
    945     * @param vars the LocalVariableTable for the method
    946     * @return Java type declaration
    947     * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
    948     */
    949    public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit,
    950        final LocalVariableTable vars) throws ClassFormatException {
    951        final StringBuilder buf = new StringBuilder("(");
    952        String type;
    953        int index;
    954        int varIndex = access.contains("static") ? 0 : 1;
    955        try {
    956            // Skip any type arguments to read argument declarations between '(' and ')'
    957            index = signature.indexOf('(') + 1;
    958            if (index <= 0) {
    959                throw new InvalidMethodSignatureException(signature);
    960            }
    961            while (signature.charAt(index) != ')') {
    962                final String paramType = typeSignatureToString(signature.substring(index), chopit);
    963                buf.append(paramType);
    964                if (vars != null) {
    965                    final LocalVariable l = vars.getLocalVariable(varIndex, 0);
    966                    if (l != null) {
    967                        buf.append(" ").append(l.getName());
    968                    }
    969                } else {
    970                    buf.append(" arg").append(varIndex);
    971                }
    972                if ("double".equals(paramType) || "long".equals(paramType)) {
    973                    varIndex += 2;
    974                } else {
    975                    varIndex++;
    976                }
    977                buf.append(", ");
    978                // corrected concurrent private static field acess
    979                index += unwrap(CONSUMER_CHARS); // update position
    980            }
    981            index++; // update position
    982            // Read return type after ')'
    983            type = typeSignatureToString(signature.substring(index), chopit);
    984        } catch (final StringIndexOutOfBoundsException e) { // Should never occur
    985            throw new InvalidMethodSignatureException(signature, e);
    986        }
    987        // ignore any throws information in the signature
    988        if (buf.length() > 1) {
    989            buf.setLength(buf.length() - 2);
    990        }
    991        buf.append(")");
    992        return access + (!access.isEmpty() ? " " : "") + // May be an empty string
    993            type + " " + name + buf.toString();
    994    }
    995
    996    /**
    997     * Converts string containing the method return and argument types to a byte code method signature.
    998     *
    999     * @param ret Return type of method
    1000     * @param argv Types of method arguments
    1001     * @return Byte code representation of method signature
    1002     *
    1003     * @throws ClassFormatException if the signature is for Void
    1004     */
    1005    public static String methodTypeToSignature(final String ret, final String[] argv) throws ClassFormatException {
    1006        final StringBuilder buf = new StringBuilder("(");
    1007        String str;
    1008        if (argv != null) {
    1009            for (final String element : argv) {
    1010                str = getSignature(element);
    1011                if (str.endsWith("V")) {
    1012                    throw new ClassFormatException("Invalid type: " + element);
    1013                }
    1014                buf.append(str);
    1015            }
    1016        }
    1017        str = getSignature(ret);
    1018        buf.append(")").append(str);
    1019        return buf.toString();
    1020    }
    1021
    1022    /**
    1023     * Converts '.'s to '/'s.
    1024     *
    1025     * @param name Source
    1026     * @return converted value
    1027     * @since 6.7.0
    1028     */
    1029    public static String packageToPath(final String name) {
    1030        return name.replace('.', '/');
    1031    }
    1032
    1033    /**
    1034     * Converts a path to a package name.
    1035     *
    1036     * @param str the source path.
    1037     * @return a package name.
    1038     * @since 6.6.0
    1039     */
    1040    public static String pathToPackage(final String str) {
    1041        return str.replace('/', '.');
    1042    }
    1043
    1044    private static int pow2(final int n) {
    1045        return 1 << n;
    1046    }
    1047
    1048    public static String printArray(final Object[] obj) {
    1049        return printArray(obj, true);
    1050    }
    1051
    1052    public static String printArray(final Object[] obj, final boolean braces) {
    1053        return printArray(obj, braces, false);
    1054    }
    1055
    1056    public static String printArray(final Object[] obj, final boolean braces, final boolean quote) {
    1057        if (obj == null) {
    1058            return null;
    1059        }
    1060        final StringBuilder buf = new StringBuilder();
    1061        if (braces) {
    1062            buf.append('{');
    1063        }
    1064        for (int i = 0; i < obj.length; i++) {
    1065            if (obj[i] != null) {
    1066                buf.append(quote ? "\"" : "").append(obj[i]).append(quote ? "\"" : "");
    1067            } else {
    1068                buf.append("null");
    1069            }
    1070            if (i < obj.length - 1) {
    1071                buf.append(", ");
    1072            }
    1073        }
    1074        if (braces) {
    1075            buf.append('}');
    1076        }
    1077        return buf.toString();
    1078    }
    1079
    1080    public static void printArray(final PrintStream out, final Object[] obj) {
    1081        out.println(printArray(obj, true));
    1082    }
    1083
    1084    public static void printArray(final PrintWriter out, final Object[] obj) {
    1085        out.println(printArray(obj, true));
    1086    }
    1087
    1088    /**
    1089     * Replace all occurrences of <em>old</em> in <em>str</em> with <em>new</em>.
    1090     *
    1091     * @param str String to permute
    1092     * @param old String to be replaced
    1093     * @param new_ Replacement string
    1094     * @return new String object
    1095     */
    1096    public static String replace(String str, final String old, final String new_) {
    1097        int index;
    1098        int oldIndex;
    1099        try {
    1100            if (str.contains(old)) { // 'old' found in str
    1101                final StringBuilder buf = new StringBuilder();
    1102                oldIndex = 0; // String start offset
    1103                // While we have something to replace
    1104                while ((index = str.indexOf(old, oldIndex)) != -1) {
    1105                    buf.append(str, oldIndex, index); // append prefix
    1106                    buf.append(new_); // append replacement
    1107                    oldIndex = index + old.length(); // Skip 'old'.length chars
    1108                }
    1109                buf.append(str.substring(oldIndex)); // append rest of string
    1110                str = buf.toString();
    1111            }
    1112        } catch (final StringIndexOutOfBoundsException e) { // Should not occur
    1113            System.err.println(e);
    1114        }
    1115        return str;
    1116    }
    1117
    1118    /**
    1119     * Map opcode names to opcode numbers. E.g., return Constants.ALOAD for "aload"
    1120     */
    1121    public static short searchOpcode(String name) {
    1122        name = name.toLowerCase(Locale.ENGLISH);
    1123        for (short i = 0; i < Const.OPCODE_NAMES_LENGTH; i++) {
    1124            if (Const.getOpcodeName(i).equals(name)) {
    1125                return i;
    1126            }
    1127        }
    1128        return -1;
    1129    }
    1130
    1131    /**
    1132     * @return 'flag' with bit 'i' set to 1
    1133     */
    1134    public static int setBit(final int flag, final int i) {
    1135        return flag | pow2(i);
    1136    }
    1137
    1138    /**
    1139     * Converts a signature to a string with all class names compacted. Class, Method and Type signatures are supported.
    1140     * Enum and Interface signatures are not supported.
    1141     *
    1142     * @param signature signature to convert
    1143     * @return String containg human readable signature
    1144     */
    1145    public static String signatureToString(final String signature) {
    1146        return signatureToString(signature, true);
    1147    }
    1148
    1149    /**
    1150     * Converts a signature to a string. Class, Method and Type signatures are supported. Enum and Interface signatures are
    1151     * not supported.
    1152     *
    1153     * @param signature signature to convert
    1154     * @param chopit flag that determines whether chopping is executed or not
    1155     * @return String containg human readable signature
    1156     */
    1157    public static String signatureToString(final String signature, final boolean chopit) {
    1158        String type = "";
    1159        String typeParams = "";
    1160        int index = 0;
    1161        if (signature.charAt(0) == '<') {
    1162            // we have type paramters
    1163            typeParams = typeParamTypesToString(signature, chopit);
    1164            index += unwrap(CONSUMER_CHARS); // update position
    1165        }
    1166        if (signature.charAt(index) == '(') {
    1167            // We have a Method signature.
    1168            // add types of arguments
    1169            type = typeParams + typeSignaturesToString(signature.substring(index), chopit, ')');
    1170            index += unwrap(CONSUMER_CHARS); // update position
    1171            // add return type
    1172            type = type + typeSignatureToString(signature.substring(index), chopit);
    1173            index += unwrap(CONSUMER_CHARS); // update position
    1174            // ignore any throws information in the signature
    1175            return type;
    1176        }
    1177        // Could be Class or Type...
    1178        type = typeSignatureToString(signature.substring(index), chopit);
    1179        index += unwrap(CONSUMER_CHARS); // update position
    1180        if (typeParams.isEmpty() && index == signature.length()) {
    1181            // We have a Type signature.
    1182            return type;
    1183        }
    1184        // We have a Class signature.
    1185        final StringBuilder typeClass = new StringBuilder(typeParams);
    1186        typeClass.append(" extends ");
    1187        typeClass.append(type);
    1188        if (index < signature.length()) {
    1189            typeClass.append(" implements ");
    1190            typeClass.append(typeSignatureToString(signature.substring(index), chopit));
    1191            index += unwrap(CONSUMER_CHARS); // update position
    1192        }
    1193        while (index < signature.length()) {
    1194            typeClass.append(", ");
    1195            typeClass.append(typeSignatureToString(signature.substring(index), chopit));
    1196            index += unwrap(CONSUMER_CHARS); // update position
    1197        }
    1198        return typeClass.toString();
    1199    }
    1200
    1201    /**
    1202     * Convert bytes into hexadecimal string
    1203     *
    1204     * @param bytes an array of bytes to convert to hexadecimal
    1205     *
    1206     * @return bytes as hexadecimal string, e.g. 00 fa 12 ...
    1207     */
    1208    public static String toHexString(final byte[] bytes) {
    1209        final StringBuilder buf = new StringBuilder();
    1210        for (int i = 0; i < bytes.length; i++) {
    1211            final short b = byteToShort(bytes[i]);
    1212            final String hex = Integer.toHexString(b);
    1213            if (b < 0x10) {
    1214                buf.append('0');
    1215            }
    1216            buf.append(hex);
    1217            if (i < bytes.length - 1) {
    1218                buf.append(' ');
    1219            }
    1220        }
    1221        return buf.toString();
    1222    }
    1223
    1224    /**
    1225     * Return type of method signature as a byte value as defined in <em>Constants</em>
    1226     *
    1227     * @param signature in format described above
    1228     * @return type of method signature
    1229     * @see Const
    1230     *
    1231     * @throws ClassFormatException if signature is not a method signature
    1232     */
    1233    public static byte typeOfMethodSignature(final String signature) throws ClassFormatException {
    1234        int index;
    1235        try {
    1236            if (signature.charAt(0) != '(') {
    1237                throw new InvalidMethodSignatureException(signature);
    1238            }
    1239            index = signature.lastIndexOf(')') + 1;
    1240            return typeOfSignature(signature.substring(index));
    1241        } catch (final StringIndexOutOfBoundsException e) {
    1242            throw new InvalidMethodSignatureException(signature, e);
    1243        }
    1244    }
    1245
    1246    /**
    1247     * Return type of signature as a byte value as defined in <em>Constants</em>
    1248     *
    1249     * @param signature in format described above
    1250     * @return type of signature
    1251     * @see Const
    1252     *
    1253     * @throws ClassFormatException if signature isn't a known type
    1254     */
    1255    public static byte typeOfSignature(final String signature) throws ClassFormatException {
    1256        try {
    1257            switch (signature.charAt(0)) {
    1258            case 'B':
    1259                return Const.T_BYTE;
    1260            case 'C':
    1261                return Const.T_CHAR;
    1262            case 'D':
    1263                return Const.T_DOUBLE;
    1264            case 'F':
    1265                return Const.T_FLOAT;
    1266            case 'I':
    1267                return Const.T_INT;
    1268            case 'J':
    1269                return Const.T_LONG;
    1270            case 'L':
    1271            case 'T':
    1272                return Const.T_REFERENCE;
    1273            case '[':
    1274                return Const.T_ARRAY;
    1275            case 'V':
    1276                return Const.T_VOID;
    1277            case 'Z':
    1278                return Const.T_BOOLEAN;
    1279            case 'S':
    1280                return Const.T_SHORT;
    1281            case '!':
    1282            case '+':
    1283            case '*':
    1284                return typeOfSignature(signature.substring(1));
    1285            default:
    1286                throw new InvalidMethodSignatureException(signature);
    1287            }
    1288        } catch (final StringIndexOutOfBoundsException e) {
    1289            throw new InvalidMethodSignatureException(signature, e);
    1290        }
    1291    }
    1292
    1293    /**
    1294     * Converts a type parameter list signature to a string.
    1295     *
    1296     * @param signature signature to convert
    1297     * @param chopit flag that determines whether chopping is executed or not
    1298     * @return String containg human readable signature
    1299     */
    1300    private static String typeParamTypesToString(final String signature, final boolean chopit) {
    1301        // The first character is guranteed to be '<'
    1302        final StringBuilder typeParams = new StringBuilder("<");
    1303        int index = 1; // skip the '<'
    1304        // get the first TypeParameter
    1305        typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
    1306        index += unwrap(CONSUMER_CHARS); // update position
    1307        // are there more TypeParameters?
    1308        while (signature.charAt(index) != '>') {
    1309            typeParams.append(", ");
    1310            typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
    1311            index += unwrap(CONSUMER_CHARS); // update position
    1312        }
    1313        wrap(CONSUMER_CHARS, index + 1); // account for the '>' char
    1314        return typeParams.append(">").toString();
    1315    }
    1316
    1317    /**
    1318     * Converts a type parameter signature to a string.
    1319     *
    1320     * @param signature signature to convert
    1321     * @param chopit flag that determines whether chopping is executed or not
    1322     * @return String containg human readable signature
    1323     */
    1324    private static String typeParamTypeToString(final String signature, final boolean chopit) {
    1325        int index = signature.indexOf(':');
    1326        if (index <= 0) {
    1327            throw new ClassFormatException("Invalid type parameter signature: " + signature);
    1328        }
    1329        // get the TypeParameter identifier
    1330        final StringBuilder typeParam = new StringBuilder(signature.substring(0, index));
    1331        index++; // account for the ':'
    1332        if (signature.charAt(index) != ':') {
    1333            // we have a class bound
    1334            typeParam.append(" extends ");
    1335            typeParam.append(typeSignatureToString(signature.substring(index), chopit));
    1336            index += unwrap(CONSUMER_CHARS); // update position
    1337        }
    1338        // look for interface bounds
    1339        while (signature.charAt(index) == ':') {
    1340            index++; // skip over the ':'
    1341            typeParam.append(" & ");
    1342            typeParam.append(typeSignatureToString(signature.substring(index), chopit));
    1343            index += unwrap(CONSUMER_CHARS); // update position
    1344        }
    1345        wrap(CONSUMER_CHARS, index);
    1346        return typeParam.toString();
    1347    }
    1348
    1349    /**
    1350     * Converts a list of type signatures to a string.
    1351     *
    1352     * @param signature signature to convert
    1353     * @param chopit flag that determines whether chopping is executed or not
    1354     * @param term character indicating the end of the list
    1355     * @return String containg human readable signature
    1356     */
    1357    private static String typeSignaturesToString(final String signature, final boolean chopit, final char term) {
    1358        // The first character will be an 'open' that matches the 'close' contained in term.
    1359        final StringBuilder typeList = new StringBuilder(signature.substring(0, 1));
    1360        int index = 1; // skip the 'open' character
    1361        // get the first Type in the list
    1362        if (signature.charAt(index) != term) {
    1363            typeList.append(typeSignatureToString(signature.substring(index), chopit));
    1364            index += unwrap(CONSUMER_CHARS); // update position
    1365        }
    1366        // are there more types in the list?
    1367        while (signature.charAt(index) != term) {
    1368            typeList.append(", ");
    1369            typeList.append(typeSignatureToString(signature.substring(index), chopit));
    1370            index += unwrap(CONSUMER_CHARS); // update position
    1371        }
    1372        wrap(CONSUMER_CHARS, index + 1); // account for the term char
    1373        return typeList.append(term).toString();
    1374    }
    1375
    1376    /**
    1377     *
    1378     * This method converts a type signature string into a Java type declaration such as 'String[]' and throws a
    1379     * 'ClassFormatException' when the parsed type is invalid.
    1380     *
    1381     * @param signature type signature
    1382     * @param chopit flag that determines whether chopping is executed or not
    1383     * @return string containing human readable type signature
    1384     * @throws ClassFormatException if a class is malformed or cannot be interpreted as a class file
    1385     * @since 6.4.0
    1386     */
    1387    public static String typeSignatureToString(final String signature, final boolean chopit) throws ClassFormatException {
    1388        // corrected concurrent private static field acess
    1389        wrap(CONSUMER_CHARS, 1); // This is the default, read just one char like 'B'
    1390        try {
    1391            switch (signature.charAt(0)) {
    1392            case 'B':
    1393                return "byte";
    1394            case 'C':
    1395                return "char";
    1396            case 'D':
    1397                return "double";
    1398            case 'F':
    1399                return "float";
    1400            case 'I':
    1401                return "int";
    1402            case 'J':
    1403                return "long";
    1404            case 'T': { // TypeVariableSignature
    1405                final int index = signature.indexOf(';'); // Look for closing ';'
    1406                if (index < 0) {
    1407                    throw new ClassFormatException("Invalid type variable signature: " + signature);
    1408                }
    1409                // corrected concurrent private static field acess
    1410                wrap(CONSUMER_CHARS, index + 1); // "Tblabla;" 'T' and ';' are removed
    1411                return compactClassName(signature.substring(1, index), chopit);
    1412            }
    1413            case 'L': { // Full class name
    1414                // should this be a while loop? can there be more than
    1415                // one generic clause? (markro)
    1416                int fromIndex = signature.indexOf('<'); // generic type?
    1417                if (fromIndex < 0) {
    1418                    fromIndex = 0;
    1419                } else {
    1420                    fromIndex = signature.indexOf('>', fromIndex);
    1421                    if (fromIndex < 0) {
    1422                        throw new ClassFormatException("Invalid signature: " + signature);
    1423                    }
    1424                }
    1425                final int index = signature.indexOf(';', fromIndex); // Look for closing ';'
    1426                if (index < 0) {
    1427                    throw new ClassFormatException("Invalid signature: " + signature);
    1428                }
    1429
    1430                // check to see if there are any TypeArguments
    1431                final int bracketIndex = signature.substring(0, index).indexOf('<');
    1432                if (bracketIndex < 0) {
    1433                    // just a class identifier
    1434                    wrap(CONSUMER_CHARS, index + 1); // "Lblabla;" 'L' and ';' are removed
    1435                    return compactClassName(signature.substring(1, index), chopit);
    1436                }
    1437                // but make sure we are not looking past the end of the current item
    1438                fromIndex = signature.indexOf(';');
    1439                if (fromIndex < 0) {
    1440                    throw new ClassFormatException("Invalid signature: " + signature);
    1441                }
    1442                if (fromIndex < bracketIndex) {
    1443                    // just a class identifier
    1444                    wrap(CONSUMER_CHARS, fromIndex + 1); // "Lblabla;" 'L' and ';' are removed
    1445                    return compactClassName(signature.substring(1, fromIndex), chopit);
    1446                }
    1447
    1448                // we have TypeArguments; build up partial result
    1449                // as we recurse for each TypeArgument
    1450                final StringBuilder type = new StringBuilder(compactClassName(signature.substring(1, bracketIndex), chopit)).append("<");
    1451                int consumedChars = bracketIndex + 1; // Shadows global var
    1452
    1453                // check for wildcards
    1454                if (signature.charAt(consumedChars) == '+') {
    1455                    type.append("? extends ");
    1456                    consumedChars++;
    1457                } else if (signature.charAt(consumedChars) == '-') {
    1458                    type.append("? super ");
    1459                    consumedChars++;
    1460                }
    1461
    1462                // get the first TypeArgument
    1463                if (signature.charAt(consumedChars) == '*') {
    1464                    type.append("?");
    1465                    consumedChars++;
    1466                } else {
    1467                    type.append(typeSignatureToString(signature.substring(consumedChars), chopit));
    1468                    // update our consumed count by the number of characters the for type argument
    1469                    consumedChars = unwrap(Utility.CONSUMER_CHARS) + consumedChars;
    1470                    wrap(Utility.CONSUMER_CHARS, consumedChars);
    1471                }
    1472
    1473                // are there more TypeArguments?
    1474                while (signature.charAt(consumedChars) != '>') {
    1475                    type.append(", ");
    1476                    // check for wildcards
    1477                    if (signature.charAt(consumedChars) == '+') {
    1478                        type.append("? extends ");
    1479                        consumedChars++;
    1480                    } else if (signature.charAt(consumedChars) == '-') {
    1481                        type.append("? super ");
    1482                        consumedChars++;
    1483                    }
    1484                    if (signature.charAt(consumedChars) == '*') {
    1485                        type.append("?");
    1486                        consumedChars++;
    1487                    } else {
    1488                        type.append(typeSignatureToString(signature.substring(consumedChars), chopit));
    1489                        // update our consumed count by the number of characters the for type argument
    1490                        consumedChars = unwrap(Utility.CONSUMER_CHARS) + consumedChars;
    1491                        wrap(Utility.CONSUMER_CHARS, consumedChars);
    1492                    }
    1493                }
    1494
    1495                // process the closing ">"
    1496                consumedChars++;
    1497                type.append(">");
    1498
    1499                if (signature.charAt(consumedChars) == '.') {
    1500                    // we have a ClassTypeSignatureSuffix
    1501                    type.append(".");
    1502                    // convert SimpleClassTypeSignature to fake ClassTypeSignature
    1503                    // and then recurse to parse it
    1504                    type.append(typeSignatureToString("L" + signature.substring(consumedChars + 1), chopit));
    1505                    // update our consumed count by the number of characters the for type argument
    1506                    // note that this count includes the "L" we added, but that is ok
    1507                    // as it accounts for the "." we didn't consume
    1508                    consumedChars = unwrap(Utility.CONSUMER_CHARS) + consumedChars;
    1509                    wrap(Utility.CONSUMER_CHARS, consumedChars);
    1510                    return type.toString();
    1511                }
    1512                if (signature.charAt(consumedChars) != ';') {
    1513                    throw new ClassFormatException("Invalid signature: " + signature);
    1514                }
    1515                wrap(Utility.CONSUMER_CHARS, consumedChars + 1); // remove final ";"
    1516                return type.toString();
    1517            }
    1518            case 'S':
    1519                return "short";
    1520            case 'Z':
    1521                return "boolean";
    1522            case '[': { // Array declaration
    1523                int n;
    1524                StringBuilder brackets;
    1525                String type;
    1526                int consumedChars; // Shadows global var
    1527                brackets = new StringBuilder(); // Accumulate []'s
    1528                // Count opening brackets and look for optional size argument
    1529                for (n = 0; signature.charAt(n) == '['; n++) {
    1530                    brackets.append("[]");
    1531                }
    1532                consumedChars = n; // Remember value
    1533                // The rest of the string denotes a '<field_type>'
    1534                type = typeSignatureToString(signature.substring(n), chopit);
    1535                // corrected concurrent private static field acess
    1536                // Utility.consumed_chars += consumed_chars; is replaced by:
    1537                final int temp = unwrap(Utility.CONSUMER_CHARS) + consumedChars;
    1538                wrap(Utility.CONSUMER_CHARS, temp);
    1539                return type + brackets.toString();
    1540            }
    1541            case 'V':
    1542                return "void";
    1543            default:
    1544                throw new ClassFormatException("Invalid signature: '" + signature + "'");
    1545            }
    1546        } catch (final StringIndexOutOfBoundsException e) { // Should never occur
    1547            throw new ClassFormatException("Invalid signature: " + signature, e);
    1548        }
    1549    }
    1550
    1551    private static int unwrap(final ThreadLocal<Integer> tl) {
    1552        return tl.get().intValue();
    1553    }
    1554
    1555    private static void wrap(final ThreadLocal<Integer> tl, final int value) {
    1556        tl.set(Integer.valueOf(value));
    1557    }
    1558
    1559}