/
Utility.java
1660 lines (1532 loc) · 63.4 KB
/
Utility.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.bcel.internal.classfile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.FilterReader;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.sun.org.apache.bcel.internal.Const;
import com.sun.org.apache.bcel.internal.util.ByteSequence;
/**
* Utility functions that do not really belong to any class in particular.
*
* @LastModified: June 2021
*/
// @since 6.0 methods are no longer final
public abstract class Utility {
private static int unwrap( final ThreadLocal<Integer> tl ) {
return tl.get();
}
private static void wrap( final ThreadLocal<Integer> tl, final int value ) {
tl.set(value);
}
/* How many chars have been consumed
* during parsing in typeSignatureToString().
* Read by methodSignatureToString().
* Set by side effect, but only internally.
*/
private static ThreadLocal<Integer> consumed_chars = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
/* The `WIDE' instruction is used in the
* byte code to allow 16-bit wide indices
* for local variables. This opcode
* precedes an `ILOAD', e.g.. The opcode
* immediately following takes an extra
* byte which is combined with the
* following byte to form a
* 16-bit value.
*/
private static boolean wide = false;
/**
* Convert bit field of flags into string such as `static final'.
*
* @param access_flags Access flags
* @return String representation of flags
*/
public static String accessToString( final int access_flags ) {
return accessToString(access_flags, false);
}
/**
* Convert bit field of flags into string such as `static final'.
*
* Special case: Classes compiled with new compilers and with the
* `ACC_SUPER' flag would be said to be "synchronized". This is
* because SUN used the same value for the flags `ACC_SUPER' and
* `ACC_SYNCHRONIZED'.
*
* @param access_flags Access flags
* @param for_class access flags are for class qualifiers ?
* @return String representation of flags
*/
public static String accessToString( final int access_flags, final boolean for_class ) {
final StringBuilder buf = new StringBuilder();
int p = 0;
for (int i = 0; p < Const.MAX_ACC_FLAG_I; i++) { // Loop through known flags
p = pow2(i);
if ((access_flags & p) != 0) {
/* Special case: Classes compiled with new compilers and with the
* `ACC_SUPER' flag would be said to be "synchronized". This is
* because SUN used the same value for the flags `ACC_SUPER' and
* `ACC_SYNCHRONIZED'.
*/
if (for_class && ((p == Const.ACC_SUPER) || (p == Const.ACC_INTERFACE))) {
continue;
}
buf.append(Const.getAccessName(i)).append(" ");
}
}
return buf.toString().trim();
}
/**
* @param access_flags the class flags
*
* @return "class" or "interface", depending on the ACC_INTERFACE flag
*/
public static String classOrInterface( final int access_flags ) {
return ((access_flags & Const.ACC_INTERFACE) != 0) ? "interface" : "class";
}
/**
* Disassemble a byte array of JVM byte codes starting from code line
* `index' and return the disassembled string representation. Decode only
* `num' opcodes (including their operands), use -1 if you want to
* decompile everything.
*
* @param code byte code array
* @param constant_pool Array of constants
* @param index offset in `code' array
* <EM>(number of opcodes, not bytes!)</EM>
* @param length number of opcodes to decompile, -1 for all
* @param verbose be verbose, e.g. print constant pool index
* @return String representation of byte codes
*/
public static String codeToString( final byte[] code, final ConstantPool constant_pool, final int index,
final int length, final boolean verbose ) {
final StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient // CHECKSTYLE IGNORE MagicNumber
try (ByteSequence stream = new ByteSequence(code)) {
for (int i = 0; i < index; i++) {
codeToString(stream, constant_pool, verbose);
}
for (int i = 0; stream.available() > 0; i++) {
if ((length < 0) || (i < length)) {
final String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
buf.append(indices).append(codeToString(stream, constant_pool, verbose)).append('\n');
}
}
} catch (final IOException e) {
throw new ClassFormatException("Byte code error: " + buf.toString(), e);
}
return buf.toString();
}
public static String codeToString( final byte[] code, final ConstantPool constant_pool, final int index, final int length ) {
return codeToString(code, constant_pool, index, length, true);
}
/**
* Disassemble a stream of byte codes and return the
* string representation.
*
* @param bytes stream of bytes
* @param constant_pool Array of constants
* @param verbose be verbose, e.g. print constant pool index
* @return String representation of byte code
*
* @throws IOException if a failure from reading from the bytes argument occurs
*/
@SuppressWarnings("fallthrough") // by design for case Const.INSTANCEOF
public static String codeToString(final ByteSequence bytes, final ConstantPool constant_pool,
final boolean verbose) throws IOException {
final short opcode = (short) bytes.readUnsignedByte();
int default_offset = 0;
int low;
int high;
int npairs;
int index;
int vindex;
int constant;
int[] match;
int[] jump_table;
int no_pad_bytes = 0;
int offset;
final StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode));
/* Special case: Skip (0-3) padding bytes, i.e., the
* following bytes are 4-byte-aligned
*/
if ((opcode == Const.TABLESWITCH) || (opcode == Const.LOOKUPSWITCH)) {
final int remainder = bytes.getIndex() % 4;
no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder;
for (int i = 0; i < no_pad_bytes; i++) {
byte b;
if ((b = bytes.readByte()) != 0) {
System.err.println("Warning: Padding byte != 0 in "
+ Const.getOpcodeName(opcode) + ":" + b);
}
}
// Both cases have a field default_offset in common
default_offset = bytes.readInt();
}
switch (opcode) {
/* Table switch has variable length arguments.
*/
case Const.TABLESWITCH:
low = bytes.readInt();
high = bytes.readInt();
offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
default_offset += offset;
buf.append("\tdefault = ").append(default_offset).append(", low = ").append(low)
.append(", high = ").append(high).append("(");
jump_table = new int[high - low + 1];
for (int i = 0; i < jump_table.length; i++) {
jump_table[i] = offset + bytes.readInt();
buf.append(jump_table[i]);
if (i < jump_table.length - 1) {
buf.append(", ");
}
}
buf.append(")");
break;
/* Lookup switch has variable length arguments.
*/
case Const.LOOKUPSWITCH: {
npairs = bytes.readInt();
offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
match = new int[npairs];
jump_table = new int[npairs];
default_offset += offset;
buf.append("\tdefault = ").append(default_offset).append(", npairs = ").append(
npairs).append(" (");
for (int i = 0; i < npairs; i++) {
match[i] = bytes.readInt();
jump_table[i] = offset + bytes.readInt();
buf.append("(").append(match[i]).append(", ").append(jump_table[i]).append(")");
if (i < npairs - 1) {
buf.append(", ");
}
}
buf.append(")");
}
break;
/* Two address bytes + offset from start of byte stream form the
* jump target
*/
case Const.GOTO:
case Const.IFEQ:
case Const.IFGE:
case Const.IFGT:
case Const.IFLE:
case Const.IFLT:
case Const.JSR:
case Const.IFNE:
case Const.IFNONNULL:
case Const.IFNULL:
case Const.IF_ACMPEQ:
case Const.IF_ACMPNE:
case Const.IF_ICMPEQ:
case Const.IF_ICMPGE:
case Const.IF_ICMPGT:
case Const.IF_ICMPLE:
case Const.IF_ICMPLT:
case Const.IF_ICMPNE:
buf.append("\t\t#").append((bytes.getIndex() - 1) + bytes.readShort());
break;
/* 32-bit wide jumps
*/
case Const.GOTO_W:
case Const.JSR_W:
buf.append("\t\t#").append((bytes.getIndex() - 1) + bytes.readInt());
break;
/* Index byte references local variable (register)
*/
case Const.ALOAD:
case Const.ASTORE:
case Const.DLOAD:
case Const.DSTORE:
case Const.FLOAD:
case Const.FSTORE:
case Const.ILOAD:
case Const.ISTORE:
case Const.LLOAD:
case Const.LSTORE:
case Const.RET:
if (wide) {
vindex = bytes.readUnsignedShort();
wide = false; // Clear flag
} else {
vindex = bytes.readUnsignedByte();
}
buf.append("\t\t%").append(vindex);
break;
/*
* Remember wide byte which is used to form a 16-bit address in the
* following instruction. Relies on that the method is called again with
* the following opcode.
*/
case Const.WIDE:
wide = true;
buf.append("\t(wide)");
break;
/* Array of basic type.
*/
case Const.NEWARRAY:
buf.append("\t\t<").append(Const.getTypeName(bytes.readByte())).append(">");
break;
/* Access object/class fields.
*/
case Const.GETFIELD:
case Const.GETSTATIC:
case Const.PUTFIELD:
case Const.PUTSTATIC:
index = bytes.readUnsignedShort();
buf.append("\t\t").append(
constant_pool.constantToString(index, Const.CONSTANT_Fieldref)).append(
verbose ? " (" + index + ")" : "");
break;
/* Operands are references to classes in constant pool
*/
case Const.NEW:
case Const.CHECKCAST:
buf.append("\t");
//$FALL-THROUGH$
case Const.INSTANCEOF:
index = bytes.readUnsignedShort();
buf.append("\t<").append(
constant_pool.constantToString(index, Const.CONSTANT_Class))
.append(">").append(verbose ? " (" + index + ")" : "");
break;
/* Operands are references to methods in constant pool
*/
case Const.INVOKESPECIAL:
case Const.INVOKESTATIC:
index = bytes.readUnsignedShort();
final Constant c = constant_pool.getConstant(index);
// With Java8 operand may be either a CONSTANT_Methodref
// or a CONSTANT_InterfaceMethodref. (markro)
buf.append("\t").append(
constant_pool.constantToString(index, c.getTag()))
.append(verbose ? " (" + index + ")" : "");
break;
case Const.INVOKEVIRTUAL:
index = bytes.readUnsignedShort();
buf.append("\t").append(
constant_pool.constantToString(index, Const.CONSTANT_Methodref))
.append(verbose ? " (" + index + ")" : "");
break;
case Const.INVOKEINTERFACE:
index = bytes.readUnsignedShort();
final int nargs = bytes.readUnsignedByte(); // historical, redundant
buf.append("\t").append(
constant_pool
.constantToString(index, Const.CONSTANT_InterfaceMethodref))
.append(verbose ? " (" + index + ")\t" : "").append(nargs).append("\t")
.append(bytes.readUnsignedByte()); // Last byte is a reserved space
break;
case Const.INVOKEDYNAMIC:
index = bytes.readUnsignedShort();
buf.append("\t").append(
constant_pool
.constantToString(index, Const.CONSTANT_InvokeDynamic))
.append(verbose ? " (" + index + ")\t" : "")
.append(bytes.readUnsignedByte()) // Thrid byte is a reserved space
.append(bytes.readUnsignedByte()); // Last byte is a reserved space
break;
/* Operands are references to items in constant pool
*/
case Const.LDC_W:
case Const.LDC2_W:
index = bytes.readUnsignedShort();
buf.append("\t\t").append(
constant_pool.constantToString(index, constant_pool.getConstant(index)
.getTag())).append(verbose ? " (" + index + ")" : "");
break;
case Const.LDC:
index = bytes.readUnsignedByte();
buf.append("\t\t").append(
constant_pool.constantToString(index, constant_pool.getConstant(index)
.getTag())).append(verbose ? " (" + index + ")" : "");
break;
/* Array of references.
*/
case Const.ANEWARRAY:
index = bytes.readUnsignedShort();
buf.append("\t\t<").append(
compactClassName(constant_pool.getConstantString(index,
Const.CONSTANT_Class), false)).append(">").append(
verbose ? " (" + index + ")" : "");
break;
/* Multidimensional array of references.
*/
case Const.MULTIANEWARRAY: {
index = bytes.readUnsignedShort();
final int dimensions = bytes.readUnsignedByte();
buf.append("\t<").append(
compactClassName(constant_pool.getConstantString(index,
Const.CONSTANT_Class), false)).append(">\t").append(dimensions)
.append(verbose ? " (" + index + ")" : "");
}
break;
/* Increment local variable.
*/
case Const.IINC:
if (wide) {
vindex = bytes.readUnsignedShort();
constant = bytes.readShort();
wide = false;
} else {
vindex = bytes.readUnsignedByte();
constant = bytes.readByte();
}
buf.append("\t\t%").append(vindex).append("\t").append(constant);
break;
default:
if (Const.getNoOfOperands(opcode) > 0) {
for (int i = 0; i < Const.getOperandTypeCount(opcode); i++) {
buf.append("\t\t");
switch (Const.getOperandType(opcode, i)) {
case Const.T_BYTE:
buf.append(bytes.readByte());
break;
case Const.T_SHORT:
buf.append(bytes.readShort());
break;
case Const.T_INT:
buf.append(bytes.readInt());
break;
default: // Never reached
throw new IllegalStateException("Unreachable default case reached!");
}
}
}
}
return buf.toString();
}
public static String codeToString( final ByteSequence bytes, final ConstantPool constant_pool )
throws IOException {
return codeToString(bytes, constant_pool, true);
}
/**
* Shorten long class names, <em>java/lang/String</em> becomes
* <em>String</em>.
*
* @param str The long class name
* @return Compacted class name
*/
public static String compactClassName( final String str ) {
return compactClassName(str, true);
}
/**
* Shorten long class names, <em>java/lang/String</em> becomes
* <em>java.lang.String</em>,
* e.g.. If <em>chopit</em> is <em>true</em> the prefix <em>java.lang</em>
* is also removed.
*
* @param str The long class name
* @param chopit flag that determines whether chopping is executed or not
* @return Compacted class name
*/
public static String compactClassName( final String str, final boolean chopit ) {
return compactClassName(str, "java.lang.", chopit);
}
/**
* Shorten long class name <em>str</em>, i.e., chop off the <em>prefix</em>,
* if the
* class name starts with this string and the flag <em>chopit</em> is true.
* Slashes <em>/</em> are converted to dots <em>.</em>.
*
* @param str The long class name
* @param prefix The prefix the get rid off
* @param chopit flag that determines whether chopping is executed or not
* @return Compacted class name
*/
public static String compactClassName( String str, final String prefix, final boolean chopit ) {
final int len = prefix.length();
str = str.replace('/', '.'); // Is `/' on all systems, even DOS
if (chopit) {
// If string starts with `prefix' and contains no further dots
if (str.startsWith(prefix) && (str.substring(len).indexOf('.') == -1)) {
str = str.substring(len);
}
}
return str;
}
/**
* @return `flag' with bit `i' set to 1
*/
public static int setBit( final int flag, final int i ) {
return flag | pow2(i);
}
/**
* @return `flag' with bit `i' set to 0
*/
public static int clearBit( final int flag, final int i ) {
final int bit = pow2(i);
return (flag & bit) == 0 ? flag : flag ^ bit;
}
/**
* @return true, if bit `i' in `flag' is set
*/
public static boolean isSet( final int flag, final int i ) {
return (flag & pow2(i)) != 0;
}
/**
* Converts string containing the method return and argument types
* to a byte code method signature.
*
* @param ret Return type of method
* @param argv Types of method arguments
* @return Byte code representation of method signature
*
* @throws ClassFormatException if the signature is for Void
*/
public static String methodTypeToSignature( final String ret, final String[] argv )
throws ClassFormatException {
final StringBuilder buf = new StringBuilder("(");
String str;
if (argv != null) {
for (final String element : argv) {
str = getSignature(element);
if (str.endsWith("V")) {
throw new ClassFormatException("Invalid type: " + element);
}
buf.append(str);
}
}
str = getSignature(ret);
buf.append(")").append(str);
return buf.toString();
}
/**
* Converts argument list portion of method signature to string with all class names compacted.
*
* @param signature Method signature
* @return String Array of argument types
* @throws ClassFormatException
*/
public static String[] methodSignatureArgumentTypes( final String signature )
throws ClassFormatException {
return methodSignatureArgumentTypes(signature, true);
}
/**
* Converts argument list portion of method signature to string.
*
* @param signature Method signature
* @param chopit flag that determines whether chopping is executed or not
* @return String Array of argument types
* @throws ClassFormatException
*/
public static String[] methodSignatureArgumentTypes( final String signature, final boolean chopit )
throws ClassFormatException {
final List<String> vec = new ArrayList<>();
int index;
try {
// Skip any type arguments to read argument declarations between `(' and `)'
index = signature.indexOf('(') + 1;
if (index <= 0) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
while (signature.charAt(index) != ')') {
vec.add(typeSignatureToString(signature.substring(index), chopit));
//corrected concurrent private static field acess
index += unwrap(consumed_chars); // update position
}
} catch (final StringIndexOutOfBoundsException e) { // Should never occur
throw new ClassFormatException("Invalid method signature: " + signature, e);
}
return vec.toArray(new String[vec.size()]);
}
/**
* Converts return type portion of method signature to string with all class names compacted.
*
* @param signature Method signature
* @return String representation of method return type
* @throws ClassFormatException
*/
public static String methodSignatureReturnType( final String signature ) throws ClassFormatException {
return methodSignatureReturnType(signature, true);
}
/**
* Converts return type portion of method signature to string.
*
* @param signature Method signature
* @param chopit flag that determines whether chopping is executed or not
* @return String representation of method return type
* @throws ClassFormatException
*/
public static String methodSignatureReturnType( final String signature, final boolean chopit ) throws ClassFormatException {
int index;
String type;
try {
// Read return type after `)'
index = signature.lastIndexOf(')') + 1;
if (index <= 0) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
type = typeSignatureToString(signature.substring(index), chopit);
} catch (final StringIndexOutOfBoundsException e) { // Should never occur
throw new ClassFormatException("Invalid method signature: " + signature, e);
}
return type;
}
/**
* Converts method signature to string with all class names compacted.
*
* @param signature to convert
* @param name of method
* @param access flags of method
* @return Human readable signature
*/
public static String methodSignatureToString( final String signature, final String name, final String access ) {
return methodSignatureToString(signature, name, access, true);
}
/**
* Converts method signature to string.
*
* @param signature to convert
* @param name of method
* @param access flags of method
* @param chopit flag that determines whether chopping is executed or not
* @return Human readable signature
*/
public static String methodSignatureToString( final String signature, final String name, final String access, final boolean chopit ) {
return methodSignatureToString(signature, name, access, chopit, null);
}
/**
* This method converts a method signature string into a Java type declaration like
* `void main(String[])' and throws a `ClassFormatException' when the parsed
* type is invalid.
*
* @param signature Method signature
* @param name Method name
* @param access Method access rights
* @param chopit flag that determines whether chopping is executed or not
* @param vars the LocalVariableTable for the method
* @return Java type declaration
* @throws ClassFormatException
*/
public static String methodSignatureToString( final String signature, final String name,
final String access, final boolean chopit, final LocalVariableTable vars ) throws ClassFormatException {
final StringBuilder buf = new StringBuilder("(");
String type;
int index;
int var_index = access.contains("static") ? 0 : 1;
try {
// Skip any type arguments to read argument declarations between `(' and `)'
index = signature.indexOf('(') + 1;
if (index <= 0) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
while (signature.charAt(index) != ')') {
final String param_type = typeSignatureToString(signature.substring(index), chopit);
buf.append(param_type);
if (vars != null) {
final LocalVariable l = vars.getLocalVariable(var_index, 0);
if (l != null) {
buf.append(" ").append(l.getName());
}
} else {
buf.append(" arg").append(var_index);
}
if ("double".equals(param_type) || "long".equals(param_type)) {
var_index += 2;
} else {
var_index++;
}
buf.append(", ");
//corrected concurrent private static field acess
index += unwrap(consumed_chars); // update position
}
index++; // update position
// Read return type after `)'
type = typeSignatureToString(signature.substring(index), chopit);
} catch (final StringIndexOutOfBoundsException e) { // Should never occur
throw new ClassFormatException("Invalid method signature: " + signature, e);
}
// ignore any throws information in the signature
if (buf.length() > 1) {
buf.setLength(buf.length() - 2);
}
buf.append(")");
return access + ((access.length() > 0) ? " " : "") + // May be an empty string
type + " " + name + buf.toString();
}
private static int pow2( final int n ) {
return 1 << n;
}
/**
* Replace all occurrences of <em>old</em> in <em>str</em> with <em>new</em>.
*
* @param str String to permute
* @param old String to be replaced
* @param new_ Replacement string
* @return new String object
*/
public static String replace( String str, final String old, final String new_ ) {
int index;
int old_index;
try {
if (str.contains(old)) { // `old' found in str
final StringBuilder buf = new StringBuilder();
old_index = 0; // String start offset
// While we have something to replace
while ((index = str.indexOf(old, old_index)) != -1) {
buf.append(str.substring(old_index, index)); // append prefix
buf.append(new_); // append replacement
old_index = index + old.length(); // Skip `old'.length chars
}
buf.append(str.substring(old_index)); // append rest of string
str = buf.toString();
}
} catch (final StringIndexOutOfBoundsException e) { // Should not occur
System.err.println(e);
}
return str;
}
/**
* WARNING:
*
* There is some nomenclature confusion through much of the BCEL code base with
* respect to the terms Descriptor and Signature. For the offical definitions see:
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3">
* Descriptors in The Java Virtual Machine Specification</a>
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.9.1">
* Signatures in The Java Virtual Machine Specification</a>
*
* In brief, a descriptor is a string representing the type of a field or method.
* Signatures are similar, but more complex. Signatures are used to encode declarations
* written in the Java programming language that use types outside the type system of the
* Java Virtual Machine. They are used to describe the type of any class, interface,
* constructor, method or field whose declaration uses type variables or parameterized types.
*
* To parse a descriptor, call typeSignatureToString.
* To parse a signature, call signatureToString.
*
* Note that if the signature string is a single, non-generic item, the call to
* signatureToString reduces to a call to typeSignatureToString.
* Also note, that if you only wish to parse the first item in a longer signature
* string, you should call typeSignatureToString directly.
*/
/**
* Converts a signature to a string with all class names compacted.
* Class, Method and Type signatures are supported.
* Enum and Interface signatures are not supported.
*
* @param signature signature to convert
* @return String containg human readable signature
*/
public static String signatureToString( final String signature ) {
return signatureToString(signature, true);
}
/**
* Converts a signature to a string.
* Class, Method and Type signatures are supported.
* Enum and Interface signatures are not supported.
*
* @param signature signature to convert
* @param chopit flag that determines whether chopping is executed or not
* @return String containg human readable signature
*/
public static String signatureToString( final String signature, final boolean chopit ) {
String type = "";
String typeParams = "";
int index = 0;
if (signature.charAt(0) == '<') {
// we have type paramters
typeParams = typeParamTypesToString(signature, chopit);
index += unwrap(consumed_chars); // update position
}
if (signature.charAt(index) == '(') {
// We have a Method signature.
// add types of arguments
type = typeParams + typeSignaturesToString(signature.substring(index), chopit, ')');
index += unwrap(consumed_chars); // update position
// add return type
type = type + typeSignatureToString(signature.substring(index), chopit);
index += unwrap(consumed_chars); // update position
// ignore any throws information in the signature
return type;
}
// Could be Class or Type...
type = typeSignatureToString(signature.substring(index), chopit);
index += unwrap(consumed_chars); // update position
if ((typeParams.length() == 0) && (index == signature.length())) {
// We have a Type signature.
return type;
}
// We have a Class signature.
final StringBuilder typeClass = new StringBuilder(typeParams);
typeClass.append(" extends ");
typeClass.append(type);
if (index < signature.length()) {
typeClass.append(" implements ");
typeClass.append(typeSignatureToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
}
while (index < signature.length()) {
typeClass.append(", ");
typeClass.append(typeSignatureToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
}
return typeClass.toString();
}
/**
* Converts a type parameter list signature to a string.
*
* @param signature signature to convert
* @param chopit flag that determines whether chopping is executed or not
* @return String containg human readable signature
*/
private static String typeParamTypesToString( final String signature, final boolean chopit ) {
// The first character is guranteed to be '<'
final StringBuilder typeParams = new StringBuilder("<");
int index = 1; // skip the '<'
// get the first TypeParameter
typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
// are there more TypeParameters?
while (signature.charAt(index) != '>') {
typeParams.append(", ");
typeParams.append(typeParamTypeToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
}
wrap(consumed_chars, index + 1); // account for the '>' char
return typeParams.append(">").toString();
}
/**
* Converts a type parameter signature to a string.
*
* @param signature signature to convert
* @param chopit flag that determines whether chopping is executed or not
* @return String containg human readable signature
*/
private static String typeParamTypeToString( final String signature, final boolean chopit ) {
int index = signature.indexOf(':');
if (index <= 0) {
throw new ClassFormatException("Invalid type parameter signature: " + signature);
}
// get the TypeParameter identifier
final StringBuilder typeParam = new StringBuilder(signature.substring(0, index));
index++; // account for the ':'
if (signature.charAt(index) != ':') {
// we have a class bound
typeParam.append(" extends ");
typeParam.append(typeSignatureToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
}
// look for interface bounds
while (signature.charAt(index) == ':') {
index++; // skip over the ':'
typeParam.append(" & ");
typeParam.append(typeSignatureToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
}
wrap(consumed_chars, index);
return typeParam.toString();
}
/**
* Converts a list of type signatures to a string.
*
* @param signature signature to convert
* @param chopit flag that determines whether chopping is executed or not
* @param term character indicating the end of the list
* @return String containg human readable signature
*/
private static String typeSignaturesToString( final String signature, final boolean chopit, final char term ) {
// The first character will be an 'open' that matches the 'close' contained in term.
final StringBuilder typeList = new StringBuilder(signature.substring(0, 1));
int index = 1; // skip the 'open' character
// get the first Type in the list
if (signature.charAt(index) != term) {
typeList.append(typeSignatureToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
}
// are there more types in the list?
while (signature.charAt(index) != term) {
typeList.append(", ");
typeList.append(typeSignatureToString(signature.substring(index), chopit));
index += unwrap(consumed_chars); // update position
}
wrap(consumed_chars, index + 1); // account for the term char
return typeList.append(term).toString();
}
/**
*
* This method converts a type signature string into a Java type declaration such as
* `String[]' and throws a `ClassFormatException' when the parsed type is invalid.
*
* @param signature type signature
* @param chopit flag that determines whether chopping is executed or not
* @return string containing human readable type signature
* @throws ClassFormatException
* @since 6.4.0
*/
public static String typeSignatureToString( final String signature, final boolean chopit ) throws ClassFormatException {
//corrected concurrent private static field acess
wrap(consumed_chars, 1); // This is the default, read just one char like `B'
try {
switch (signature.charAt(0)) {
case 'B':
return "byte";
case 'C':
return "char";
case 'D':
return "double";
case 'F':
return "float";
case 'I':
return "int";
case 'J':
return "long";
case 'T': { // TypeVariableSignature
final int index = signature.indexOf(';'); // Look for closing `;'
if (index < 0) {
throw new ClassFormatException("Invalid type variable signature: " + signature);
}
//corrected concurrent private static field acess
wrap(consumed_chars, index + 1); // "Tblabla;" `T' and `;' are removed
return compactClassName(signature.substring(1, index), chopit);
}
case 'L': { // Full class name
// should this be a while loop? can there be more than
// one generic clause? (markro)
int fromIndex = signature.indexOf('<'); // generic type?
if (fromIndex < 0) {
fromIndex = 0;
} else {
fromIndex = signature.indexOf('>', fromIndex);
if (fromIndex < 0) {
throw new ClassFormatException("Invalid signature: " + signature);
}
}
final int index = signature.indexOf(';', fromIndex); // Look for closing `;'
if (index < 0) {