1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.bcel.classfile;
19
20 import java.io.ByteArrayInputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.CharArrayReader;
23 import java.io.CharArrayWriter;
24 import java.io.FilterReader;
25 import java.io.FilterWriter;
26 import java.io.IOException;
27 import java.io.PrintStream;
28 import java.io.PrintWriter;
29 import java.io.Reader;
30 import java.io.Writer;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.List;
34 import java.util.Locale;
35 import java.util.zip.GZIPInputStream;
36 import java.util.zip.GZIPOutputStream;
37
38 import org.apache.bcel.Const;
39 import org.apache.bcel.util.ByteSequence;
40 import org.apache.commons.lang3.ArrayFill;
41 import org.apache.commons.lang3.ArrayUtils;
42
43
44
45
46
47 public abstract class Utility {
48
49
50
51
52 private static final class JavaReader extends FilterReader {
53
54 public JavaReader(final Reader in) {
55 super(in);
56 }
57
58 @Override
59 public int read() throws IOException {
60 final int b = in.read();
61 if (b != ESCAPE_CHAR) {
62 return b;
63 }
64 final int i = in.read();
65 if (i < 0) {
66 return -1;
67 }
68 if (i >= '0' && i <= '9' || i >= 'a' && i <= 'f') {
69 final int j = in.read();
70 if (j < 0) {
71 return -1;
72 }
73 final char[] tmp = {(char) i, (char) j};
74 return Integer.parseInt(new String(tmp), 16);
75 }
76 return MAP_CHAR[i];
77 }
78
79 @Override
80 public int read(final char[] cbuf, final int off, final int len) throws IOException {
81 for (int i = 0; i < len; i++) {
82 cbuf[off + i] = (char) read();
83 }
84 return len;
85 }
86 }
87
88
89
90
91
92 private static final class JavaWriter extends FilterWriter {
93
94 public JavaWriter(final Writer out) {
95 super(out);
96 }
97
98 @Override
99 public void write(final char[] cbuf, final int off, final int len) throws IOException {
100 for (int i = 0; i < len; i++) {
101 write(cbuf[off + i]);
102 }
103 }
104
105 @Override
106 public void write(final int b) throws IOException {
107 if (isJavaIdentifierPart((char) b) && b != ESCAPE_CHAR) {
108 out.write(b);
109 } else {
110 out.write(ESCAPE_CHAR);
111
112 if (b >= 0 && b < FREE_CHARS) {
113 out.write(CHAR_MAP[b]);
114 } else {
115 final char[] tmp = Integer.toHexString(b).toCharArray();
116 if (tmp.length == 1) {
117 out.write('0');
118 out.write(tmp[0]);
119 } else {
120 out.write(tmp[0]);
121 out.write(tmp[1]);
122 }
123 }
124 }
125 }
126
127 @Override
128 public void write(final String str, final int off, final int len) throws IOException {
129 write(str.toCharArray(), off, len);
130 }
131 }
132
133
134
135
136
137 private static final ThreadLocal<Integer> CONSUMER_CHARS = ThreadLocal.withInitial(() -> Integer.valueOf(0));
138
139
140
141
142
143
144 private static boolean wide;
145
146
147 private static final int FREE_CHARS = 48;
148
149 private static final int[] CHAR_MAP = new int[FREE_CHARS];
150
151 private static final int[] MAP_CHAR = new int[256];
152
153 private static final char ESCAPE_CHAR = '$';
154
155 static {
156 int j = 0;
157 for (int i = 'A'; i <= 'Z'; i++) {
158 CHAR_MAP[j] = i;
159 MAP_CHAR[i] = j;
160 j++;
161 }
162 for (int i = 'g'; i <= 'z'; i++) {
163 CHAR_MAP[j] = i;
164 MAP_CHAR[i] = j;
165 j++;
166 }
167 CHAR_MAP[j] = '$';
168 MAP_CHAR['$'] = j;
169 j++;
170 CHAR_MAP[j] = '_';
171 MAP_CHAR['_'] = j;
172 }
173
174
175
176
177
178
179
180 public static String accessToString(final int accessFlags) {
181 return accessToString(accessFlags, false);
182 }
183
184
185
186
187
188
189
190
191
192
193
194 public static String accessToString(final int accessFlags, final boolean forClass) {
195 final StringBuilder buf = new StringBuilder();
196 int p = 0;
197 for (int i = 0; p < Const.MAX_ACC_FLAG_I; i++) {
198 p = pow2(i);
199 if ((accessFlags & p) != 0) {
200
201
202
203
204 if (forClass && (p == Const.ACC_SUPER || p == Const.ACC_INTERFACE)) {
205 continue;
206 }
207 buf.append(Const.getAccessName(i)).append(" ");
208 }
209 }
210 return buf.toString().trim();
211 }
212
213
214
215
216 private static short byteToShort(final byte b) {
217 return b < 0 ? (short) (256 + b) : (short) b;
218 }
219
220
221
222
223
224
225 public static String classOrInterface(final int accessFlags) {
226 return (accessFlags & Const.ACC_INTERFACE) != 0 ? "interface" : "class";
227 }
228
229
230
231
232 public static int clearBit(final int flag, final int i) {
233 final int bit = pow2(i);
234 return (flag & bit) == 0 ? flag : flag ^ bit;
235 }
236
237 public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length) {
238 return codeToString(code, constantPool, index, length, true);
239 }
240
241
242
243
244
245
246
247
248
249
250
251
252 public static String codeToString(final byte[] code, final ConstantPool constantPool, final int index, final int length, final boolean verbose) {
253 final StringBuilder buf = new StringBuilder(code.length * 20);
254 try (ByteSequence stream = new ByteSequence(code)) {
255 for (int i = 0; i < index; i++) {
256 codeToString(stream, constantPool, verbose);
257 }
258 for (int i = 0; stream.available() > 0; i++) {
259 if (length < 0 || i < length) {
260 final String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
261 buf.append(indices).append(codeToString(stream, constantPool, verbose)).append('\n');
262 }
263 }
264 } catch (final IOException e) {
265 throw new ClassFormatException("Byte code error: " + buf.toString(), e);
266 }
267 return buf.toString();
268 }
269
270 public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool) throws IOException {
271 return codeToString(bytes, constantPool, true);
272 }
273
274
275
276
277
278
279
280
281
282
283
284 public static String codeToString(final ByteSequence bytes, final ConstantPool constantPool, final boolean verbose) throws IOException {
285 final short opcode = (short) bytes.readUnsignedByte();
286 int defaultOffset = 0;
287 int low;
288 int high;
289 int npairs;
290 int index;
291 int vindex;
292 int constant;
293 int[] match;
294 int[] jumpTable;
295 int noPadBytes = 0;
296 int offset;
297 final StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode));
298
299
300
301 if (opcode == Const.TABLESWITCH || opcode == Const.LOOKUPSWITCH) {
302 final int remainder = bytes.getIndex() % 4;
303 noPadBytes = remainder == 0 ? 0 : 4 - remainder;
304 for (int i = 0; i < noPadBytes; i++) {
305 byte b;
306 if ((b = bytes.readByte()) != 0) {
307 System.err.println("Warning: Padding byte != 0 in " + Const.getOpcodeName(opcode) + ":" + b);
308 }
309 }
310
311 defaultOffset = bytes.readInt();
312 }
313 switch (opcode) {
314
315
316
317 case Const.TABLESWITCH:
318 low = bytes.readInt();
319 high = bytes.readInt();
320 offset = bytes.getIndex() - 12 - noPadBytes - 1;
321 defaultOffset += offset;
322 buf.append("\tdefault = ").append(defaultOffset).append(", low = ").append(low).append(", high = ").append(high).append("(");
323 jumpTable = new int[high - low + 1];
324 for (int i = 0; i < jumpTable.length; i++) {
325 jumpTable[i] = offset + bytes.readInt();
326 buf.append(jumpTable[i]);
327 if (i < jumpTable.length - 1) {
328 buf.append(", ");
329 }
330 }
331 buf.append(")");
332 break;
333
334
335
336 case Const.LOOKUPSWITCH: {
337 npairs = bytes.readInt();
338 offset = bytes.getIndex() - 8 - noPadBytes - 1;
339 match = new int[npairs];
340 jumpTable = new int[npairs];
341 defaultOffset += offset;
342 buf.append("\tdefault = ").append(defaultOffset).append(", npairs = ").append(npairs).append(" (");
343 for (int i = 0; i < npairs; i++) {
344 match[i] = bytes.readInt();
345 jumpTable[i] = offset + bytes.readInt();
346 buf.append("(").append(match[i]).append(", ").append(jumpTable[i]).append(")");
347 if (i < npairs - 1) {
348 buf.append(", ");
349 }
350 }
351 buf.append(")");
352 }
353 break;
354
355
356
357 case Const.GOTO:
358 case Const.IFEQ:
359 case Const.IFGE:
360 case Const.IFGT:
361 case Const.IFLE:
362 case Const.IFLT:
363 case Const.JSR:
364 case Const.IFNE:
365 case Const.IFNONNULL:
366 case Const.IFNULL:
367 case Const.IF_ACMPEQ:
368 case Const.IF_ACMPNE:
369 case Const.IF_ICMPEQ:
370 case Const.IF_ICMPGE:
371 case Const.IF_ICMPGT:
372 case Const.IF_ICMPLE:
373 case Const.IF_ICMPLT:
374 case Const.IF_ICMPNE:
375 buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readShort());
376 break;
377
378
379
380 case Const.GOTO_W:
381 case Const.JSR_W:
382 buf.append("\t\t#").append(bytes.getIndex() - 1 + bytes.readInt());
383 break;
384
385
386
387 case Const.ALOAD:
388 case Const.ASTORE:
389 case Const.DLOAD:
390 case Const.DSTORE:
391 case Const.FLOAD:
392 case Const.FSTORE:
393 case Const.ILOAD:
394 case Const.ISTORE:
395 case Const.LLOAD:
396 case Const.LSTORE:
397 case Const.RET:
398 if (wide) {
399 vindex = bytes.readUnsignedShort();
400 wide = false;
401 } else {
402 vindex = bytes.readUnsignedByte();
403 }
404 buf.append("\t\t%").append(vindex);
405 break;
406
407
408
409
410 case Const.WIDE:
411 wide = true;
412 buf.append("\t(wide)");
413 break;
414
415
416
417 case Const.NEWARRAY:
418 buf.append("\t\t<").append(Const.getTypeName(bytes.readByte())).append(">");
419 break;
420
421
422
423 case Const.GETFIELD:
424 case Const.GETSTATIC:
425 case Const.PUTFIELD:
426 case Const.PUTSTATIC:
427 index = bytes.readUnsignedShort();
428 buf.append("\t\t").append(constantPool.constantToString(index, Const.CONSTANT_Fieldref)).append(verbose ? " (" + index + ")" : "");
429 break;
430
431
432
433 case Const.NEW:
434 case Const.CHECKCAST:
435 buf.append("\t");
436 index = bytes.readUnsignedShort();
437 buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
438 break;
439 case Const.INSTANCEOF:
440 index = bytes.readUnsignedShort();
441 buf.append("\t<").append(constantPool.constantToString(index, Const.CONSTANT_Class)).append(">").append(verbose ? " (" + index + ")" : "");
442 break;
443
444
445
446 case Const.INVOKESPECIAL:
447 case Const.INVOKESTATIC:
448 index = bytes.readUnsignedShort();
449 final Constant c = constantPool.getConstant(index);
450
451
452 buf.append("\t").append(constantPool.constantToString(index, c.getTag())).append(verbose ? " (" + index + ")" : "");
453 break;
454 case Const.INVOKEVIRTUAL:
455 index = bytes.readUnsignedShort();
456 buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_Methodref)).append(verbose ? " (" + index + ")" : "");
457 break;
458 case Const.INVOKEINTERFACE:
459 index = bytes.readUnsignedShort();
460 final int nargs = bytes.readUnsignedByte();
461 buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InterfaceMethodref)).append(verbose ? " (" + index + ")\t" : "")
462 .append(nargs).append("\t").append(bytes.readUnsignedByte());
463 break;
464 case Const.INVOKEDYNAMIC:
465 index = bytes.readUnsignedShort();
466 buf.append("\t").append(constantPool.constantToString(index, Const.CONSTANT_InvokeDynamic)).append(verbose ? " (" + index + ")\t" : "")
467 .append(bytes.readUnsignedByte())
468 .append(bytes.readUnsignedByte());
469 break;
470
471
472
473 case Const.LDC_W:
474 case Const.LDC2_W:
475 index = bytes.readUnsignedShort();
476 buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
477 .append(verbose ? " (" + index + ")" : "");
478 break;
479 case Const.LDC:
480 index = bytes.readUnsignedByte();
481 buf.append("\t\t").append(constantPool.constantToString(index, constantPool.getConstant(index).getTag()))
482 .append(verbose ? " (" + index + ")" : "");
483 break;
484
485
486
487 case Const.ANEWARRAY:
488 index = bytes.readUnsignedShort();
489 buf.append("\t\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">")
490 .append(verbose ? " (" + index + ")" : "");
491 break;
492
493
494
495 case Const.MULTIANEWARRAY: {
496 index = bytes.readUnsignedShort();
497 final int dimensions = bytes.readUnsignedByte();
498 buf.append("\t<").append(compactClassName(constantPool.getConstantString(index, Const.CONSTANT_Class), false)).append(">\t").append(dimensions)
499 .append(verbose ? " (" + index + ")" : "");
500 }
501 break;
502
503
504
505 case Const.IINC:
506 if (wide) {
507 vindex = bytes.readUnsignedShort();
508 constant = bytes.readShort();
509 wide = false;
510 } else {
511 vindex = bytes.readUnsignedByte();
512 constant = bytes.readByte();
513 }
514 buf.append("\t\t%").append(vindex).append("\t").append(constant);
515 break;
516 default:
517 if (Const.getNoOfOperands(opcode) > 0) {
518 for (int i = 0; i < Const.getOperandTypeCount(opcode); i++) {
519 buf.append("\t\t");
520 switch (Const.getOperandType(opcode, i)) {
521 case Const.T_BYTE:
522 buf.append(bytes.readByte());
523 break;
524 case Const.T_SHORT:
525 buf.append(bytes.readShort());
526 break;
527 case Const.T_INT:
528 buf.append(bytes.readInt());
529 break;
530 default:
531 throw new IllegalStateException("Unreachable default case reached!");
532 }
533 }
534 }
535 }
536 return buf.toString();
537 }
538
539
540
541
542
543
544
545 public static String compactClassName(final String str) {
546 return compactClassName(str, true);
547 }
548
549
550
551
552
553
554
555
556
557 public static String compactClassName(final String str, final boolean chopit) {
558 return compactClassName(str, "java.lang.", chopit);
559 }
560
561
562
563
564
565
566
567
568
569
570 public static String compactClassName(String str, final String prefix, final boolean chopit) {
571 final int len = prefix.length();
572 str = pathToPackage(str);
573
574 if (chopit && str.startsWith(prefix) && str.substring(len).indexOf('.') == -1) {
575 str = str.substring(len);
576 }
577 return str;
578 }
579
580
581
582
583 public static String convertString(final String label) {
584 final char[] ch = label.toCharArray();
585 final StringBuilder buf = new StringBuilder();
586 for (final char element : ch) {
587 switch (element) {
588 case '\n':
589 buf.append("\\n");
590 break;
591 case '\r':
592 buf.append("\\r");
593 break;
594 case '\"':
595 buf.append("\\\"");
596 break;
597 case '\'':
598 buf.append("\\'");
599 break;
600 case '\\':
601 buf.append("\\\\");
602 break;
603 default:
604 buf.append(element);
605 break;
606 }
607 }
608 return buf.toString();
609 }
610
611 private static int countBrackets(final String brackets) {
612 final char[] chars = brackets.toCharArray();
613 int count = 0;
614 boolean open = false;
615 for (final char c : chars) {
616 switch (c) {
617 case '[':
618 if (open) {
619 throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
620 }
621 open = true;
622 break;
623 case ']':
624 if (!open) {
625 throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
626 }
627 open = false;
628 count++;
629 break;
630 default:
631
632 break;
633 }
634 }
635 if (open) {
636 throw new IllegalArgumentException("Illegally nested brackets:" + brackets);
637 }
638 return count;
639 }
640
641
642
643
644
645
646
647
648
649 public static byte[] decode(final String s, final boolean uncompress) throws IOException {
650 byte[] bytes;
651 try (JavaReader jr = new JavaReader(new CharArrayReader(s.toCharArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
652 int ch;
653 while ((ch = jr.read()) >= 0) {
654 bos.write(ch);
655 }
656 bytes = bos.toByteArray();
657 }
658 if (uncompress) {
659 final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
660 final byte[] tmp = new byte[bytes.length * 3];
661 int count = 0;
662 int b;
663 while ((b = gis.read()) >= 0) {
664 tmp[count++] = (byte) b;
665 }
666 bytes = Arrays.copyOf(tmp, count);
667 }
668 return bytes;
669 }
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690 public static String encode(byte[] bytes, final boolean compress) throws IOException {
691 if (compress) {
692 try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos)) {
693 gos.write(bytes, 0, bytes.length);
694 gos.close();
695 bytes = baos.toByteArray();
696 }
697 }
698 final CharArrayWriter caw = new CharArrayWriter();
699 try (JavaWriter jw = new JavaWriter(caw)) {
700 for (final byte b : bytes) {
701 final int in = b & 0x000000ff;
702 jw.write(in);
703 }
704 }
705 return caw.toString();
706 }
707
708
709
710
711
712
713
714
715
716
717 public static String fillup(final String str, final int length, final boolean leftJustify, final char fill) {
718 final int len = length - str.length();
719 final char[] buf = ArrayFill.fill(new char[Math.max(len, 0)], fill);
720 if (leftJustify) {
721 return str + new String(buf);
722 }
723 return new String(buf) + str;
724 }
725
726
727
728
729
730
731
732
733
734
735 public static String format(final int i, final int length, final boolean leftJustify, final char fill) {
736 return fillup(Integer.toString(i), length, leftJustify, fill);
737 }
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770 public static String getSignature(String type) {
771 final StringBuilder buf = new StringBuilder();
772 final char[] chars = type.toCharArray();
773 boolean charFound = false;
774 boolean delim = false;
775 int index = -1;
776 loop: for (int i = 0; i < chars.length; i++) {
777 switch (chars[i]) {
778 case ' ':
779 case '\t':
780 case '\n':
781 case '\r':
782 case '\f':
783 if (charFound) {
784 delim = true;
785 }
786 break;
787 case '[':
788 if (!charFound) {
789 throw new IllegalArgumentException("Illegal type: " + type);
790 }
791 index = i;
792 break loop;
793 default:
794 charFound = true;
795 if (!delim) {
796 buf.append(chars[i]);
797 }
798 }
799 }
800 int brackets = 0;
801 if (index > 0) {
802 brackets = countBrackets(type.substring(index));
803 }
804 type = buf.toString();
805 buf.setLength(0);
806 for (int i = 0; i < brackets; i++) {
807 buf.append('[');
808 }
809 boolean found = false;
810 for (int i = Const.T_BOOLEAN; i <= Const.T_VOID && !found; i++) {
811 if (Const.getTypeName(i).equals(type)) {
812 found = true;
813 buf.append(Const.getShortTypeName(i));
814 }
815 }
816 if (!found) {
817 buf.append('L').append(packageToPath(type)).append(';');
818 }
819 return buf.toString();
820 }
821
822
823
824
825
826
827 public static boolean isJavaIdentifierPart(final char ch) {
828 return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '_';
829 }
830
831
832
833
834 public static boolean isSet(final int flag, final int i) {
835 return (flag & pow2(i)) != 0;
836 }
837
838
839
840
841
842
843
844
845 public static String[] methodSignatureArgumentTypes(final String signature) throws ClassFormatException {
846 return methodSignatureArgumentTypes(signature, true);
847 }
848
849
850
851
852
853
854
855
856
857 public static String[] methodSignatureArgumentTypes(final String signature, final boolean chopit) throws ClassFormatException {
858 final List<String> vec = new ArrayList<>();
859 int index;
860 try {
861
862 index = signature.indexOf('(') + 1;
863 if (index <= 0) {
864 throw new InvalidMethodSignatureException(signature);
865 }
866 while (signature.charAt(index) != ')') {
867 vec.add(typeSignatureToString(signature.substring(index), chopit));
868
869 index += unwrap(CONSUMER_CHARS);
870 }
871 } catch (final StringIndexOutOfBoundsException e) {
872 throw new InvalidMethodSignatureException(signature, e);
873 }
874 return vec.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
875 }
876
877
878
879
880
881
882
883
884 public static String methodSignatureReturnType(final String signature) throws ClassFormatException {
885 return methodSignatureReturnType(signature, true);
886 }
887
888
889
890
891
892
893
894
895
896 public static String methodSignatureReturnType(final String signature, final boolean chopit) throws ClassFormatException {
897 int index;
898 String type;
899 try {
900
901 index = signature.lastIndexOf(')') + 1;
902 if (index <= 0) {
903 throw new InvalidMethodSignatureException(signature);
904 }
905 type = typeSignatureToString(signature.substring(index), chopit);
906 } catch (final StringIndexOutOfBoundsException e) {
907 throw new InvalidMethodSignatureException(signature, e);
908 }
909 return type;
910 }
911
912
913
914
915
916
917
918
919
920 public static String methodSignatureToString(final String signature, final String name, final String access) {
921 return methodSignatureToString(signature, name, access, true);
922 }
923
924
925
926
927
928
929
930
931
932
933 public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit) {
934 return methodSignatureToString(signature, name, access, chopit, null);
935 }
936
937
938
939
940
941
942
943
944
945
946
947
948
949 public static String methodSignatureToString(final String signature, final String name, final String access, final boolean chopit,
950 final LocalVariableTable vars) throws ClassFormatException {
951 final StringBuilder buf = new StringBuilder("(");
952 String type;
953 int index;
954 int varIndex = access.contains("static") ? 0 : 1;
955 try {
956
957 index = signature.indexOf('(') + 1;
958 if (index <= 0) {
959 throw new InvalidMethodSignatureException(signature);
960 }
961 while (signature.charAt(index) != ')') {
962 final String paramType = typeSignatureToString(signature.substring(index), chopit);
963 buf.append(paramType);
964 if (vars != null) {
965 final LocalVariable l = vars.getLocalVariable(varIndex, 0);
966 if (l != null) {
967 buf.append(" ").append(l.getName());
968 }
969 } else {
970 buf.append(" arg").append(varIndex);
971 }
972 if ("double".equals(paramType) || "long".equals(paramType)) {
973 varIndex += 2;
974 } else {
975 varIndex++;
976 }
977 buf.append(", ");
978
979 index += unwrap(CONSUMER_CHARS);
980 }
981 index++;
982
983 type = typeSignatureToString(signature.substring(index), chopit);
984 } catch (final StringIndexOutOfBoundsException e) {
985 throw new InvalidMethodSignatureException(signature, e);
986 }
987
988 if (buf.length() > 1) {
989 buf.setLength(buf.length() - 2);
990 }
991 buf.append(")");
992 return access + (!access.isEmpty() ? " " : "") +
993 type + " " + name + buf.toString();
994 }
995
996
997
998
999
1000
1001
1002
1003
1004
1005 public static String methodTypeToSignature(final String ret, final String[] argv) throws ClassFormatException {
1006 final StringBuilder buf = new StringBuilder("(");
1007 String str;
1008 if (argv != null) {
1009 for (final String element : argv) {
1010 str = getSignature(element);
1011 if (str.endsWith("V")) {
1012 throw new ClassFormatException("Invalid type: " + element);
1013 }
1014 buf.append(str);
1015 }
1016 }
1017 str = getSignature(ret);
1018 buf.append(")").append(str);
1019 return buf.toString();
1020 }
1021
1022
1023
1024
1025
1026
1027
1028
1029 public static String packageToPath(final String name) {
1030 return name.replace('.', '/');
1031 }
1032
1033
1034
1035
1036
1037
1038
1039
1040 public static String pathToPackage(final String str) {
1041 return str.replace('/', '.');
1042 }
1043
1044 private static int pow2(final int n) {
1045 return 1 << n;
1046 }
1047
1048 public static String printArray(final Object[] obj) {
1049 return printArray(obj, true);
1050 }
1051
1052 public static String printArray(final Object[] obj, final boolean braces) {
1053 return printArray(obj, braces, false);
1054 }
1055
1056 public static String printArray(final Object[] obj, final boolean braces, final boolean quote) {
1057 if (obj == null) {
1058 return null;
1059 }
1060 final StringBuilder buf = new StringBuilder();
1061 if (braces) {
1062 buf.append('{');
1063 }
1064 for (int i = 0; i < obj.length; i++) {
1065 if (obj[i] != null) {
1066 buf.append(quote ? "\"" : "").append(obj[i]).append(quote ? "\"" : "");
1067 } else {
1068 buf.append("null");
1069 }
1070 if (i < obj.length - 1) {
1071 buf.append(", ");
1072 }
1073 }
1074 if (braces) {
1075 buf.append('}');
1076 }
1077 return buf.toString();
1078 }
1079
1080 public static void printArray(final PrintStream out, final Object[] obj) {
1081 out.println(printArray(obj, true));
1082 }
1083
1084 public static void printArray(final PrintWriter out, final Object[] obj) {
1085 out.println(printArray(obj, true));
1086 }
1087
1088
1089
1090
1091
1092
1093
1094
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)) {
1101 final StringBuilder buf = new StringBuilder();
1102 oldIndex = 0;
1103
1104 while ((index = str.indexOf(old, oldIndex)) != -1) {
1105 buf.append(str, oldIndex, index);
1106 buf.append(new_);
1107 oldIndex = index + old.length();
1108 }
1109 buf.append(str.substring(oldIndex));
1110 str = buf.toString();
1111 }
1112 } catch (final StringIndexOutOfBoundsException e) {
1113 System.err.println(e);
1114 }
1115 return str;
1116 }
1117
1118
1119
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
1133
1134 public static int setBit(final int flag, final int i) {
1135 return flag | pow2(i);
1136 }
1137
1138
1139
1140
1141
1142
1143
1144
1145 public static String signatureToString(final String signature) {
1146 return signatureToString(signature, true);
1147 }
1148
1149
1150
1151
1152
1153
1154
1155
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
1163 typeParams = typeParamTypesToString(signature, chopit);
1164 index += unwrap(CONSUMER_CHARS);
1165 }
1166 if (signature.charAt(index) == '(') {
1167
1168
1169 type = typeParams + typeSignaturesToString(signature.substring(index), chopit, ')');
1170 index += unwrap(CONSUMER_CHARS);
1171
1172 type += typeSignatureToString(signature.substring(index), chopit);
1173 index += unwrap(CONSUMER_CHARS);
1174
1175 return type;
1176 }
1177
1178 type = typeSignatureToString(signature.substring(index), chopit);
1179 index += unwrap(CONSUMER_CHARS);
1180 if (typeParams.isEmpty() && index == signature.length()) {
1181
1182 return type;
1183 }
1184
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);
1192 }
1193 while (index < signature.length()) {
1194 typeClass.append(", ");
1195 typeClass.append(typeSignatureToString(signature.substring(index), chopit));
1196 index += unwrap(CONSUMER_CHARS);
1197 }
1198 return typeClass.toString();
1199 }
1200
1201
1202
1203
1204
1205
1206
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
1226
1227
1228
1229
1230
1231
1232
1233 public static byte typeOfMethodSignature(final String signature) throws ClassFormatException {
1234 int index;
1235 try {
1236 if (signature.charAt(0) != '(') {
1237 throw new InvalidMethodSignatureException(signature);
1238 }
1239 index = signature.lastIndexOf(')') + 1;
1240 return typeOfSignature(signature.substring(index));
1241 } catch (final StringIndexOutOfBoundsException e) {
1242 throw new InvalidMethodSignatureException(signature, e);
1243 }
1244 }
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255 public static byte typeOfSignature(final String signature) throws ClassFormatException {
1256 try {
1257 switch (signature.charAt(0)) {
1258 case 'B':
1259 return Const.T_BYTE;
1260 case 'C':
1261 return Const.T_CHAR;
1262 case 'D':
1263 return Const.T_DOUBLE;
1264 case 'F':
1265 return Const.T_FLOAT;
1266 case 'I':
1267 return Const.T_INT;
1268 case 'J':
1269 return Const.T_LONG;
1270 case 'L':
1271 case 'T':
1272 return Const.T_REFERENCE;
1273 case '[':
1274 return Const.T_ARRAY;
1275 case 'V':
1276 return Const.T_VOID;
1277 case 'Z':
1278 return Const.T_BOOLEAN;
1279 case 'S':
1280 return Const.T_SHORT;
1281 case '!':
1282 case '+':
1283 case '*':
1284 return typeOfSignature(signature.substring(1));
1285 default:
1286 throw new InvalidMethodSignatureException(signature);
1287 }
1288 } catch (final StringIndexOutOfBoundsException e) {
1289 throw new InvalidMethodSignatureException(signature, e);
1290 }
1291 }
1292
1293
1294
1295
1296
1297
1298
1299
1300 private static String typeParamTypesToString(final String signature, final boolean chopit) {
1301
1302 final StringBuilder typeParams = new StringBuilder("<");
1303 int index = 1;
1304
1305 typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
1306 index += unwrap(CONSUMER_CHARS);
1307
1308 while (signature.charAt(index) != '>') {
1309 typeParams.append(", ");
1310 typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
1311 index += unwrap(CONSUMER_CHARS);
1312 }
1313 wrap(CONSUMER_CHARS, index + 1);
1314 return typeParams.append(">").toString();
1315 }
1316
1317
1318
1319
1320
1321
1322
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
1330 final StringBuilder typeParam = new StringBuilder(signature.substring(0, index));
1331 index++;
1332 if (signature.charAt(index) != ':') {
1333
1334 typeParam.append(" extends ");
1335 typeParam.append(typeSignatureToString(signature.substring(index), chopit));
1336 index += unwrap(CONSUMER_CHARS);
1337 }
1338
1339 while (signature.charAt(index) == ':') {
1340 index++;
1341 typeParam.append(" & ");
1342 typeParam.append(typeSignatureToString(signature.substring(index), chopit));
1343 index += unwrap(CONSUMER_CHARS);
1344 }
1345 wrap(CONSUMER_CHARS, index);
1346 return typeParam.toString();
1347 }
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357 private static String typeSignaturesToString(final String signature, final boolean chopit, final char term) {
1358
1359 final StringBuilder typeList = new StringBuilder(signature.substring(0, 1));
1360 int index = 1;
1361
1362 if (signature.charAt(index) != term) {
1363 typeList.append(typeSignatureToString(signature.substring(index), chopit));
1364 index += unwrap(CONSUMER_CHARS);
1365 }
1366
1367 while (signature.charAt(index) != term) {
1368 typeList.append(", ");
1369 typeList.append(typeSignatureToString(signature.substring(index), chopit));
1370 index += unwrap(CONSUMER_CHARS);
1371 }
1372 wrap(CONSUMER_CHARS, index + 1);
1373 return typeList.append(term).toString();
1374 }
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387 public static String typeSignatureToString(final String signature, final boolean chopit) throws ClassFormatException {
1388
1389 wrap(CONSUMER_CHARS, 1);
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': {
1405 final int index = signature.indexOf(';');
1406 if (index < 0) {
1407 throw new ClassFormatException("Invalid type variable signature: " + signature);
1408 }
1409
1410 wrap(CONSUMER_CHARS, index + 1);
1411 return compactClassName(signature.substring(1, index), chopit);
1412 }
1413 case 'L': {
1414
1415
1416 int fromIndex = signature.indexOf('<');
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);
1426 if (index < 0) {
1427 throw new ClassFormatException("Invalid signature: " + signature);
1428 }
1429
1430
1431 final int bracketIndex = signature.substring(0, index).indexOf('<');
1432 if (bracketIndex < 0) {
1433
1434 wrap(CONSUMER_CHARS, index + 1);
1435 return compactClassName(signature.substring(1, index), chopit);
1436 }
1437
1438 fromIndex = signature.indexOf(';');
1439 if (fromIndex < 0) {
1440 throw new ClassFormatException("Invalid signature: " + signature);
1441 }
1442 if (fromIndex < bracketIndex) {
1443
1444 wrap(CONSUMER_CHARS, fromIndex + 1);
1445 return compactClassName(signature.substring(1, fromIndex), chopit);
1446 }
1447
1448
1449
1450 final StringBuilder type = new StringBuilder(compactClassName(signature.substring(1, bracketIndex), chopit)).append("<");
1451 int consumedChars = bracketIndex + 1;
1452
1453
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
1463 if (signature.charAt(consumedChars) == '*') {
1464 type.append("?");
1465 consumedChars++;
1466 } else {
1467 type.append(typeSignatureToString(signature.substring(consumedChars), chopit));
1468
1469 consumedChars = unwrap(CONSUMER_CHARS) + consumedChars;
1470 wrap(CONSUMER_CHARS, consumedChars);
1471 }
1472
1473
1474 while (signature.charAt(consumedChars) != '>') {
1475 type.append(", ");
1476
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
1490 consumedChars = unwrap(CONSUMER_CHARS) + consumedChars;
1491 wrap(CONSUMER_CHARS, consumedChars);
1492 }
1493 }
1494
1495
1496 consumedChars++;
1497 type.append(">");
1498
1499 if (signature.charAt(consumedChars) == '.') {
1500
1501 type.append(".");
1502
1503
1504 type.append(typeSignatureToString("L" + signature.substring(consumedChars + 1), chopit));
1505
1506
1507
1508 consumedChars = unwrap(CONSUMER_CHARS) + consumedChars;
1509 wrap(CONSUMER_CHARS, consumedChars);
1510 return type.toString();
1511 }
1512 if (signature.charAt(consumedChars) != ';') {
1513 throw new ClassFormatException("Invalid signature: " + signature);
1514 }
1515 wrap(CONSUMER_CHARS, consumedChars + 1);
1516 return type.toString();
1517 }
1518 case 'S':
1519 return "short";
1520 case 'Z':
1521 return "boolean";
1522 case '[': {
1523 int n;
1524 StringBuilder brackets;
1525 String type;
1526 int consumedChars;
1527 brackets = new StringBuilder();
1528
1529 for (n = 0; signature.charAt(n) == '['; n++) {
1530 brackets.append("[]");
1531 }
1532 consumedChars = n;
1533
1534 type = typeSignatureToString(signature.substring(n), chopit);
1535
1536
1537 final int temp = unwrap(CONSUMER_CHARS) + consumedChars;
1538 wrap(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) {
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 }