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