-
Notifications
You must be signed in to change notification settings - Fork 857
/
ClassFileWriter.java
4564 lines (4285 loc) · 164 KB
/
ClassFileWriter.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
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.classfile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import org.mozilla.javascript.ObjArray;
import org.mozilla.javascript.UintMap;
/**
* ClassFileWriter
*
* A ClassFileWriter is used to write a Java class file. Methods are
* provided to create fields and methods, and within methods to write
* Java bytecodes.
*
* @author Roger Lawrence
*/
public class ClassFileWriter {
/**
* Thrown for cases where the error in generating the class file is due to a program size
* constraints rather than a likely bug in the compiler.
*/
public static class ClassFileFormatException extends RuntimeException {
private static final long serialVersionUID = 1263998431033790599L;
ClassFileFormatException(String message) {
super(message);
}
}
/**
* Construct a ClassFileWriter for a class.
*
* @param className the name of the class to write, including full package qualification.
* @param superClassName the name of the superclass of the class to write, including full package
* qualification.
* @param sourceFileName the name of the source file to use for producing debug information, or
* null if debug information is not desired
*/
public ClassFileWriter(String className, String superClassName, String sourceFileName) {
generatedClassName = className;
itsConstantPool = new ConstantPool(this);
itsThisClassIndex = itsConstantPool.addClass(className);
itsSuperClassIndex = itsConstantPool.addClass(superClassName);
if (sourceFileName != null)
itsSourceFileNameIndex = itsConstantPool.addUtf8(sourceFileName);
// All "new" implementations are supposed to output ACC_SUPER as a
// class flag. This is specified in the first JVM spec, so it should
// be old enough that it's okay to always set it.
itsFlags = ACC_PUBLIC | ACC_SUPER;
}
public final String getClassName() {
return generatedClassName;
}
/**
* Add an interface implemented by this class.
*
* This method may be called multiple times for classes that implement multiple interfaces.
*
* @param interfaceName a name of an interface implemented by the class being written, including
* full package qualification.
*/
public void addInterface(String interfaceName) {
short interfaceIndex = itsConstantPool.addClass(interfaceName);
itsInterfaces.add(Short.valueOf(interfaceIndex));
}
public static final short
ACC_PUBLIC = 0x0001,
ACC_PRIVATE = 0x0002,
ACC_PROTECTED = 0x0004,
ACC_STATIC = 0x0008,
ACC_FINAL = 0x0010,
ACC_SUPER = 0x0020,
ACC_SYNCHRONIZED = 0x0020,
ACC_VOLATILE = 0x0040,
ACC_TRANSIENT = 0x0080,
ACC_NATIVE = 0x0100,
ACC_ABSTRACT = 0x0400;
/**
* Set the class's flags.
*
* Flags must be a set of the following flags, bitwise or'd together: ACC_PUBLIC ACC_PRIVATE
* ACC_PROTECTED ACC_FINAL ACC_ABSTRACT TODO: check that this is the appropriate set
*
* @param flags the set of class flags to set
*/
public void setFlags(short flags) {
itsFlags = flags;
}
static String getSlashedForm(String name) {
return name.replace('.', '/');
}
/**
* Convert Java class name in dot notation into "Lname-with-dots-replaced-by-slashes;" form
* suitable for use as JVM type signatures.
*/
public static String classNameToSignature(String name) {
int nameLength = name.length();
int colonPos = 1 + nameLength;
char[] buf = new char[colonPos + 1];
buf[0] = 'L';
buf[colonPos] = ';';
name.getChars(0, nameLength, buf, 1);
for (int i = 1; i != colonPos; ++i) {
if (buf[i] == '.') {
buf[i] = '/';
}
}
return new String(buf, 0, colonPos + 1);
}
/**
* Add a field to the class.
*
* @param fieldName the name of the field
* @param type the type of the field using ...
* @param flags the attributes of the field, such as ACC_PUBLIC, etc. bitwise or'd together
*/
public void addField(String fieldName, String type, short flags) {
short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
short typeIndex = itsConstantPool.addUtf8(type);
itsFields.add(new ClassFileField(fieldNameIndex, typeIndex, flags));
}
/**
* Add a field to the class.
*
* @param fieldName the name of the field
* @param type the type of the field using ...
* @param flags the attributes of the field, such as ACC_PUBLIC, etc. bitwise or'd together
* @param value an initial integral value
*/
public void addField(String fieldName, String type, short flags,
int value) {
short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
short typeIndex = itsConstantPool.addUtf8(type);
ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex,
flags);
field.setAttributes(itsConstantPool.addUtf8("ConstantValue"),
(short) 0,
(short) 0,
itsConstantPool.addConstant(value));
itsFields.add(field);
}
/**
* Add a field to the class.
*
* @param fieldName the name of the field
* @param type the type of the field using ...
* @param flags the attributes of the field, such as ACC_PUBLIC, etc. bitwise or'd together
* @param value an initial long value
*/
public void addField(String fieldName, String type, short flags,
long value) {
short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
short typeIndex = itsConstantPool.addUtf8(type);
ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex,
flags);
field.setAttributes(itsConstantPool.addUtf8("ConstantValue"),
(short) 0,
(short) 2,
itsConstantPool.addConstant(value));
itsFields.add(field);
}
/**
* Add a field to the class.
*
* @param fieldName the name of the field
* @param type the type of the field using ...
* @param flags the attributes of the field, such as ACC_PUBLIC, etc. bitwise or'd together
* @param value an initial double value
*/
public void addField(String fieldName, String type, short flags,
double value) {
short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
short typeIndex = itsConstantPool.addUtf8(type);
ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex,
flags);
field.setAttributes(itsConstantPool.addUtf8("ConstantValue"),
(short) 0,
(short) 2,
itsConstantPool.addConstant(value));
itsFields.add(field);
}
/**
* Add Information about java variable to use when generating the local variable table.
*
* @param name variable name.
* @param type variable type as bytecode descriptor string.
* @param startPC the starting bytecode PC where this variable is live, or -1 if it does not have
* a Java register.
* @param register the Java register number of variable or -1 if it does not have a Java
* register.
*/
public void addVariableDescriptor(String name, String type, int startPC, int register) {
int nameIndex = itsConstantPool.addUtf8(name);
int descriptorIndex = itsConstantPool.addUtf8(type);
int[] chunk = {nameIndex, descriptorIndex, startPC, register};
if (itsVarDescriptors == null) {
itsVarDescriptors = new ObjArray();
}
itsVarDescriptors.add(chunk);
}
/**
* Add a method and begin adding code.
*
* This method must be called before other methods for adding code, exception tables, etc. can be
* invoked.
*
* @param methodName the name of the method
* @param type a string representing the type
* @param flags the attributes of the field, such as ACC_PUBLIC, etc. bitwise or'd together
*/
public void startMethod(String methodName, String type, short flags) {
short methodNameIndex = itsConstantPool.addUtf8(methodName);
short typeIndex = itsConstantPool.addUtf8(type);
itsCurrentMethod = new ClassFileMethod(methodName, methodNameIndex,
type, typeIndex, flags);
itsJumpFroms = new UintMap();
itsMethods.add(itsCurrentMethod);
addSuperBlockStart(0);
}
/**
* Complete generation of the method.
*
* After this method is called, no more code can be added to the method begun with
* <code>startMethod</code>.
*
* @param maxLocals the maximum number of local variable slots (a.k.a. Java registers) used by the
* method
*/
public void stopMethod(short maxLocals) {
if (itsCurrentMethod == null)
throw new IllegalStateException("No method to stop");
fixLabelGotos();
itsMaxLocals = maxLocals;
StackMapTable stackMap = null;
if (GenerateStackMap) {
finalizeSuperBlockStarts();
stackMap = new StackMapTable();
stackMap.generate();
}
int lineNumberTableLength = 0;
if (itsLineNumberTable != null) {
// 6 bytes for the attribute header
// 2 bytes for the line number count
// 4 bytes for each entry
lineNumberTableLength = 6 + 2 + (itsLineNumberTableTop * 4);
}
int variableTableLength = 0;
if (itsVarDescriptors != null) {
// 6 bytes for the attribute header
// 2 bytes for the variable count
// 10 bytes for each entry
variableTableLength = 6 + 2 + (itsVarDescriptors.size() * 10);
}
int stackMapTableLength = 0;
if (stackMap != null) {
int stackMapWriteSize = stackMap.computeWriteSize();
if (stackMapWriteSize > 0) {
stackMapTableLength = 6 + stackMapWriteSize;
}
}
int attrLength = 2 + // attribute_name_index
4 + // attribute_length
2 + // max_stack
2 + // max_locals
4 + // code_length
itsCodeBufferTop +
2 + // exception_table_length
(itsExceptionTableTop * 8) +
2 + // attributes_count
lineNumberTableLength +
variableTableLength +
stackMapTableLength;
if (attrLength > 65536) {
// See http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html,
// section 4.10, "The amount of code per non-native, non-abstract
// method is limited to 65536 bytes...
throw new ClassFileFormatException("generated bytecode for method exceeds 64K limit.");
}
byte[] codeAttribute = new byte[attrLength];
int index = 0;
int codeAttrIndex = itsConstantPool.addUtf8("Code");
index = putInt16(codeAttrIndex, codeAttribute, index);
attrLength -= 6; // discount the attribute header
index = putInt32(attrLength, codeAttribute, index);
index = putInt16(itsMaxStack, codeAttribute, index);
index = putInt16(itsMaxLocals, codeAttribute, index);
index = putInt32(itsCodeBufferTop, codeAttribute, index);
System.arraycopy(itsCodeBuffer, 0, codeAttribute, index,
itsCodeBufferTop);
index += itsCodeBufferTop;
if (itsExceptionTableTop > 0) {
index = putInt16(itsExceptionTableTop, codeAttribute, index);
for (int i = 0; i < itsExceptionTableTop; i++) {
ExceptionTableEntry ete = itsExceptionTable[i];
int startPC = getLabelPC(ete.itsStartLabel);
int endPC = getLabelPC(ete.itsEndLabel);
int handlerPC = getLabelPC(ete.itsHandlerLabel);
short catchType = ete.itsCatchType;
if (startPC == -1)
throw new IllegalStateException("start label not defined");
if (endPC == -1)
throw new IllegalStateException("end label not defined");
if (handlerPC == -1)
throw new IllegalStateException(
"handler label not defined");
// no need to cast to short here, the putInt16 uses only
// the short part of the int
index = putInt16(startPC, codeAttribute, index);
index = putInt16(endPC, codeAttribute, index);
index = putInt16(handlerPC, codeAttribute, index);
index = putInt16(catchType, codeAttribute, index);
}
} else {
// write 0 as exception table length
index = putInt16(0, codeAttribute, index);
}
int attributeCount = 0;
if (itsLineNumberTable != null)
attributeCount++;
if (itsVarDescriptors != null)
attributeCount++;
if (stackMapTableLength > 0) {
attributeCount++;
}
index = putInt16(attributeCount, codeAttribute, index);
if (itsLineNumberTable != null) {
int lineNumberTableAttrIndex
= itsConstantPool.addUtf8("LineNumberTable");
index = putInt16(lineNumberTableAttrIndex, codeAttribute, index);
int tableAttrLength = 2 + (itsLineNumberTableTop * 4);
index = putInt32(tableAttrLength, codeAttribute, index);
index = putInt16(itsLineNumberTableTop, codeAttribute, index);
for (int i = 0; i < itsLineNumberTableTop; i++) {
index = putInt32(itsLineNumberTable[i], codeAttribute, index);
}
}
if (itsVarDescriptors != null) {
int variableTableAttrIndex
= itsConstantPool.addUtf8("LocalVariableTable");
index = putInt16(variableTableAttrIndex, codeAttribute, index);
int varCount = itsVarDescriptors.size();
int tableAttrLength = 2 + (varCount * 10);
index = putInt32(tableAttrLength, codeAttribute, index);
index = putInt16(varCount, codeAttribute, index);
for (int i = 0; i < varCount; i++) {
int[] chunk = (int[]) itsVarDescriptors.get(i);
int nameIndex = chunk[0];
int descriptorIndex = chunk[1];
int startPC = chunk[2];
int register = chunk[3];
int length = itsCodeBufferTop - startPC;
index = putInt16(startPC, codeAttribute, index);
index = putInt16(length, codeAttribute, index);
index = putInt16(nameIndex, codeAttribute, index);
index = putInt16(descriptorIndex, codeAttribute, index);
index = putInt16(register, codeAttribute, index);
}
}
if (stackMapTableLength > 0) {
int stackMapTableAttrIndex =
itsConstantPool.addUtf8("StackMapTable");
index = putInt16(stackMapTableAttrIndex, codeAttribute, index);
index = stackMap.write(codeAttribute, index);
}
itsCurrentMethod.setCodeAttribute(codeAttribute);
itsExceptionTable = null;
itsExceptionTableTop = 0;
itsLineNumberTableTop = 0;
itsCodeBufferTop = 0;
itsCurrentMethod = null;
itsMaxStack = 0;
itsStackTop = 0;
itsLabelTableTop = 0;
itsFixupTableTop = 0;
itsVarDescriptors = null;
itsSuperBlockStarts = null;
itsSuperBlockStartsTop = 0;
itsJumpFroms = null;
}
/**
* Add the single-byte opcode to the current method.
*
* @param theOpCode the opcode of the bytecode
*/
public void add(int theOpCode) {
if (opcodeCount(theOpCode) != 0)
throw new IllegalArgumentException("Unexpected operands");
int newStack = itsStackTop + stackChange(theOpCode);
if (newStack < 0 || Short.MAX_VALUE < newStack)
badStack(newStack);
if (DEBUGCODE)
System.out.println("Add " + bytecodeStr(theOpCode));
addToCodeBuffer(theOpCode);
itsStackTop = (short) newStack;
if (newStack > itsMaxStack)
itsMaxStack = (short) newStack;
if (DEBUGSTACK) {
System.out.println("After " + bytecodeStr(theOpCode)
+ " stack = " + itsStackTop);
}
if (theOpCode == ByteCode.ATHROW) {
addSuperBlockStart(itsCodeBufferTop);
}
}
/**
* Add a single-operand opcode to the current method.
*
* @param theOpCode the opcode of the bytecode
* @param theOperand the operand of the bytecode
*/
public void add(int theOpCode, int theOperand) {
if (DEBUGCODE) {
System.out.println("Add " + bytecodeStr(theOpCode)
+ ", " + Integer.toHexString(theOperand));
}
int newStack = itsStackTop + stackChange(theOpCode);
if (newStack < 0 || Short.MAX_VALUE < newStack)
badStack(newStack);
switch (theOpCode) {
case ByteCode.GOTO:
// This is necessary because dead code is seemingly being
// generated and Sun's verifier is expecting type state to be
// placed even at dead blocks of code.
addSuperBlockStart(itsCodeBufferTop + 3);
// fall through...
case ByteCode.IFEQ:
case ByteCode.IFNE:
case ByteCode.IFLT:
case ByteCode.IFGE:
case ByteCode.IFGT:
case ByteCode.IFLE:
case ByteCode.IF_ICMPEQ:
case ByteCode.IF_ICMPNE:
case ByteCode.IF_ICMPLT:
case ByteCode.IF_ICMPGE:
case ByteCode.IF_ICMPGT:
case ByteCode.IF_ICMPLE:
case ByteCode.IF_ACMPEQ:
case ByteCode.IF_ACMPNE:
case ByteCode.JSR:
case ByteCode.IFNULL:
case ByteCode.IFNONNULL: {
if ((theOperand & 0x80000000) != 0x80000000) {
if ((theOperand < 0) || (theOperand > 65535))
throw new IllegalArgumentException(
"Bad label for branch");
}
int branchPC = itsCodeBufferTop;
addToCodeBuffer(theOpCode);
if ((theOperand & 0x80000000) != 0x80000000) {
// hard displacement
addToCodeInt16(theOperand);
int target = theOperand + branchPC;
addSuperBlockStart(target);
itsJumpFroms.put(target, branchPC);
} else { // a label
int targetPC = getLabelPC(theOperand);
if (DEBUGLABELS) {
int theLabel = theOperand & 0x7FFFFFFF;
System.out.println("Fixing branch to " +
theLabel + " at " + targetPC +
" from " + branchPC);
}
if (targetPC != -1) {
int offset = targetPC - branchPC;
addToCodeInt16(offset);
addSuperBlockStart(targetPC);
itsJumpFroms.put(targetPC, branchPC);
} else {
addLabelFixup(theOperand, branchPC + 1);
addToCodeInt16(0);
}
}
}
break;
case ByteCode.BIPUSH:
if ((byte) theOperand != theOperand)
throw new IllegalArgumentException("out of range byte");
addToCodeBuffer(theOpCode);
addToCodeBuffer((byte) theOperand);
break;
case ByteCode.SIPUSH:
if ((short) theOperand != theOperand)
throw new IllegalArgumentException("out of range short");
addToCodeBuffer(theOpCode);
addToCodeInt16(theOperand);
break;
case ByteCode.NEWARRAY:
if (!(0 <= theOperand && theOperand < 256))
throw new IllegalArgumentException("out of range index");
addToCodeBuffer(theOpCode);
addToCodeBuffer(theOperand);
break;
case ByteCode.GETFIELD:
case ByteCode.PUTFIELD:
if (!(0 <= theOperand && theOperand < 65536))
throw new IllegalArgumentException("out of range field");
addToCodeBuffer(theOpCode);
addToCodeInt16(theOperand);
break;
case ByteCode.LDC:
case ByteCode.LDC_W:
case ByteCode.LDC2_W:
if (!(0 <= theOperand && theOperand < 65536))
throw new ClassFileFormatException("out of range index");
if (theOperand >= 256
|| theOpCode == ByteCode.LDC_W
|| theOpCode == ByteCode.LDC2_W) {
if (theOpCode == ByteCode.LDC) {
addToCodeBuffer(ByteCode.LDC_W);
} else {
addToCodeBuffer(theOpCode);
}
addToCodeInt16(theOperand);
} else {
addToCodeBuffer(theOpCode);
addToCodeBuffer(theOperand);
}
break;
case ByteCode.RET:
case ByteCode.ILOAD:
case ByteCode.LLOAD:
case ByteCode.FLOAD:
case ByteCode.DLOAD:
case ByteCode.ALOAD:
case ByteCode.ISTORE:
case ByteCode.LSTORE:
case ByteCode.FSTORE:
case ByteCode.DSTORE:
case ByteCode.ASTORE:
if (theOperand < 0 || 65536 <= theOperand)
throw new ClassFileFormatException("out of range variable");
if (theOperand >= 256) {
addToCodeBuffer(ByteCode.WIDE);
addToCodeBuffer(theOpCode);
addToCodeInt16(theOperand);
} else {
addToCodeBuffer(theOpCode);
addToCodeBuffer(theOperand);
}
break;
default:
throw new IllegalArgumentException(
"Unexpected opcode for 1 operand");
}
itsStackTop = (short) newStack;
if (newStack > itsMaxStack)
itsMaxStack = (short) newStack;
if (DEBUGSTACK) {
System.out.println("After " + bytecodeStr(theOpCode)
+ " stack = " + itsStackTop);
}
}
/**
* Generate the load constant bytecode for the given integer.
*
* @param k the constant
*/
public void addLoadConstant(int k) {
switch (k) {
case 0:
add(ByteCode.ICONST_0);
break;
case 1:
add(ByteCode.ICONST_1);
break;
case 2:
add(ByteCode.ICONST_2);
break;
case 3:
add(ByteCode.ICONST_3);
break;
case 4:
add(ByteCode.ICONST_4);
break;
case 5:
add(ByteCode.ICONST_5);
break;
default:
add(ByteCode.LDC, itsConstantPool.addConstant(k));
break;
}
}
/**
* Generate the load constant bytecode for the given long.
*
* @param k the constant
*/
public void addLoadConstant(long k) {
add(ByteCode.LDC2_W, itsConstantPool.addConstant(k));
}
/**
* Generate the load constant bytecode for the given float.
*
* @param k the constant
*/
public void addLoadConstant(float k) {
add(ByteCode.LDC, itsConstantPool.addConstant(k));
}
/**
* Generate the load constant bytecode for the given double.
*
* @param k the constant
*/
public void addLoadConstant(double k) {
add(ByteCode.LDC2_W, itsConstantPool.addConstant(k));
}
/**
* Generate the load constant bytecode for the given string.
*
* @param k the constant
*/
public void addLoadConstant(String k) {
add(ByteCode.LDC, itsConstantPool.addConstant(k));
}
/**
* Add the given two-operand bytecode to the current method.
*
* @param theOpCode the opcode of the bytecode
* @param theOperand1 the first operand of the bytecode
* @param theOperand2 the second operand of the bytecode
*/
public void add(int theOpCode, int theOperand1, int theOperand2) {
if (DEBUGCODE) {
System.out.println("Add " + bytecodeStr(theOpCode)
+ ", " + Integer.toHexString(theOperand1)
+ ", " + Integer.toHexString(theOperand2));
}
int newStack = itsStackTop + stackChange(theOpCode);
if (newStack < 0 || Short.MAX_VALUE < newStack)
badStack(newStack);
if (theOpCode == ByteCode.IINC) {
if (theOperand1 < 0 || 65536 <= theOperand1)
throw new ClassFileFormatException("out of range variable");
if (theOperand2 < 0 || 65536 <= theOperand2)
throw new ClassFileFormatException("out of range increment");
if (theOperand1 > 255 || theOperand2 > 127) {
addToCodeBuffer(ByteCode.WIDE);
addToCodeBuffer(ByteCode.IINC);
addToCodeInt16(theOperand1);
addToCodeInt16(theOperand2);
} else {
addToCodeBuffer(ByteCode.IINC);
addToCodeBuffer(theOperand1);
addToCodeBuffer(theOperand2);
}
} else if (theOpCode == ByteCode.MULTIANEWARRAY) {
if (!(0 <= theOperand1 && theOperand1 < 65536))
throw new IllegalArgumentException("out of range index");
if (!(0 <= theOperand2 && theOperand2 < 256))
throw new IllegalArgumentException("out of range dimensions");
addToCodeBuffer(ByteCode.MULTIANEWARRAY);
addToCodeInt16(theOperand1);
addToCodeBuffer(theOperand2);
} else {
throw new IllegalArgumentException(
"Unexpected opcode for 2 operands");
}
itsStackTop = (short) newStack;
if (newStack > itsMaxStack)
itsMaxStack = (short) newStack;
if (DEBUGSTACK) {
System.out.println("After " + bytecodeStr(theOpCode)
+ " stack = " + itsStackTop);
}
}
public void add(int theOpCode, String className) {
if (DEBUGCODE) {
System.out.println("Add " + bytecodeStr(theOpCode)
+ ", " + className);
}
int newStack = itsStackTop + stackChange(theOpCode);
if (newStack < 0 || Short.MAX_VALUE < newStack)
badStack(newStack);
switch (theOpCode) {
case ByteCode.NEW:
case ByteCode.ANEWARRAY:
case ByteCode.CHECKCAST:
case ByteCode.INSTANCEOF: {
short classIndex = itsConstantPool.addClass(className);
addToCodeBuffer(theOpCode);
addToCodeInt16(classIndex);
}
break;
default:
throw new IllegalArgumentException(
"bad opcode for class reference");
}
itsStackTop = (short) newStack;
if (newStack > itsMaxStack)
itsMaxStack = (short) newStack;
if (DEBUGSTACK) {
System.out.println("After " + bytecodeStr(theOpCode)
+ " stack = " + itsStackTop);
}
}
public void add(int theOpCode, String className, String fieldName,
String fieldType) {
if (DEBUGCODE) {
System.out.println("Add " + bytecodeStr(theOpCode)
+ ", " + className + ", " + fieldName + ", " + fieldType);
}
int newStack = itsStackTop + stackChange(theOpCode);
char fieldTypeChar = fieldType.charAt(0);
int fieldSize = (fieldTypeChar == 'J' || fieldTypeChar == 'D')
? 2 : 1;
switch (theOpCode) {
case ByteCode.GETFIELD:
case ByteCode.GETSTATIC:
newStack += fieldSize;
break;
case ByteCode.PUTSTATIC:
case ByteCode.PUTFIELD:
newStack -= fieldSize;
break;
default:
throw new IllegalArgumentException(
"bad opcode for field reference");
}
if (newStack < 0 || Short.MAX_VALUE < newStack)
badStack(newStack);
short fieldRefIndex = itsConstantPool.addFieldRef(className,
fieldName, fieldType);
addToCodeBuffer(theOpCode);
addToCodeInt16(fieldRefIndex);
itsStackTop = (short) newStack;
if (newStack > itsMaxStack)
itsMaxStack = (short) newStack;
if (DEBUGSTACK) {
System.out.println("After " + bytecodeStr(theOpCode)
+ " stack = " + itsStackTop);
}
}
public void addInvoke(int theOpCode, String className, String methodName,
String methodType) {
if (DEBUGCODE) {
System.out.println("Add " + bytecodeStr(theOpCode)
+ ", " + className + ", " + methodName + ", "
+ methodType);
}
int parameterInfo = sizeOfParameters(methodType);
int parameterCount = parameterInfo >>> 16;
int stackDiff = (short) parameterInfo;
int newStack = itsStackTop + stackDiff;
newStack += stackChange(theOpCode); // adjusts for 'this'
if (newStack < 0 || Short.MAX_VALUE < newStack)
badStack(newStack);
switch (theOpCode) {
case ByteCode.INVOKEVIRTUAL:
case ByteCode.INVOKESPECIAL:
case ByteCode.INVOKESTATIC:
case ByteCode.INVOKEINTERFACE: {
addToCodeBuffer(theOpCode);
if (theOpCode == ByteCode.INVOKEINTERFACE) {
short ifMethodRefIndex
= itsConstantPool.addInterfaceMethodRef(
className, methodName,
methodType);
addToCodeInt16(ifMethodRefIndex);
addToCodeBuffer(parameterCount + 1);
addToCodeBuffer(0);
} else {
short methodRefIndex = itsConstantPool.addMethodRef(
className, methodName,
methodType);
addToCodeInt16(methodRefIndex);
}
}
break;
default:
throw new IllegalArgumentException(
"bad opcode for method reference");
}
itsStackTop = (short) newStack;
if (newStack > itsMaxStack)
itsMaxStack = (short) newStack;
if (DEBUGSTACK) {
System.out.println("After " + bytecodeStr(theOpCode)
+ " stack = " + itsStackTop);
}
}
public void addInvokeDynamic(String methodName, String methodType,
MHandle bsm, Object... bsmArgs) {
if (DEBUGCODE) {
System.out.println("Add invokedynamic, " + methodName + ", " + methodType);
}
// JDK 1.7 major class file version is required for invokedynamic
if (MajorVersion < 51) {
throw new RuntimeException(
"Please build and run with JDK 1.7 for invokedynamic support");
}
int parameterInfo = sizeOfParameters(methodType);
// int parameterCount = parameterInfo >>> 16;
int stackDiff = (short) parameterInfo;
int newStack = itsStackTop + stackDiff;
if (newStack < 0 || Short.MAX_VALUE < newStack)
badStack(newStack);
BootstrapEntry bsmEntry = new BootstrapEntry(bsm, bsmArgs);
if (itsBootstrapMethods == null) {
itsBootstrapMethods = new ObjArray();
}
int bootstrapIndex = itsBootstrapMethods.indexOf(bsmEntry);
if (bootstrapIndex == -1) {
bootstrapIndex = itsBootstrapMethods.size();
itsBootstrapMethods.add(bsmEntry);
itsBootstrapMethodsLength += bsmEntry.code.length;
}
short invokedynamicIndex = itsConstantPool.addInvokeDynamic(
methodName, methodType, bootstrapIndex);
addToCodeBuffer(ByteCode.INVOKEDYNAMIC);
addToCodeInt16(invokedynamicIndex);
addToCodeInt16(0);
itsStackTop = (short) newStack;
if (newStack > itsMaxStack)
itsMaxStack = (short) newStack;
if (DEBUGSTACK) {
System.out.println("After invokedynamic stack = " + itsStackTop);
}
}
/**
* Generate code to load the given integer on stack.
*
* @param k the constant
*/
public void addPush(int k) {
if ((byte) k == k) {
if (k == -1) {
add(ByteCode.ICONST_M1);
} else if (0 <= k && k <= 5) {
add((byte) (ByteCode.ICONST_0 + k));
} else {
add(ByteCode.BIPUSH, (byte) k);
}
} else if ((short) k == k) {
add(ByteCode.SIPUSH, (short) k);
} else {
addLoadConstant(k);
}
}
public void addPush(boolean k) {
add(k ? ByteCode.ICONST_1 : ByteCode.ICONST_0);
}
/**
* Generate code to load the given long on stack.
*
* @param k the constant
*/
public void addPush(long k) {
int ik = (int) k;
if (ik == k) {
addPush(ik);
add(ByteCode.I2L);
} else {
addLoadConstant(k);
}
}
/**
* Generate code to load the given double on stack.
*
* @param k the constant
*/
public void addPush(double k) {
if (k == 0.0) {
// zero
add(ByteCode.DCONST_0);
if (1.0 / k < 0) {
// Negative zero
add(ByteCode.DNEG);
}
} else if (k == 1.0 || k == -1.0) {
add(ByteCode.DCONST_1);
if (k < 0) {
add(ByteCode.DNEG);
}
} else {
addLoadConstant(k);
}
}
/**
* Generate the code to leave on stack the given string even if the string encoding exeeds the
* class file limit for single string constant
*
* @param k the constant
*/
public void addPush(String k) {
int length = k.length();
int limit = itsConstantPool.getUtfEncodingLimit(k, 0, length);
if (limit == length) {
addLoadConstant(k);
return;
}
// Split string into picies fitting the UTF limit and generate code for
// StringBuilder sb = new StringBuilder(length);
// sb.append(loadConstant(piece_1));
// ...
// sb.append(loadConstant(piece_N));
// sb.toString();
final String SB = "java/lang/StringBuilder";
add(ByteCode.NEW, SB);
add(ByteCode.DUP);
addPush(length);
addInvoke(ByteCode.INVOKESPECIAL, SB, "<init>", "(I)V");
int cursor = 0;
for (; ; ) {
add(ByteCode.DUP);
String s = k.substring(cursor, limit);
addLoadConstant(s);
addInvoke(ByteCode.INVOKEVIRTUAL, SB, "append",
"(Ljava/lang/String;)Ljava/lang/StringBuilder;");
add(ByteCode.POP);
if (limit == length) {
break;
}
cursor = limit;
limit = itsConstantPool.getUtfEncodingLimit(k, limit, length);