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