    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.ArrayFill;
    041import org.apache.commons.lang3.ArrayUtils;
    042
    043/**
    044 * Utility functions that do not really belong to any class in particular.
    045 */
    046// @since 6.0 methods are no longer final
    047public abstract class Utility {
    048
    049    /**
    050     * Decode characters into bytes. Used by <a href="Utility.html#decode(java.lang.String, boolean)">decode()</a>
    051     */
    052    private static final class JavaReader extends FilterReader {
    053
    054        public JavaReader(final Reader in) {
    055            super(in);
    056        }
    057
    058        @Override
    059        public int read() throws IOException {
    060            final int b = in.read();
    061            if (b != ESCAPE_CHAR) {
    062                return b;
    063            }
    064            final int i = in.read();
    065            if (i < 0) {
    066                return -1;
    067            }
    068            if (i >= '0' && i <= '9' || i >= 'a' && i <= 'f') { // Normal escape
    069                final int j = in.read();
    070                if (j < 0) {
    071                    return -1;
    072                }
    073                final char[] tmp = {(char) i, (char) j};
    074                return Integer.parseInt(new String(tmp), 16);
    075            }
    076            return MAP_CHAR[i];
    077        }
    078
    079        @Override
    080        public int read(final char[] cbuf, final int off, final int len) throws IOException {
    081            for (int i = 0; i < len; i++) {
    082                cbuf[off + i] = (char) read();
    083            }
    084            return len;
    085        }
    086    }
    087
    088    /**
    089     * Encode bytes into valid Java identifier characters. Used by
    090     * <a href="Utility.html#encode(byte[], boolean)">encode()</a>
    091     */
    092    private static final class JavaWriter extends FilterWriter {
    093
    094        public JavaWriter(final Writer out) {
    095            super(out);
    096        }
    097
    098        @Override
    099        public void write(final char[] cbuf, final int off, final int len) throws IOException {
    100            for (int i = 0; i < len; i++) {
    101                write(cbuf[off + i]);
    102            }
    103        }
    104
    105        @Override
    106        public void write(final int b) throws IOException {
    107            if (isJavaIdentifierPart((char) b) && b != ESCAPE_CHAR) {
    108                out.write(b);
    109            } else {
    110                out.write(ESCAPE_CHAR); // Escape character
    111                // Special escape
    112                if (b >= 0 && b < FREE_CHARS) {
    113                    out.write(CHAR_MAP[b]);
    114                } else { // Normal escape
    115                    final char[] tmp = Integer.toHexString(b).toCharArray();
    116                    if (tmp.length == 1) {
    117                        out.write('0');
    118                        out.write(tmp[0]);
    119                    } else {
    120                        out.write(tmp[0]);
    121                        out.write(tmp[1]);
    122                    }
    123                }
    124            }
    125        }
    126
    127        @Override
    128        public void write(final String str, final int off, final int len) throws IOException {
    129            write(str.toCharArray(), off, len);
    130        }
    131    }
    132
    133    /*
    134     * How many chars have been consumed during parsing in typeSignatureToString(). Read by methodSignatureToString(). Set
    135     * by side effect, but only internally.
    136     */
    137    private static final ThreadLocal<Integer> CONSUMER_CHARS = ThreadLocal.withInitial(() -> Integer.valueOf(0));
    138
    139    /*
    140     * The 'WIDE' instruction is used in the byte code to allow 16-bit wide indices for local variables. This opcode
    141     * precedes an 'ILOAD', e.g.. The opcode immediately following takes an extra byte which is combined with the following
    142     * byte to form a 16-bit value.
    143     */
    144    private static boolean wide;
    145
    146    // A-Z, g-z, _, $
    147    private static final int FREE_CHARS = 48;
    148
    149    private static final int[] CHAR_MAP = new int[FREE_CHARS];
    150
    151    private static final int[] MAP_CHAR = new int[256]; // Reverse map
    152
    153    private static final char ESCAPE_CHAR = '$';
    154
    155    static {
    156        int j = 0;
    157        for (int i = 'A'; i <= 'Z'; i++) {
    158            CHAR_MAP[j] = i;
    159            MAP_CHAR[i] = j;
    160            j++;
    161        }
    162        for (int i = 'g'; i <= 'z'; i++) {
    163            CHAR_MAP[j] = i;
    164            MAP_CHAR[i] = j;
    165            j++;
    166        }
    167        CHAR_MAP[j] = '$';
    168        MAP_CHAR['$'] = j;
    169        j++;
    170        CHAR_MAP[j] = '_';
    171        MAP_CHAR['_'] = j;
    172    }
    173
    174    /**
    175     * Convert bit field of flags into string such as 'static final'.
    176     *
    177     * @param accessFlags Access flags
    178     * @return String representation of flags
    179     */
    180    public static String accessToString(final int accessFlags) {
    181        return accessToString(accessFlags, false);
    182    }
    183
    184    /**
    185     * Convert bit field of flags into string such as 'static final'.
    186     *
    187     * Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized".
    188     * This is because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'.
    189     *
    190     * @param accessFlags Access flags
    191     * @param forClass access flags are for class qualifiers ?
    192     * @return String representation of flags
    193     */
    194    public static String accessToString(final int accessFlags, final boolean forClass) {
    195        final StringBuilder buf = new StringBuilder();
    196        int p = 0;
    197        for (int i = 0; p < Const.MAX_ACC_FLAG_I; i++) { // Loop through known flags
    198            p = pow2(i);
    199            if ((accessFlags & p) != 0) {
    200                /*
    201                 * Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized".
    202                 * This is because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'.
    203                 */
    204                if (forClass && (p == Const.ACC_SUPER || p == Const.ACC_INTERFACE)) {
    205                    continue;
    206                }
    207                buf.append(Const.getAccessName(i)).append(" ");
    208            }
    209        }
    210        return buf.toString().trim();
    211    }
    212
    213    /**
    214     * Convert (signed) byte to (unsigned) short value, i.e., all negative values become positive.
    215     */
    216    private static short byteToShort(final byte b) {
    217        return b < 0 ? (short) (256 + b) : (short) b;
    218    }
    219
    220    /**
    221     * @param accessFlags the class flags
    222     *
    223     * @return "class" or "interface", depending on the ACC_INTERFACE flag
    224     */
    225    public static String classOrInterface(final int accessFlags) {
    226        return (accessFlags & Const.ACC_INTERFACE) != 0 ? "interface" : "class";
    227    }
    228
    229    /**
    230     * @return 'flag' with bit 'i' set to 0
    231     */
    232    public static int clearBit(final int flag, final int i) {
    233        final int bit = pow2(i);
    234        return (flag & bit) == 0 ? flag : flag ^ bit;
    235    }
    236
    237    public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length) {
    238        return codeToString(code, constantPool, index, length, true);
    239    }
    240
    241    /**
    242     * Disassemble a byte array of JVM byte codes starting from code line 'index' and return the disassembled string
    243     * representation. Decode only 'num' opcodes (including their operands), use -1 if you want to decompile everything.
    244     *
    245     * @param code byte code array
    246     * @param constantPool Array of constants
    247     * @param index offset in 'code' array <EM>(number of opcodes, not bytes!)</EM>
    248     * @param length number of opcodes to decompile, -1 for all
    249     * @param verbose be verbose, e.g. print constant pool index
    250     * @return String representation of byte codes
    251     */
    252    public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length, final boolean verbose) {
    253        final StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient // CHECKSTYLE IGNORE MagicNumber
    254        try (ByteSequence stream = new ByteSequence(code)) {
    255            for (int i = 0; i < index; i++) {
    256                codeToString(stream, constantPool, verbose);
    257            }
    258            for (int i = 0; stream.available() > 0; i++) {
    259                if (length < 0 || i < length) {
    260                    final String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
    261                    buf.append(indices).append(codeToString(stream, constantPool, verbose)).append('\n');
    262                }
    263            }
    264        } catch (final IOException e) {
    265            throw new ClassFormatException("Byte code error: " + buf.toString(), e);
    266        }
    267        return buf.toString();
    268    }
    269
    270    public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool) throws IOException {
    271        return codeToString(bytes, constantPool, true);
    272    }
    273
    274    /**
    275     * Disassemble a stream of byte codes and return the string representation.
    276     *
    277     * @param bytes stream of bytes
    278     * @param constantPool Array of constants
    279     * @param verbose be verbose, e.g. print constant pool index
    280     * @return String representation of byte code
    281     *
    282     * @throws IOException if a failure from reading from the bytes argument occurs
    283     */
    284    public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool, final boolean verbose) throws IOException {
    285        final short opcode = (short) bytes.readUnsignedByte();
    286        int defaultOffset = 0;
    287        int low;
    288        int high;
    289        int npairs;
    290        int index;
    291        int vindex;
    292        int constant;
    293        int[] match;
    294        int[] jumpTable;
    295        int noPadBytes = 0;
    296        int offset;
    297        final StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode));
    298        /*
    299         * Special case: Skip (0-3) padding bytes, i.e., the following bytes are 4-byte-aligned
    300         */
    301        if (opcode == Const.TABLESWITCH || opcode == Const.LOOKUPSWITCH) {
    302            final int remainder = bytes.getIndex() % 4;
    303            noPadBytes = remainder == 0 ? 0 : 4 - remainder;
    304            for (int i = 0; i < noPadBytes; i++) {
    305                byte b;
    306                if ((b = bytes.readByte()) != 0) {
    307                    System.err.println("Warning: Padding byte != 0 in " + Const.getOpcodeName(opcode) + ":" + b);
    308                }
    309            }
    310            // Both cases have a field default_offset in common
    311            defaultOffset = bytes.readInt();
    312        }
    313        switch (opcode) {
    314        /*
    315         * Table switch has variable length arguments.
    316         */
    317        case Const.TABLESWITCH:
    318            low = bytes.readInt();
    319            high = bytes.readInt();
    320            offset = bytes.getIndex() - 12 - noPadBytes - 1;
    321            defaultOffset += offset;
    322            buf.append("\tdefault = ").append(defaultOffset).append(", low = ").append(low).append(", high = ").append(high).append("(");
    323            jumpTable = new int[high - low + 1];
    324            for (int i = 0; i < jumpTable.length; i++) {
    325                jumpTable[i] = offset + bytes.readInt();
    326                buf.append(jumpTable[i]);
    327                if (i < jumpTable.length - 1) {
    328                    buf.append(", ");
    329                }
    330            }
    331            buf.append(")");
    332            break;
    333        /*
    334         * Lookup switch has variable length arguments.
    335         */
    336        case Const.LOOKUPSWITCH: {
    337            npairs = bytes.readInt();
    338            offset = bytes.getIndex() - 8 - noPadBytes - 1;
    339            match = new int[npairs];
    340            jumpTable = new int[npairs];
    341            defaultOffset += offset;
    342            buf.append("\tdefault = ").append(defaultOffset).append(", npairs = ").append(npairs).append(" (");
    343            for (int i = 0; i < npairs; i++) {
    344                match[i] = bytes.readInt();
    345                jumpTable[i] = offset + bytes.readInt();
    346                buf.append("(").append(match[i]).append(", ").append(jumpTable[i]).append(")");
    347                if (i < npairs - 1) {
    348                    buf.append(", ");
    349                }
    350            }
    351            buf.append(")");
    352        }
    353            break;
    354        /*
    355         * Two address bytes + offset from start of byte stream form the jump target
    356         */
    357        case Const.GOTO:
    358        case Const.IFEQ:
    359        case Const.IFGE:
    360        case Const.IFGT:
    361        case Const.IFLE:
    362        case Const.IFLT:
    363        case Const.JSR:
    364        case Const.IFNE:
    365        case Const.IFNONNULL:
    366        case Const.IFNULL:
    367        case Const.IF_ACMPEQ:
    368        case Const.IF_ACMPNE:
    369        case Const.IF_ICMPEQ:
    370        case Const.IF_ICMPGE:
    371        case Const.IF_ICMPGT:
    372        case Const.IF_ICMPLE:
    373        case Const.IF_ICMPLT:
    374        case Const.IF_ICMPNE:
    375            buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readShort());
    376            break;
    377        /*
    378         * 32-bit wide jumps
    379         */
    380        case Const.GOTO_W:
    381        case Const.JSR_W:
    382            buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readInt());
    383            break;
    384        /*
    385         * Index byte references local variable (register)
    386         */
    387        case Const.ALOAD:
    388        case Const.ASTORE:
    389        case Const.DLOAD:
    390        case Const.DSTORE:
    391        case Const.FLOAD:
    392        case Const.FSTORE:
    393        case Const.ILOAD:
    394        case Const.ISTORE:
    395        case Const.LLOAD:
    396        case Const.LSTORE:
    397        case Const.RET:
    398            if (wide) {
    399                vindex = bytes.readUnsignedShort();
    400                wide = false; // Clear flag
    401            } else {
    402                vindex = bytes.readUnsignedByte();
    403            }
    404            buf.append("\t\t%").append(vindex);
    405            break;
    406        /*
    407         * Remember wide byte which is used to form a 16-bit address in the following instruction. Relies on that the method is
    408         * called again with the following opcode.
    409         */
    410        case Const.WIDE:
    411            wide = true;
    412            buf.append("\t(wide)");
    413            break;
    414        /*
    415         * Array of basic type.
    416         */
    417        case Const.NEWARRAY:
    418            buf.append("\t\t<").append(Const.getTypeName(bytes.readByte())).append(">");
    419            break;
    420        /*
    421         * Access object/class fields.
    422         */
    423        case Const.GETFIELD:
    424        case Const.GETSTATIC:
    425        case Const.PUTFIELD:
    426        case Const.PUTSTATIC:
    427            index = bytes.readUnsignedShort();
    428            buf.append("\t\t").append(constantPool.constantToString(index, Const.CONSTANT_Fieldref)).append(verbose ? " (" + index + ")" : "");
    429            break;
    430        /*
    431         * Operands are references to classes in constant pool
    432         */
    433        case Const.NEW:
    434        case Const.CHECKCAST:
    435            buf.append("\t");
    436            index = bytes.readUnsignedShort();
    437            buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
    438            break;
    439        case Const.INSTANCEOF:
    440            index = bytes.readUnsignedShort();
    441            buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
    442            break;
    443        /*
    444         * Operands are references to methods in constant pool
    445         */
    446        case Const.INVOKESPECIAL:
    447        case Const.INVOKESTATIC:
    448            index = bytes.readUnsignedShort();
    449            final Constant c = constantPool.getConstant(index);
    450            // With Java8 operand may be either a CONSTANT_Methodref
    451            // or a CONSTANT_InterfaceMethodref. (markro)
    452            buf.append("\t").append(constantPool.constantToString(index, c.getTag())).append(verbose ? " (" + index + ")" : "");
    453            break;
    454        case Const.INVOKEVIRTUAL:
    455            index = bytes.readUnsignedShort();
    456            buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_Methodref)).append(verbose ? " (" + index + ")" : "");
    457            break;
    458        case Const.INVOKEINTERFACE:
    459            index = bytes.readUnsignedShort();
    460            final int nargs = bytes.readUnsignedByte(); // historical, redundant
    461            buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InterfaceMethodref)).append(verbose ? " (" + index + ")\t" : "")
    462                .append(nargs).append("\t").append(bytes.readUnsignedByte()); // Last byte is a reserved space
    463            break;
    464        case Const.INVOKEDYNAMIC:
    465            index = bytes.readUnsignedShort();
    466            buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InvokeDynamic)).append(verbose ? " (" + index + ")\t" : "")
    467                .append(bytes.readUnsignedByte()) // Thrid byte is a reserved space
    468                .append(bytes.readUnsignedByte()); // Last byte is a reserved space
    469            break;
    470        /*
    471         * Operands are references to items in constant pool
    472         */
    473        case Const.LDC_W:
    474        case Const.LDC2_W:
    475            index = bytes.readUnsignedShort();
    476            buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
    477                .append(verbose ? " (" + index + ")" : "");
    478            break;
    479        case Const.LDC:
    480            index = bytes.readUnsignedByte();
    481            buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
    482                .append(verbose ? " (" + index + ")" : "");
    483            break;
    484        /*
    485         * Array of references.
    486         */
    487        case Const.ANEWARRAY:
    488            index = bytes.readUnsignedShort();
    489            buf.append("\t\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">")
    490                .append(verbose ? " (" + index + ")" : "");
    491            break;
    492        /*
    493         * Multidimensional array of references.
    494         */
    495        case Const.MULTIANEWARRAY: {
    496            index = bytes.readUnsignedShort();
    497            final int dimensions = bytes.readUnsignedByte();
    498            buf.append("\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">\t").append(dimensions)
    499                .append(verbose ? " (" + index + ")" : "");
    500        }
    501            break;
    502        /*
    503         * Increment local variable.
    504         */
    505        case Const.IINC:
    506            if (wide) {
    507                vindex = bytes.readUnsignedShort();
    508                constant = bytes.readShort();
    509                wide = false;
    510            } else {
    511                vindex = bytes.readUnsignedByte();
    512                constant = bytes.readByte();
    513            }
    514            buf.append("\t\t%").append(vindex).append("\t").append(constant);
    515            break;
    516        default:
    517            if (Const.getNoOfOperands(opcode) > 0) {
    518                for (int i = 0; i < Const.getOperandTypeCount(opcode); i++) {
    519                    buf.append("\t\t");
    520                    switch (Const.getOperandType(opcode, i)) {
    521                    case Const.T_BYTE:
    522                        buf.append(bytes.readByte());
    523                        break;
    524                    case Const.T_SHORT:
    525                        buf.append(bytes.readShort());
    526                        break;
    527                    case Const.T_INT:
    528                        buf.append(bytes.readInt());
    529                        break;
    530                    default: // Never reached
    531                        throw new IllegalStateException("Unreachable default case reached!");
    532                    }
    533                }
    534            }
    535        }
    536        return buf.toString();
    537    }
    538
    539    /**
    540     * Shorten long class names, <em>java/lang/String</em> becomes <em>String</em>.
    541     *
    542     * @param str The long class name
    543     * @return Compacted class name
    544     */
    545    public static String compactClassName(final String str) {
    546        return compactClassName(str, true);
    547    }
    548
    549    /**
    550     * Shorten long class names, <em>java/lang/String</em> becomes <em>java.lang.String</em>, e.g.. If <em>chopit</em> is
    551     * <em>true</em> the prefix <em>java.lang</em> is also removed.
    552     *
    553     * @param str The long class name
    554     * @param chopit flag that determines whether chopping is executed or not
    555     * @return Compacted class name
    556     */
    557    public static String compactClassName(final String str, final boolean chopit) {
    558        return compactClassName(str, "java.lang.", chopit);
    559    }
    560
    561    /**
    562     * Shorten long class name <em>str</em>, i.e., chop off the <em>prefix</em>, if the class name starts with this string
    563     * and the flag <em>chopit</em> is true. Slashes <em>/</em> are converted to dots <em>.</em>.
    564     *
    565     * @param str The long class name
    566     * @param prefix The prefix the get rid off
    567     * @param chopit flag that determines whether chopping is executed or not
    568     * @return Compacted class name
    569     */
    570    public static String compactClassName(String str, final String prefix, final boolean chopit) {
    571        final int len = prefix.length();
    572        str = pathToPackage(str); // Is '/' on all systems, even DOS
    573        // If string starts with 'prefix' and contains no further dots
    574        if (chopit && str.startsWith(prefix) && str.substring(len).indexOf('.') == -1) {
    575            str = str.substring(len);
    576        }
    577        return str;
    578    }
    579
    580    /**
    581     * Escape all occurrences of newline chars '\n', quotes \", etc.
    582     */
    583    public static String convertString(final String label) {
    584        final char[] ch = label.toCharArray();
    585        final StringBuilder buf = new StringBuilder();
    586        for (final char element : ch) {
    587            switch (element) {
    588            case '\n':
    589                buf.append("\\n");
    590                break;
    591            case '\r':
    592                buf.append("\\r");
    593                break;
    594            case '\"':
    595                buf.append("\\\"");
    596                break;
    597            case '\'':
    598                buf.append("\\'");
    599                break;
    600            case '\\':
    601                buf.append("\\\\");
    602                break;
    603            default:
    604                buf.append(element);
    605                break;
    606            }
    607        }
    608        return buf.toString();
    609    }
    610
    611    private static int countBrackets(final String brackets) {
    612        final char[] chars = brackets.toCharArray();
    613        int count = 0;
    614        boolean open = false;
    615        for (final char c : chars) {
    616            switch (c) {
    617            case '[':
    618                if (open) {
    619                    throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
    620                }
    621                open = true;
    622                break;
    623            case ']':
    624                if (!open) {
    625                    throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
    626                }
    627                open = false;
    628                count++;
    629                break;
    630            default:
    631                // Don't care
    632                break;
    633            }
    634        }
    635        if (open) {
    636            throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
    637        }
    638        return count;
    639    }
    640
    641    /**
    642     * Decode a string back to a byte array.
    643     *
    644     * @param s the string to convert
    645     * @param uncompress use gzip to uncompress the stream of bytes
    646     *
    647     * @throws IOException if there's a gzip exception
    648     */
    649    public static byte[] decode(final String s, final boolean uncompress) throws IOException {
    650        byte[] bytes;
    651        try (JavaReader jr = new JavaReader(new CharArrayReader(s.toCharArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    652            int ch;
    653            while ((ch = jr.read()) >= 0) {
    654                bos.write(ch);
    655            }
    656            bytes = bos.toByteArray();
    657        }
    658        if (uncompress) {
    659            final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
    660            final byte[] tmp = new byte[bytes.length * 3]; // Rough estimate
    661            int count = 0;
    662            int b;
    663            while ((b = gis.read()) >= 0) {
    664                tmp[count++] = (byte) b;
    665            }
    666            bytes = Arrays.copyOf(tmp, count);
    667        }
    668        return bytes;
    669    }
    670
    671    /**
    672     * Encode byte array it into Java identifier string, i.e., a string that only contains the following characters: (a, ...
    673     * z, A, ... Z, 0, ... 9, _, $). The encoding algorithm itself is not too clever: if the current byte's ASCII value
    674     * already is a valid Java identifier part, leave it as it is. Otherwise it writes the escape character($) followed by:
    675     *
    676     * <ul>
    677     * <li>the ASCII value as a hexadecimal string, if the value is not in the range 200..247</li>
    678     * <li>a Java identifier char not used in a lowercase hexadecimal string, if the value is in the range 200..247</li>
    679     * </ul>
    680     *
    681     * <p>
    682     * This operation inflates the original byte array by roughly 40-50%
    683     * </p>
    684     *
    685     * @param bytes the byte array to convert
    686     * @param compress use gzip to minimize string
    687     *
    688     * @throws IOException if there's a gzip exception
    689     */
    690    public static String encode(byte[] bytes, final boolean compress) throws IOException {
    691        if (compress) {
    692            try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos)) {
    693                gos.write(bytes, 0, bytes.length);
    694                gos.close();
    695                bytes = baos.toByteArray();
    696            }
    697        }
    698        final CharArrayWriter caw = new CharArrayWriter();
    699        try (JavaWriter jw = new JavaWriter(caw)) {
    700            for (final byte b : bytes) {
    701                final int in = b & 0x000000ff; // Normalize to unsigned
    702                jw.write(in);
    703            }
    704        }
    705        return caw.toString();
    706    }
    707
    708    /**
    709     * Fillup char with up to length characters with char 'fill' and justify it left or right.
    710     *
    711     * @param str string to format
    712     * @param length length of desired string
    713     * @param leftJustify format left or right
    714     * @param fill fill character
    715     * @return formatted string
    716     */
    717    public static String fillup(final String str, final int length, final boolean leftJustify, final char fill) {
    718        final int len = length - str.length();
    719        final char[] buf = ArrayFill.fill(new char[Math.max(len, 0)], 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 += 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}