Debian Codegraph @

rhino/src/org/mozilla/classfile/ClassFileWriter.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.classfile;
8
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import org.mozilla.javascript.ObjToIntMap;
13 import org.mozilla.javascript.ObjArray;
14 import org.mozilla.javascript.UintMap;
15
16 import java.util.Arrays;
17
18 /**
19 * ClassFileWriter
20 *
21 * A ClassFileWriter is used to write a Java class file. Methods are
22 * provided to create fields and methods, and within methods to write
23 * Java bytecodes.
24 *
25 * @author Roger Lawrence
26 */
27 public class ClassFileWriter {
28
29 /**
30 * Thrown for cases where the error in generating the class file is
31 * due to a program size constraints rather than a likely bug in the
32 * compiler.
33 */
34 public static class ClassFileFormatException extends RuntimeException {
35
36 private static final long serialVersionUID = 1263998431033790599L;
37
38 ClassFileFormatException(String message) {
39 super(message);
40 }
41 }
42
43 /**
44 * Construct a ClassFileWriter for a class.
45 *
46 * @param className the name of the class to write, including
47 * full package qualification.
48 * @param superClassName the name of the superclass of the class
49 * to write, including full package qualification.
50 * @param sourceFileName the name of the source file to use for
51 * producing debug information, or null if debug information
52 * is not desired
53 */
54 public ClassFileWriter(String className, String superClassName,
55 String sourceFileName)
56 {
57 generatedClassName = className;
58 itsConstantPool = new ConstantPool(this);
59 itsThisClassIndex = itsConstantPool.addClass(className);
60 itsSuperClassIndex = itsConstantPool.addClass(superClassName);
61 if (sourceFileName != null)
62 itsSourceFileNameIndex = itsConstantPool.addUtf8(sourceFileName);
63 // All "new" implementations are supposed to output ACC_SUPER as a
64 // class flag. This is specified in the first JVM spec, so it should
65 // be old enough that it's okay to always set it.
66 itsFlags = ACC_PUBLIC | ACC_SUPER;
67 }
68
69 public final String getClassName()
70 {
71 return generatedClassName;
72 }
73
74 /**
75 * Add an interface implemented by this class.
76 *
77 * This method may be called multiple times for classes that
78 * implement multiple interfaces.
79 *
80 * @param interfaceName a name of an interface implemented
81 * by the class being written, including full package
82 * qualification.
83 */
84 public void addInterface(String interfaceName) {
85 short interfaceIndex = itsConstantPool.addClass(interfaceName);
86 itsInterfaces.add(Short.valueOf(interfaceIndex));
87 }
88
89 public static final short
90 ACC_PUBLIC = 0x0001,
91 ACC_PRIVATE = 0x0002,
92 ACC_PROTECTED = 0x0004,
93 ACC_STATIC = 0x0008,
94 ACC_FINAL = 0x0010,
95 ACC_SUPER = 0x0020,
96 ACC_SYNCHRONIZED = 0x0020,
97 ACC_VOLATILE = 0x0040,
98 ACC_TRANSIENT = 0x0080,
99 ACC_NATIVE = 0x0100,
100 ACC_ABSTRACT = 0x0400;
101
102 /**
103 * Set the class's flags.
104 *
105 * Flags must be a set of the following flags, bitwise or'd
106 * together:
107 * ACC_PUBLIC
108 * ACC_PRIVATE
109 * ACC_PROTECTED
110 * ACC_FINAL
111 * ACC_ABSTRACT
112 * TODO: check that this is the appropriate set
113 * @param flags the set of class flags to set
114 */
115 public void setFlags(short flags) {
116 itsFlags = flags;
117 }
118
119 static String getSlashedForm(String name)
120 {
121 return name.replace('.', '/');
122 }
123
124 /**
125 * Convert Java class name in dot notation into
126 * "Lname-with-dots-replaced-by-slashes;" form suitable for use as
127 * JVM type signatures.
128 */
129 public static String classNameToSignature(String name)
130 {
131 int nameLength = name.length();
132 int colonPos = 1 + nameLength;
133 char[] buf = new char[colonPos + 1];
134 buf[0] = 'L';
135 buf[colonPos] = ';';
136 name.getChars(0, nameLength, buf, 1);
137 for (int i = 1; i != colonPos; ++i) {
138 if (buf[i] == '.') {
139 buf[i] = '/';
140 }
141 }
142 return new String(buf, 0, colonPos + 1);
143 }
144
145 /**
146 * Add a field to the class.
147 *
148 * @param fieldName the name of the field
149 * @param type the type of the field using ...
150 * @param flags the attributes of the field, such as ACC_PUBLIC, etc.
151 * bitwise or'd together
152 */
153 public void addField(String fieldName, String type, short flags) {
154 short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
155 short typeIndex = itsConstantPool.addUtf8(type);
156 itsFields.add(new ClassFileField(fieldNameIndex, typeIndex, flags));
157 }
158
159 /**
160 * Add a field to the class.
161 *
162 * @param fieldName the name of the field
163 * @param type the type of the field using ...
164 * @param flags the attributes of the field, such as ACC_PUBLIC, etc.
165 * bitwise or'd together
166 * @param value an initial integral value
167 */
168 public void addField(String fieldName, String type, short flags,
169 int value)
170 {
171 short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
172 short typeIndex = itsConstantPool.addUtf8(type);
173 ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex,
174 flags);
175 field.setAttributes(itsConstantPool.addUtf8("ConstantValue"),
176 (short)0,
177 (short)0,
178 itsConstantPool.addConstant(value));
179 itsFields.add(field);
180 }
181
182 /**
183 * Add a field to the class.
184 *
185 * @param fieldName the name of the field
186 * @param type the type of the field using ...
187 * @param flags the attributes of the field, such as ACC_PUBLIC, etc.
188 * bitwise or'd together
189 * @param value an initial long value
190 */
191 public void addField(String fieldName, String type, short flags,
192 long value)
193 {
194 short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
195 short typeIndex = itsConstantPool.addUtf8(type);
196 ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex,
197 flags);
198 field.setAttributes(itsConstantPool.addUtf8("ConstantValue"),
199 (short)0,
200 (short)2,
201 itsConstantPool.addConstant(value));
202 itsFields.add(field);
203 }
204
205 /**
206 * Add a field to the class.
207 *
208 * @param fieldName the name of the field
209 * @param type the type of the field using ...
210 * @param flags the attributes of the field, such as ACC_PUBLIC, etc.
211 * bitwise or'd together
212 * @param value an initial double value
213 */
214 public void addField(String fieldName, String type, short flags,
215 double value)
216 {
217 short fieldNameIndex = itsConstantPool.addUtf8(fieldName);
218 short typeIndex = itsConstantPool.addUtf8(type);
219 ClassFileField field = new ClassFileField(fieldNameIndex, typeIndex,
220 flags);
221 field.setAttributes(itsConstantPool.addUtf8("ConstantValue"),
222 (short)0,
223 (short)2,
224 itsConstantPool.addConstant(value));
225 itsFields.add(field);
226 }
227
228 /**
229 * Add Information about java variable to use when generating the local
230 * variable table.
231 *
232 * @param name variable name.
233 * @param type variable type as bytecode descriptor string.
234 * @param startPC the starting bytecode PC where this variable is live,
235 * or -1 if it does not have a Java register.
236 * @param register the Java register number of variable
237 * or -1 if it does not have a Java register.
238 */
239 public void addVariableDescriptor(String name, String type, int startPC, int register)
240 {
241 int nameIndex = itsConstantPool.addUtf8(name);
242 int descriptorIndex = itsConstantPool.addUtf8(type);
243 int [] chunk = { nameIndex, descriptorIndex, startPC, register };
244 if (itsVarDescriptors == null) {
245 itsVarDescriptors = new ObjArray();
246 }
247 itsVarDescriptors.add(chunk);
248 }
249
250 /**
251 * Add a method and begin adding code.
252 *
253 * This method must be called before other methods for adding code,
254 * exception tables, etc. can be invoked.
255 *
256 * @param methodName the name of the method
257 * @param type a string representing the type
258 * @param flags the attributes of the field, such as ACC_PUBLIC, etc.
259 * bitwise or'd together
260 */
261 public void startMethod(String methodName, String type, short flags) {
262 short methodNameIndex = itsConstantPool.addUtf8(methodName);
263 short typeIndex = itsConstantPool.addUtf8(type);
264 itsCurrentMethod = new ClassFileMethod(methodName, methodNameIndex,
265 type, typeIndex, flags);
266 itsJumpFroms = new UintMap();
267 itsMethods.add(itsCurrentMethod);
268 addSuperBlockStart(0);
269 }
270
271 /**
272 * Complete generation of the method.
273 *
274 * After this method is called, no more code can be added to the
275 * method begun with <code>startMethod</code>.
276 *
277 * @param maxLocals the maximum number of local variable slots
278 * (a.k.a. Java registers) used by the method
279 */
280 public void stopMethod(short maxLocals) {
281 if (itsCurrentMethod == null)
282 throw new IllegalStateException("No method to stop");
283
284 fixLabelGotos();
285
286 itsMaxLocals = maxLocals;
287
288 StackMapTable stackMap = null;
289 if (GenerateStackMap) {
290 finalizeSuperBlockStarts();
291 stackMap = new StackMapTable();
292 stackMap.generate();
293 }
294
295 int lineNumberTableLength = 0;
296 if (itsLineNumberTable != null) {
297 // 6 bytes for the attribute header
298 // 2 bytes for the line number count
299 // 4 bytes for each entry
300 lineNumberTableLength = 6 + 2 + (itsLineNumberTableTop * 4);
301 }
302
303 int variableTableLength = 0;
304 if (itsVarDescriptors != null) {
305 // 6 bytes for the attribute header
306 // 2 bytes for the variable count
307 // 10 bytes for each entry
308 variableTableLength = 6 + 2 + (itsVarDescriptors.size() * 10);
309 }
310
311 int stackMapTableLength = 0;
312 if (stackMap != null) {
313 int stackMapWriteSize = stackMap.computeWriteSize();
314 if (stackMapWriteSize > 0) {
315 stackMapTableLength = 6 + stackMapWriteSize;
316 }
317 }
318
319 int attrLength = 2 + // attribute_name_index
320 4 + // attribute_length
321 2 + // max_stack
322 2 + // max_locals
323 4 + // code_length
324 itsCodeBufferTop +
325 2 + // exception_table_length
326 (itsExceptionTableTop * 8) +
327 2 + // attributes_count
328 lineNumberTableLength +
329 variableTableLength +
330 stackMapTableLength;
331
332 if (attrLength > 65536) {
333 // See http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html,
334 // section 4.10, "The amount of code per non-native, non-abstract
335 // method is limited to 65536 bytes...
336 throw new ClassFileFormatException(
337 "generated bytecode for method exceeds 64K limit.");
338 }
339 byte[] codeAttribute = new byte[attrLength];
340 int index = 0;
341 int codeAttrIndex = itsConstantPool.addUtf8("Code");
342 index = putInt16(codeAttrIndex, codeAttribute, index);
343 attrLength -= 6; // discount the attribute header
344 index = putInt32(attrLength, codeAttribute, index);
345 index = putInt16(itsMaxStack, codeAttribute, index);
346 index = putInt16(itsMaxLocals, codeAttribute, index);
347 index = putInt32(itsCodeBufferTop, codeAttribute, index);
348 System.arraycopy(itsCodeBuffer, 0, codeAttribute, index,
349 itsCodeBufferTop);
350 index += itsCodeBufferTop;
351
352 if (itsExceptionTableTop > 0) {
353 index = putInt16(itsExceptionTableTop, codeAttribute, index);
354 for (int i = 0; i < itsExceptionTableTop; i++) {
355 ExceptionTableEntry ete = itsExceptionTable[i];
356 short startPC = (short)getLabelPC(ete.itsStartLabel);
357 short endPC = (short)getLabelPC(ete.itsEndLabel);
358 short handlerPC = (short)getLabelPC(ete.itsHandlerLabel);
359 short catchType = ete.itsCatchType;
360 if (startPC == -1)
361 throw new IllegalStateException("start label not defined");
362 if (endPC == -1)
363 throw new IllegalStateException("end label not defined");
364 if (handlerPC == -1)
365 throw new IllegalStateException(
366 "handler label not defined");
367
368 index = putInt16(startPC, codeAttribute, index);
369 index = putInt16(endPC, codeAttribute, index);
370 index = putInt16(handlerPC, codeAttribute, index);
371 index = putInt16(catchType, codeAttribute, index);
372 }
373 }
374 else {
375 // write 0 as exception table length
376 index = putInt16(0, codeAttribute, index);
377 }
378
379 int attributeCount = 0;
380 if (itsLineNumberTable != null)
381 attributeCount++;
382 if (itsVarDescriptors != null)
383 attributeCount++;
384 if (stackMapTableLength > 0) {
385 attributeCount++;
386 }
387 index = putInt16(attributeCount, codeAttribute, index);
388
389 if (itsLineNumberTable != null) {
390 int lineNumberTableAttrIndex
391 = itsConstantPool.addUtf8("LineNumberTable");
392 index = putInt16(lineNumberTableAttrIndex, codeAttribute, index);
393 int tableAttrLength = 2 + (itsLineNumberTableTop * 4);
394 index = putInt32(tableAttrLength, codeAttribute, index);
395 index = putInt16(itsLineNumberTableTop, codeAttribute, index);
396 for (int i = 0; i < itsLineNumberTableTop; i++) {
397 index = putInt32(itsLineNumberTable[i], codeAttribute, index);
398 }
399 }
400
401 if (itsVarDescriptors != null) {
402 int variableTableAttrIndex
403 = itsConstantPool.addUtf8("LocalVariableTable");
404 index = putInt16(variableTableAttrIndex, codeAttribute, index);
405 int varCount = itsVarDescriptors.size();
406 int tableAttrLength = 2 + (varCount * 10);
407 index = putInt32(tableAttrLength, codeAttribute, index);
408 index = putInt16(varCount, codeAttribute, index);
409 for (int i = 0; i < varCount; i++) {
410 int[] chunk = (int[])itsVarDescriptors.get(i);
411 int nameIndex = chunk[0];
412 int descriptorIndex = chunk[1];
413 int startPC = chunk[2];
414 int register = chunk[3];
415 int length = itsCodeBufferTop - startPC;
416
417 index = putInt16(startPC, codeAttribute, index);
418 index = putInt16(length, codeAttribute, index);
419 index = putInt16(nameIndex, codeAttribute, index);
420 index = putInt16(descriptorIndex, codeAttribute, index);
421 index = putInt16(register, codeAttribute, index);
422 }
423 }
424
425 if (stackMapTableLength > 0) {
426 int stackMapTableAttrIndex =
427 itsConstantPool.addUtf8("StackMapTable");
428 int start = index;
429 index = putInt16(stackMapTableAttrIndex, codeAttribute, index);
430 index = stackMap.write(codeAttribute, index);
431 }
432
433 itsCurrentMethod.setCodeAttribute(codeAttribute);
434
435 itsExceptionTable = null;
436 itsExceptionTableTop = 0;
437 itsLineNumberTableTop = 0;
438 itsCodeBufferTop = 0;
439 itsCurrentMethod = null;
440 itsMaxStack = 0;
441 itsStackTop = 0;
442 itsLabelTableTop = 0;
443 itsFixupTableTop = 0;
444 itsVarDescriptors = null;
445 itsSuperBlockStarts = null;
446 itsSuperBlockStartsTop = 0;
447 itsJumpFroms = null;
448 }
449
450 /**
451 * Add the single-byte opcode to the current method.
452 *
453 * @param theOpCode the opcode of the bytecode
454 */
455 public void add(int theOpCode) {
456 if (opcodeCount(theOpCode) != 0)
457 throw new IllegalArgumentException("Unexpected operands");
458 int newStack = itsStackTop + stackChange(theOpCode);
459 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
460 if (DEBUGCODE)
461 System.out.println("Add " + bytecodeStr(theOpCode));
462 addToCodeBuffer(theOpCode);
463 itsStackTop = (short)newStack;
464 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
465 if (DEBUGSTACK) {
466 System.out.println("After "+bytecodeStr(theOpCode)
467 +" stack = "+itsStackTop);
468 }
469 if (theOpCode == ByteCode.ATHROW) {
470 addSuperBlockStart(itsCodeBufferTop);
471 }
472 }
473
474 /**
475 * Add a single-operand opcode to the current method.
476 *
477 * @param theOpCode the opcode of the bytecode
478 * @param theOperand the operand of the bytecode
479 */
480 public void add(int theOpCode, int theOperand) {
481 if (DEBUGCODE) {
482 System.out.println("Add "+bytecodeStr(theOpCode)
483 +", "+Integer.toHexString(theOperand));
484 }
485 int newStack = itsStackTop + stackChange(theOpCode);
486 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
487
488 switch (theOpCode) {
489 case ByteCode.GOTO :
490 // This is necessary because dead code is seemingly being
491 // generated and Sun's verifier is expecting type state to be
492 // placed even at dead blocks of code.
493 addSuperBlockStart(itsCodeBufferTop + 3);
494 // fallthru...
495 case ByteCode.IFEQ :
496 case ByteCode.IFNE :
497 case ByteCode.IFLT :
498 case ByteCode.IFGE :
499 case ByteCode.IFGT :
500 case ByteCode.IFLE :
501 case ByteCode.IF_ICMPEQ :
502 case ByteCode.IF_ICMPNE :
503 case ByteCode.IF_ICMPLT :
504 case ByteCode.IF_ICMPGE :
505 case ByteCode.IF_ICMPGT :
506 case ByteCode.IF_ICMPLE :
507 case ByteCode.IF_ACMPEQ :
508 case ByteCode.IF_ACMPNE :
509 case ByteCode.JSR :
510 case ByteCode.IFNULL :
511 case ByteCode.IFNONNULL : {
512 if ((theOperand & 0x80000000) != 0x80000000) {
513 if ((theOperand < 0) || (theOperand > 65535))
514 throw new IllegalArgumentException(
515 "Bad label for branch");
516 }
517 int branchPC = itsCodeBufferTop;
518 addToCodeBuffer(theOpCode);
519 if ((theOperand & 0x80000000) != 0x80000000) {
520 // hard displacement
521 addToCodeInt16(theOperand);
522 int target = theOperand + branchPC;
523 addSuperBlockStart(target);
524 itsJumpFroms.put(target, branchPC);
525 }
526 else { // a label
527 int targetPC = getLabelPC(theOperand);
528 if (DEBUGLABELS) {
529 int theLabel = theOperand & 0x7FFFFFFF;
530 System.out.println("Fixing branch to " +
531 theLabel + " at " + targetPC +
532 " from " + branchPC);
533 }
534 if (targetPC != -1) {
535 int offset = targetPC - branchPC;
536 addToCodeInt16(offset);
537 addSuperBlockStart(targetPC);
538 itsJumpFroms.put(targetPC, branchPC);
539 }
540 else {
541 addLabelFixup(theOperand, branchPC + 1);
542 addToCodeInt16(0);
543 }
544 }
545 }
546 break;
547
548 case ByteCode.BIPUSH :
549 if ((byte)theOperand != theOperand)
550 throw new IllegalArgumentException("out of range byte");
551 addToCodeBuffer(theOpCode);
552 addToCodeBuffer((byte)theOperand);
553 break;
554
555 case ByteCode.SIPUSH :
556 if ((short)theOperand != theOperand)
557 throw new IllegalArgumentException("out of range short");
558 addToCodeBuffer(theOpCode);
559 addToCodeInt16(theOperand);
560 break;
561
562 case ByteCode.NEWARRAY :
563 if (!(0 <= theOperand && theOperand < 256))
564 throw new IllegalArgumentException("out of range index");
565 addToCodeBuffer(theOpCode);
566 addToCodeBuffer(theOperand);
567 break;
568
569 case ByteCode.GETFIELD :
570 case ByteCode.PUTFIELD :
571 if (!(0 <= theOperand && theOperand < 65536))
572 throw new IllegalArgumentException("out of range field");
573 addToCodeBuffer(theOpCode);
574 addToCodeInt16(theOperand);
575 break;
576
577 case ByteCode.LDC :
578 case ByteCode.LDC_W :
579 case ByteCode.LDC2_W :
580 if (!(0 <= theOperand && theOperand < 65536))
581 throw new IllegalArgumentException("out of range index");
582 if (theOperand >= 256
583 || theOpCode == ByteCode.LDC_W
584 || theOpCode == ByteCode.LDC2_W)
585 {
586 if (theOpCode == ByteCode.LDC) {
587 addToCodeBuffer(ByteCode.LDC_W);
588 } else {
589 addToCodeBuffer(theOpCode);
590 }
591 addToCodeInt16(theOperand);
592 } else {
593 addToCodeBuffer(theOpCode);
594 addToCodeBuffer(theOperand);
595 }
596 break;
597
598 case ByteCode.RET :
599 case ByteCode.ILOAD :
600 case ByteCode.LLOAD :
601 case ByteCode.FLOAD :
602 case ByteCode.DLOAD :
603 case ByteCode.ALOAD :
604 case ByteCode.ISTORE :
605 case ByteCode.LSTORE :
606 case ByteCode.FSTORE :
607 case ByteCode.DSTORE :
608 case ByteCode.ASTORE :
609 if (!(0 <= theOperand && theOperand < 65536))
610 throw new ClassFileFormatException("out of range variable");
611 if (theOperand >= 256) {
612 addToCodeBuffer(ByteCode.WIDE);
613 addToCodeBuffer(theOpCode);
614 addToCodeInt16(theOperand);
615 }
616 else {
617 addToCodeBuffer(theOpCode);
618 addToCodeBuffer(theOperand);
619 }
620 break;
621
622 default :
623 throw new IllegalArgumentException(
624 "Unexpected opcode for 1 operand");
625 }
626
627 itsStackTop = (short)newStack;
628 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
629 if (DEBUGSTACK) {
630 System.out.println("After "+bytecodeStr(theOpCode)
631 +" stack = "+itsStackTop);
632 }
633 }
634
635 /**
636 * Generate the load constant bytecode for the given integer.
637 *
638 * @param k the constant
639 */
640 public void addLoadConstant(int k) {
641 switch (k) {
642 case 0: add(ByteCode.ICONST_0); break;
643 case 1: add(ByteCode.ICONST_1); break;
644 case 2: add(ByteCode.ICONST_2); break;
645 case 3: add(ByteCode.ICONST_3); break;
646 case 4: add(ByteCode.ICONST_4); break;
647 case 5: add(ByteCode.ICONST_5); break;
648 default:
649 add(ByteCode.LDC, itsConstantPool.addConstant(k));
650 break;
651 }
652 }
653
654 /**
655 * Generate the load constant bytecode for the given long.
656 *
657 * @param k the constant
658 */
659 public void addLoadConstant(long k) {
660 add(ByteCode.LDC2_W, itsConstantPool.addConstant(k));
661 }
662
663 /**
664 * Generate the load constant bytecode for the given float.
665 *
666 * @param k the constant
667 */
668 public void addLoadConstant(float k) {
669 add(ByteCode.LDC, itsConstantPool.addConstant(k));
670 }
671
672 /**
673 * Generate the load constant bytecode for the given double.
674 *
675 * @param k the constant
676 */
677 public void addLoadConstant(double k) {
678 add(ByteCode.LDC2_W, itsConstantPool.addConstant(k));
679 }
680
681 /**
682 * Generate the load constant bytecode for the given string.
683 *
684 * @param k the constant
685 */
686 public void addLoadConstant(String k) {
687 add(ByteCode.LDC, itsConstantPool.addConstant(k));
688 }
689
690 /**
691 * Add the given two-operand bytecode to the current method.
692 *
693 * @param theOpCode the opcode of the bytecode
694 * @param theOperand1 the first operand of the bytecode
695 * @param theOperand2 the second operand of the bytecode
696 */
697 public void add(int theOpCode, int theOperand1, int theOperand2) {
698 if (DEBUGCODE) {
699 System.out.println("Add "+bytecodeStr(theOpCode)
700 +", "+Integer.toHexString(theOperand1)
701 +", "+Integer.toHexString(theOperand2));
702 }
703 int newStack = itsStackTop + stackChange(theOpCode);
704 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
705
706 if (theOpCode == ByteCode.IINC) {
707 if (!(0 <= theOperand1 && theOperand1 < 65536))
708 throw new ClassFileFormatException("out of range variable");
709 if (!(0 <= theOperand2 && theOperand2 < 65536))
710 throw new ClassFileFormatException("out of range increment");
711
712 if (theOperand1 > 255 || theOperand2 < -128 || theOperand2 > 127) {
713 addToCodeBuffer(ByteCode.WIDE);
714 addToCodeBuffer(ByteCode.IINC);
715 addToCodeInt16(theOperand1);
716 addToCodeInt16(theOperand2);
717 }
718 else {
719 addToCodeBuffer(ByteCode.IINC);
720 addToCodeBuffer(theOperand1);
721 addToCodeBuffer(theOperand2);
722 }
723 }
724 else if (theOpCode == ByteCode.MULTIANEWARRAY) {
725 if (!(0 <= theOperand1 && theOperand1 < 65536))
726 throw new IllegalArgumentException("out of range index");
727 if (!(0 <= theOperand2 && theOperand2 < 256))
728 throw new IllegalArgumentException("out of range dimensions");
729
730 addToCodeBuffer(ByteCode.MULTIANEWARRAY);
731 addToCodeInt16(theOperand1);
732 addToCodeBuffer(theOperand2);
733 }
734 else {
735 throw new IllegalArgumentException(
736 "Unexpected opcode for 2 operands");
737 }
738 itsStackTop = (short)newStack;
739 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
740 if (DEBUGSTACK) {
741 System.out.println("After "+bytecodeStr(theOpCode)
742 +" stack = "+itsStackTop);
743 }
744
745 }
746
747 public void add(int theOpCode, String className) {
748 if (DEBUGCODE) {
749 System.out.println("Add "+bytecodeStr(theOpCode)
750 +", "+className);
751 }
752 int newStack = itsStackTop + stackChange(theOpCode);
753 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
754 switch (theOpCode) {
755 case ByteCode.NEW :
756 case ByteCode.ANEWARRAY :
757 case ByteCode.CHECKCAST :
758 case ByteCode.INSTANCEOF : {
759 short classIndex = itsConstantPool.addClass(className);
760 addToCodeBuffer(theOpCode);
761 addToCodeInt16(classIndex);
762 }
763 break;
764
765 default :
766 throw new IllegalArgumentException(
767 "bad opcode for class reference");
768 }
769 itsStackTop = (short)newStack;
770 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
771 if (DEBUGSTACK) {
772 System.out.println("After "+bytecodeStr(theOpCode)
773 +" stack = "+itsStackTop);
774 }
775 }
776
777
778 public void add(int theOpCode, String className, String fieldName,
779 String fieldType)
780 {
781 if (DEBUGCODE) {
782 System.out.println("Add "+bytecodeStr(theOpCode)
783 +", "+className+", "+fieldName+", "+fieldType);
784 }
785 int newStack = itsStackTop + stackChange(theOpCode);
786 char fieldTypeChar = fieldType.charAt(0);
787 int fieldSize = (fieldTypeChar == 'J' || fieldTypeChar == 'D')
788 ? 2 : 1;
789 switch (theOpCode) {
790 case ByteCode.GETFIELD :
791 case ByteCode.GETSTATIC :
792 newStack += fieldSize;
793 break;
794 case ByteCode.PUTSTATIC :
795 case ByteCode.PUTFIELD :
796 newStack -= fieldSize;
797 break;
798 default :
799 throw new IllegalArgumentException(
800 "bad opcode for field reference");
801 }
802 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
803 short fieldRefIndex = itsConstantPool.addFieldRef(className,
804 fieldName, fieldType);
805 addToCodeBuffer(theOpCode);
806 addToCodeInt16(fieldRefIndex);
807
808 itsStackTop = (short)newStack;
809 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
810 if (DEBUGSTACK) {
811 System.out.println("After "+bytecodeStr(theOpCode)
812 +" stack = "+itsStackTop);
813 }
814 }
815
816 public void addInvoke(int theOpCode, String className, String methodName,
817 String methodType)
818 {
819 if (DEBUGCODE) {
820 System.out.println("Add "+bytecodeStr(theOpCode)
821 +", "+className+", "+methodName+", "
822 +methodType);
823 }
824 int parameterInfo = sizeOfParameters(methodType);
825 int parameterCount = parameterInfo >>> 16;
826 int stackDiff = (short)parameterInfo;
827
828 int newStack = itsStackTop + stackDiff;
829 newStack += stackChange(theOpCode); // adjusts for 'this'
830 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
831
832 switch (theOpCode) {
833 case ByteCode.INVOKEVIRTUAL :
834 case ByteCode.INVOKESPECIAL :
835 case ByteCode.INVOKESTATIC :
836 case ByteCode.INVOKEINTERFACE : {
837 addToCodeBuffer(theOpCode);
838 if (theOpCode == ByteCode.INVOKEINTERFACE) {
839 short ifMethodRefIndex
840 = itsConstantPool.addInterfaceMethodRef(
841 className, methodName,
842 methodType);
843 addToCodeInt16(ifMethodRefIndex);
844 addToCodeBuffer(parameterCount + 1);
845 addToCodeBuffer(0);
846 }
847 else {
848 short methodRefIndex = itsConstantPool.addMethodRef(
849 className, methodName,
850 methodType);
851 addToCodeInt16(methodRefIndex);
852 }
853 }
854 break;
855
856 default :
857 throw new IllegalArgumentException(
858 "bad opcode for method reference");
859 }
860 itsStackTop = (short)newStack;
861 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
862 if (DEBUGSTACK) {
863 System.out.println("After "+bytecodeStr(theOpCode)
864 +" stack = "+itsStackTop);
865 }
866 }
867
868 /**
869 * Generate code to load the given integer on stack.
870 *
871 * @param k the constant
872 */
873 public void addPush(int k)
874 {
875 if ((byte)k == k) {
876 if (k == -1) {
877 add(ByteCode.ICONST_M1);
878 } else if (0 <= k && k <= 5) {
879 add((byte)(ByteCode.ICONST_0 + k));
880 } else {
881 add(ByteCode.BIPUSH, (byte)k);
882 }
883 } else if ((short)k == k) {
884 add(ByteCode.SIPUSH, (short)k);
885 } else {
886 addLoadConstant(k);
887 }
888 }
889
890 public void addPush(boolean k)
891 {
892 add(k ? ByteCode.ICONST_1 : ByteCode.ICONST_0);
893 }
894
895 /**
896 * Generate code to load the given long on stack.
897 *
898 * @param k the constant
899 */
900 public void addPush(long k)
901 {
902 int ik = (int)k;
903 if (ik == k) {
904 addPush(ik);
905 add(ByteCode.I2L);
906 } else {
907 addLoadConstant(k);
908 }
909 }
910
911 /**
912 * Generate code to load the given double on stack.
913 *
914 * @param k the constant
915 */
916 public void addPush(double k)
917 {
918 if (k == 0.0) {
919 // zero
920 add(ByteCode.DCONST_0);
921 if (1.0 / k < 0) {
922 // Negative zero
923 add(ByteCode.DNEG);
924 }
925 } else if (k == 1.0 || k == -1.0) {
926 add(ByteCode.DCONST_1);
927 if (k < 0) {
928 add(ByteCode.DNEG);
929 }
930 } else {
931 addLoadConstant(k);
932 }
933 }
934
935 /**
936 * Generate the code to leave on stack the given string even if the
937 * string encoding exeeds the class file limit for single string constant
938 *
939 * @param k the constant
940 */
941 public void addPush(String k) {
942 int length = k.length();
943 int limit = itsConstantPool.getUtfEncodingLimit(k, 0, length);
944 if (limit == length) {
945 addLoadConstant(k);
946 return;
947 }
948 // Split string into picies fitting the UTF limit and generate code for
949 // StringBuilder sb = new StringBuilder(length);
950 // sb.append(loadConstant(piece_1));
951 // ...
952 // sb.append(loadConstant(piece_N));
953 // sb.toString();
954 final String SB = "java/lang/StringBuilder";
955 add(ByteCode.NEW, SB);
956 add(ByteCode.DUP);
957 addPush(length);
958 addInvoke(ByteCode.INVOKESPECIAL, SB, "<init>", "(I)V");
959 int cursor = 0;
960 for (;;) {
961 add(ByteCode.DUP);
962 String s = k.substring(cursor, limit);
963 addLoadConstant(s);
964 addInvoke(ByteCode.INVOKEVIRTUAL, SB, "append",
965 "(Ljava/lang/String;)Ljava/lang/StringBuilder;");
966 add(ByteCode.POP);
967 if (limit == length) {
968 break;
969 }
970 cursor = limit;
971 limit = itsConstantPool.getUtfEncodingLimit(k, limit, length);
972 }
973 addInvoke(ByteCode.INVOKEVIRTUAL, SB, "toString",
974 "()Ljava/lang/String;");
975 }
976
977 /**
978 * Check if k fits limit on string constant size imposed by class file
979 * format.
980 *
981 * @param k the string constant
982 */
983 public boolean isUnderStringSizeLimit(String k)
984 {
985 return itsConstantPool.isUnderUtfEncodingLimit(k);
986 }
987
988 /**
989 * Store integer from stack top into the given local.
990 *
991 * @param local number of local register
992 */
993 public void addIStore(int local)
994 {
995 xop(ByteCode.ISTORE_0, ByteCode.ISTORE, local);
996 }
997
998 /**
999 * Store long from stack top into the given local.
1000 *
1001 * @param local number of local register
1002 */
1003 public void addLStore(int local)
1004 {
1005 xop(ByteCode.LSTORE_0, ByteCode.LSTORE, local);
1006 }
1007
1008 /**
1009 * Store float from stack top into the given local.
1010 *
1011 * @param local number of local register
1012 */
1013 public void addFStore(int local)
1014 {
1015 xop(ByteCode.FSTORE_0, ByteCode.FSTORE, local);
1016 }
1017
1018 /**
1019 * Store double from stack top into the given local.
1020 *
1021 * @param local number of local register
1022 */
1023 public void addDStore(int local)
1024 {
1025 xop(ByteCode.DSTORE_0, ByteCode.DSTORE, local);
1026 }
1027
1028 /**
1029 * Store object from stack top into the given local.
1030 *
1031 * @param local number of local register
1032 */
1033 public void addAStore(int local)
1034 {
1035 xop(ByteCode.ASTORE_0, ByteCode.ASTORE, local);
1036 }
1037
1038 /**
1039 * Load integer from the given local into stack.
1040 *
1041 * @param local number of local register
1042 */
1043 public void addILoad(int local)
1044 {
1045 xop(ByteCode.ILOAD_0, ByteCode.ILOAD, local);
1046 }
1047
1048 /**
1049 * Load long from the given local into stack.
1050 *
1051 * @param local number of local register
1052 */
1053 public void addLLoad(int local)
1054 {
1055 xop(ByteCode.LLOAD_0, ByteCode.LLOAD, local);
1056 }
1057
1058 /**
1059 * Load float from the given local into stack.
1060 *
1061 * @param local number of local register
1062 */
1063 public void addFLoad(int local)
1064 {
1065 xop(ByteCode.FLOAD_0, ByteCode.FLOAD, local);
1066 }
1067
1068 /**
1069 * Load double from the given local into stack.
1070 *
1071 * @param local number of local register
1072 */
1073 public void addDLoad(int local)
1074 {
1075 xop(ByteCode.DLOAD_0, ByteCode.DLOAD, local);
1076 }
1077
1078 /**
1079 * Load object from the given local into stack.
1080 *
1081 * @param local number of local register
1082 */
1083 public void addALoad(int local)
1084 {
1085 xop(ByteCode.ALOAD_0, ByteCode.ALOAD, local);
1086 }
1087
1088 /**
1089 * Load "this" into stack.
1090 */
1091 public void addLoadThis()
1092 {
1093 add(ByteCode.ALOAD_0);
1094 }
1095
1096 private void xop(int shortOp, int op, int local)
1097 {
1098 switch (local) {
1099 case 0:
1100 add(shortOp);
1101 break;
1102 case 1:
1103 add(shortOp + 1);
1104 break;
1105 case 2:
1106 add(shortOp + 2);
1107 break;
1108 case 3:
1109 add(shortOp + 3);
1110 break;
1111 default:
1112 add(op, local);
1113 }
1114 }
1115
1116 public int addTableSwitch(int low, int high)
1117 {
1118 if (DEBUGCODE) {
1119 System.out.println("Add "+bytecodeStr(ByteCode.TABLESWITCH)
1120 +" "+low+" "+high);
1121 }
1122 if (low > high)
1123 throw new ClassFileFormatException("Bad bounds: "+low+' '+ high);
1124
1125 int newStack = itsStackTop + stackChange(ByteCode.TABLESWITCH);
1126 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
1127
1128 int entryCount = high - low + 1;
1129 int padSize = 3 & ~itsCodeBufferTop; // == 3 - itsCodeBufferTop % 4
1130
1131 int N = addReservedCodeSpace(1 + padSize + 4 * (1 + 2 + entryCount));
1132 int switchStart = N;
1133 itsCodeBuffer[N++] = (byte)ByteCode.TABLESWITCH;
1134 while (padSize != 0) {
1135 itsCodeBuffer[N++] = 0;
1136 --padSize;
1137 }
1138 N += 4; // skip default offset
1139 N = putInt32(low, itsCodeBuffer, N);
1140 putInt32(high, itsCodeBuffer, N);
1141
1142 itsStackTop = (short)newStack;
1143 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
1144 if (DEBUGSTACK) {
1145 System.out.println("After "+bytecodeStr(ByteCode.TABLESWITCH)
1146 +" stack = "+itsStackTop);
1147 }
1148
1149 return switchStart;
1150 }
1151
1152 public final void markTableSwitchDefault(int switchStart)
1153 {
1154 addSuperBlockStart(itsCodeBufferTop);
1155 itsJumpFroms.put(itsCodeBufferTop, switchStart);
1156 setTableSwitchJump(switchStart, -1, itsCodeBufferTop);
1157 }
1158
1159 public final void markTableSwitchCase(int switchStart, int caseIndex)
1160 {
1161 addSuperBlockStart(itsCodeBufferTop);
1162 itsJumpFroms.put(itsCodeBufferTop, switchStart);
1163 setTableSwitchJump(switchStart, caseIndex, itsCodeBufferTop);
1164 }
1165
1166 public final void markTableSwitchCase(int switchStart, int caseIndex,
1167 int stackTop)
1168 {
1169 if (!(0 <= stackTop && stackTop <= itsMaxStack))
1170 throw new IllegalArgumentException("Bad stack index: "+stackTop);
1171 itsStackTop = (short)stackTop;
1172 addSuperBlockStart(itsCodeBufferTop);
1173 itsJumpFroms.put(itsCodeBufferTop, switchStart);
1174 setTableSwitchJump(switchStart, caseIndex, itsCodeBufferTop);
1175 }
1176
1177 /**
1178 * Set a jump case for a tableswitch instruction. The jump target should
1179 * be marked as a super block start for stack map generation.
1180 */
1181 public void setTableSwitchJump(int switchStart, int caseIndex,
1182 int jumpTarget)
1183 {
1184 if (!(0 <= jumpTarget && jumpTarget <= itsCodeBufferTop))
1185 throw new IllegalArgumentException("Bad jump target: "+jumpTarget);
1186 if (!(caseIndex >= -1))
1187 throw new IllegalArgumentException("Bad case index: "+caseIndex);
1188
1189 int padSize = 3 & ~switchStart; // == 3 - switchStart % 4
1190 int caseOffset;
1191 if (caseIndex < 0) {
1192 // default label
1193 caseOffset = switchStart + 1 + padSize;
1194 } else {
1195 caseOffset = switchStart + 1 + padSize + 4 * (3 + caseIndex);
1196 }
1197 if (!(0 <= switchStart
1198 && switchStart <= itsCodeBufferTop - 4 * 4 - padSize - 1))
1199 {
1200 throw new IllegalArgumentException(
1201 switchStart+" is outside a possible range of tableswitch"
1202 +" in already generated code");
1203 }
1204 if ((0xFF & itsCodeBuffer[switchStart]) != ByteCode.TABLESWITCH) {
1205 throw new IllegalArgumentException(
1206 switchStart+" is not offset of tableswitch statement");
1207 }
1208 if (!(0 <= caseOffset && caseOffset + 4 <= itsCodeBufferTop)) {
1209 // caseIndex >= -1 does not guarantee that caseOffset >= 0 due
1210 // to a possible overflow.
1211 throw new ClassFileFormatException(
1212 "Too big case index: "+caseIndex);
1213 }
1214 // ALERT: perhaps check against case bounds?
1215 putInt32(jumpTarget - switchStart, itsCodeBuffer, caseOffset);
1216 }
1217
1218 public int acquireLabel()
1219 {
1220 int top = itsLabelTableTop;
1221 if (itsLabelTable == null || top == itsLabelTable.length) {
1222 if (itsLabelTable == null) {
1223 itsLabelTable = new int[MIN_LABEL_TABLE_SIZE];
1224 }else {
1225 int[] tmp = new int[itsLabelTable.length * 2];
1226 System.arraycopy(itsLabelTable, 0, tmp, 0, top);
1227 itsLabelTable = tmp;
1228 }
1229 }
1230 itsLabelTableTop = top + 1;
1231 itsLabelTable[top] = -1;
1232 return top | 0x80000000;
1233 }
1234
1235 public void markLabel(int label)
1236 {
1237 if (!(label < 0))
1238 throw new IllegalArgumentException("Bad label, no biscuit");
1239
1240 label &= 0x7FFFFFFF;
1241 if (label > itsLabelTableTop)
1242 throw new IllegalArgumentException("Bad label");
1243
1244 if (itsLabelTable[label] != -1) {
1245 throw new IllegalStateException("Can only mark label once");
1246 }
1247
1248 itsLabelTable[label] = itsCodeBufferTop;
1249 }
1250
1251 public void markLabel(int label, short stackTop)
1252 {
1253 markLabel(label);
1254 itsStackTop = stackTop;
1255 }
1256
1257 public void markHandler(int theLabel) {
1258 itsStackTop = 1;
1259 markLabel(theLabel);
1260 }
1261
1262 public int getLabelPC(int label)
1263 {
1264 if (!(label < 0))
1265 throw new IllegalArgumentException("Bad label, no biscuit");
1266 label &= 0x7FFFFFFF;
1267 if (!(label < itsLabelTableTop))
1268 throw new IllegalArgumentException("Bad label");
1269 return itsLabelTable[label];
1270 }
1271
1272 private void addLabelFixup(int label, int fixupSite)
1273 {
1274 if (!(label < 0))
1275 throw new IllegalArgumentException("Bad label, no biscuit");
1276 label &= 0x7FFFFFFF;
1277 if (!(label < itsLabelTableTop))
1278 throw new IllegalArgumentException("Bad label");
1279 int top = itsFixupTableTop;
1280 if (itsFixupTable == null || top == itsFixupTable.length) {
1281 if (itsFixupTable == null) {
1282 itsFixupTable = new long[MIN_FIXUP_TABLE_SIZE];
1283 }else {
1284 long[] tmp = new long[itsFixupTable.length * 2];
1285 System.arraycopy(itsFixupTable, 0, tmp, 0, top);
1286 itsFixupTable = tmp;
1287 }
1288 }
1289 itsFixupTableTop = top + 1;
1290 itsFixupTable[top] = ((long)label << 32) | fixupSite;
1291 }
1292
1293 private void fixLabelGotos()
1294 {
1295 byte[] codeBuffer = itsCodeBuffer;
1296 for (int i = 0; i < itsFixupTableTop; i++) {
1297 long fixup = itsFixupTable[i];
1298 int label = (int)(fixup >> 32);
1299 int fixupSite = (int)fixup;
1300 int pc = itsLabelTable[label];
1301 if (pc == -1) {
1302 // Unlocated label
1303 throw new RuntimeException();
1304 }
1305 // -1 to get delta from instruction start
1306 addSuperBlockStart(pc);
1307 itsJumpFroms.put(pc, fixupSite - 1);
1308 int offset = pc - (fixupSite - 1);
1309 if ((short)offset != offset) {
1310 throw new ClassFileFormatException
1311 ("Program too complex: too big jump offset");
1312 }
1313 codeBuffer[fixupSite] = (byte)(offset >> 8);
1314 codeBuffer[fixupSite + 1] = (byte)offset;
1315 }
1316 itsFixupTableTop = 0;
1317 }
1318
1319 /**
1320 * Get the current offset into the code of the current method.
1321 *
1322 * @return an integer representing the offset
1323 */
1324 public int getCurrentCodeOffset() {
1325 return itsCodeBufferTop;
1326 }
1327
1328 public short getStackTop() {
1329 return itsStackTop;
1330 }
1331
1332 public void setStackTop(short n) {
1333 itsStackTop = n;
1334 }
1335
1336 public void adjustStackTop(int delta) {
1337 int newStack = itsStackTop + delta;
1338 if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
1339 itsStackTop = (short)newStack;
1340 if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
1341 if (DEBUGSTACK) {
1342 System.out.println("After "+"adjustStackTop("+delta+")"
1343 +" stack = "+itsStackTop);
1344 }
1345 }
1346
1347 private void addToCodeBuffer(int b)
1348 {
1349 int N = addReservedCodeSpace(1);
1350 itsCodeBuffer[N] = (byte)b;
1351 }
1352
1353 private void addToCodeInt16(int value)
1354 {
1355 int N = addReservedCodeSpace(2);
1356 putInt16(value, itsCodeBuffer, N);
1357 }
1358
1359 private int addReservedCodeSpace(int size)
1360 {
1361 if (itsCurrentMethod == null)
1362 throw new IllegalArgumentException("No method to add to");
1363 int oldTop = itsCodeBufferTop;
1364 int newTop = oldTop + size;
1365 if (newTop > itsCodeBuffer.length) {
1366 int newSize = itsCodeBuffer.length * 2;
1367 if (newTop > newSize) { newSize = newTop; }
1368 byte[] tmp = new byte[newSize];
1369 System.arraycopy(itsCodeBuffer, 0, tmp, 0, oldTop);
1370 itsCodeBuffer = tmp;
1371 }
1372 itsCodeBufferTop = newTop;
1373 return oldTop;
1374 }
1375
1376 public void addExceptionHandler(int startLabel, int endLabel,
1377 int handlerLabel, String catchClassName)
1378 {
1379 if ((startLabel & 0x80000000) != 0x80000000)
1380 throw new IllegalArgumentException("Bad startLabel");
1381 if ((endLabel & 0x80000000) != 0x80000000)
1382 throw new IllegalArgumentException("Bad endLabel");
1383 if ((handlerLabel & 0x80000000) != 0x80000000)
1384 throw new IllegalArgumentException("Bad handlerLabel");
1385
1386 /*
1387 * If catchClassName is null, use 0 for the catch_type_index; which
1388 * means catch everything. (Even when the verifier has let you throw
1389 * something other than a Throwable.)
1390 */
1391 short catch_type_index = (catchClassName == null)
1392 ? 0
1393 : itsConstantPool.addClass(catchClassName);
1394 ExceptionTableEntry newEntry = new ExceptionTableEntry(
1395 startLabel,
1396 endLabel,
1397 handlerLabel,
1398 catch_type_index);
1399 int N = itsExceptionTableTop;
1400 if (N == 0) {
1401 itsExceptionTable = new ExceptionTableEntry[ExceptionTableSize];
1402 } else if (N == itsExceptionTable.length) {
1403 ExceptionTableEntry[] tmp = new ExceptionTableEntry[N * 2];
1404 System.arraycopy(itsExceptionTable, 0, tmp, 0, N);
1405 itsExceptionTable = tmp;
1406 }
1407 itsExceptionTable[N] = newEntry;
1408 itsExceptionTableTop = N + 1;
1409
1410 }
1411
1412 public void addLineNumberEntry(short lineNumber) {
1413 if (itsCurrentMethod == null)
1414 throw new IllegalArgumentException("No method to stop");
1415 int N = itsLineNumberTableTop;
1416 if (N == 0) {
1417 itsLineNumberTable = new int[LineNumberTableSize];
1418 } else if (N == itsLineNumberTable.length) {
1419 int[] tmp = new int[N * 2];
1420 System.arraycopy(itsLineNumberTable, 0, tmp, 0, N);
1421 itsLineNumberTable = tmp;
1422 }
1423 itsLineNumberTable[N] = (itsCodeBufferTop << 16) + lineNumber;
1424 itsLineNumberTableTop = N + 1;
1425 }
1426
1427 /**
1428 * A stack map table is a code attribute introduced in Java 6 that
1429 * gives type information at key points in the method body (namely, at
1430 * the beginning of each super block after the first). Each frame of a
1431 * stack map table contains the state of local variable and operand stack
1432 * for a given super block.
1433 */
1434 final class StackMapTable {
1435 StackMapTable() {
1436 superBlocks = null;
1437 locals = stack = null;
1438 workList = null;
1439 rawStackMap = null;
1440 localsTop = 0;
1441 stackTop = 0;
1442 workListTop = 0;
1443 rawStackMapTop = 0;
1444 wide = false;
1445 }
1446
1447 void generate() {
1448 superBlocks = new SuperBlock[itsSuperBlockStartsTop];
1449 int[] initialLocals = createInitialLocals();
1450
1451 for (int i = 0; i < itsSuperBlockStartsTop; i++) {
1452 int start = itsSuperBlockStarts[i];
1453 int end;
1454 if (i == itsSuperBlockStartsTop - 1) {
1455 end = itsCodeBufferTop;
1456 } else {
1457 end = itsSuperBlockStarts[i + 1];
1458 }
1459 superBlocks[i] = new SuperBlock(i, start, end, initialLocals);
1460 }
1461
1462 if (DEBUGSTACKMAP) {
1463 System.out.println("super blocks: ");
1464 for (int i = 0;
1465 i < superBlocks.length && superBlocks[i] != null; i++) {
1466 System.out.println("sb " + i + ": [" +
1467 superBlocks[i].getStart() + ", " +
1468 superBlocks[i].getEnd() + ")");
1469 }
1470 }
1471
1472 superBlockDeps = getSuperBlockDependencies();
1473
1474 verify();
1475
1476 if (DEBUGSTACKMAP) {
1477 System.out.println("type information:");
1478 for (int i = 0; i < superBlocks.length; i++) {
1479 SuperBlock sb = superBlocks[i];
1480 System.out.println("sb " + i + ":");
1481 TypeInfo.print(sb.getLocals(), sb.getStack(),
1482 itsConstantPool);
1483 }
1484 }
1485 }
1486
1487 private SuperBlock getSuperBlockFromOffset(int offset) {
1488 for (int i = 0; i < superBlocks.length; i++) {
1489 SuperBlock sb = superBlocks[i];
1490 if (sb == null) {
1491 break;
1492 } else if (offset >= sb.getStart() && offset < sb.getEnd()) {
1493 return sb;
1494 }
1495 }
1496 throw new IllegalArgumentException("bad offset: " + offset);
1497 }
1498
1499 /**
1500 * Determine whether or not an opcode is an actual end to a super
1501 * block. This includes any returns or unconditional jumps.
1502 */
1503 private boolean isSuperBlockEnd(int opcode) {
1504 switch (opcode) {
1505 case ByteCode.ARETURN:
1506 case ByteCode.FRETURN:
1507 case ByteCode.IRETURN:
1508 case ByteCode.LRETURN:
1509 case ByteCode.RETURN:
1510 case ByteCode.ATHROW:
1511 case ByteCode.GOTO:
1512 case ByteCode.GOTO_W:
1513 case ByteCode.TABLESWITCH:
1514 case ByteCode.LOOKUPSWITCH:
1515 return true;
1516 default:
1517 return false;
1518 }
1519 }
1520
1521 /**
1522 * Calculate partial dependencies for super blocks.
1523 *
1524 * This is used as a workaround for dead code that is generated. Only
1525 * one dependency per super block is given.
1526 */
1527 private SuperBlock[] getSuperBlockDependencies() {
1528 SuperBlock[] deps = new SuperBlock[superBlocks.length];
1529
1530 for (int i = 0; i < itsExceptionTableTop; i++) {
1531 ExceptionTableEntry ete = itsExceptionTable[i];
1532 short startPC = (short) getLabelPC(ete.itsStartLabel);
1533 short handlerPC = (short) getLabelPC(ete.itsHandlerLabel);
1534 SuperBlock handlerSB = getSuperBlockFromOffset(handlerPC);
1535 SuperBlock dep = getSuperBlockFromOffset(startPC);
1536 deps[handlerSB.getIndex()] = dep;
1537 }
1538 int[] targetPCs = itsJumpFroms.getKeys();
1539 for (int i = 0; i < targetPCs.length; i++) {
1540 int targetPC = targetPCs[i];
1541 int branchPC = itsJumpFroms.getInt(targetPC, -1);
1542 SuperBlock branchSB = getSuperBlockFromOffset(branchPC);
1543 SuperBlock targetSB = getSuperBlockFromOffset(targetPC);
1544 deps[targetSB.getIndex()] = branchSB;
1545 }
1546
1547 return deps;
1548 }
1549
1550 /**
1551 * Get the target super block of a branch instruction.
1552 *
1553 * @param bci the index of the branch instruction in the code buffer
1554 */
1555 private SuperBlock getBranchTarget(int bci) {
1556 int target;
1557 if ((itsCodeBuffer[bci] & 0xFF) == ByteCode.GOTO_W) {
1558 target = bci + getOperand(bci + 1, 4);
1559 } else {
1560 target = bci + (short) getOperand(bci + 1, 2);
1561 }
1562 return getSuperBlockFromOffset(target);
1563 }
1564
1565 /**
1566 * Determine whether or not an opcode is a conditional or unconditional
1567 * jump.
1568 */
1569 private boolean isBranch(int opcode) {
1570 switch (opcode) {
1571 case ByteCode.GOTO:
1572 case ByteCode.GOTO_W:
1573 case ByteCode.IFEQ:
1574 case ByteCode.IFGE:
1575 case ByteCode.IFGT:
1576 case ByteCode.IFLE:
1577 case ByteCode.IFLT:
1578 case ByteCode.IFNE:
1579 case ByteCode.IFNONNULL:
1580 case ByteCode.IFNULL:
1581 case ByteCode.IF_ACMPEQ:
1582 case ByteCode.IF_ACMPNE:
1583 case ByteCode.IF_ICMPEQ:
1584 case ByteCode.IF_ICMPGE:
1585 case ByteCode.IF_ICMPGT:
1586 case ByteCode.IF_ICMPLE:
1587 case ByteCode.IF_ICMPLT:
1588 case ByteCode.IF_ICMPNE:
1589 return true;
1590 default:
1591 return false;
1592 }
1593 }
1594
1595 private int getOperand(int offset) {
1596 return getOperand(offset, 1);
1597 }
1598
1599 /**
1600 * Extract a logical operand from the byte code.
1601 *
1602 * This is used, for example, to get branch offsets.
1603 */
1604 private int getOperand(int start, int size) {
1605 int result = 0;
1606 if (size > 4) {
1607 throw new IllegalArgumentException("bad operand size");
1608 }
1609 for (int i = 0; i < size; i++) {
1610 result = (result << 8) | (itsCodeBuffer[start + i] & 0xFF);
1611 }
1612 return result;
1613 }
1614
1615 /**
1616 * Calculate initial local variable and op stack types for each super
1617 * block in the method.
1618 */
1619 private void verify() {
1620 int[] initialLocals = createInitialLocals();
1621 superBlocks[0].merge(initialLocals, initialLocals.length,
1622 new int[0], 0, itsConstantPool);
1623
1624 // Start from the top of the method and queue up block dependencies
1625 // as they come along.
1626 workList = new SuperBlock[] { superBlocks[0] };
1627 workListTop = 1;
1628 executeWorkList();
1629
1630 // Replace dead code with no-ops.
1631 for (int i = 0; i < superBlocks.length; i++) {
1632 SuperBlock sb = superBlocks[i];
1633 if (!sb.isInitialized()) {
1634 killSuperBlock(sb);
1635 }
1636 }
1637 executeWorkList();
1638 }
1639
1640 /**
1641 * Replace the contents of a super block with no-ops.
1642 *
1643 * The above description is not strictly true; the last instruction is
1644 * an athrow instruction. This technique is borrowed from ASM's
1645 * developer guide: http://asm.ow2.org/doc/developer-guide.html#deadcode
1646 *
1647 * The proposed algorithm fills a block with nop, ending it with an
1648 * athrow. The stack map generated would be empty locals with an
1649 * exception on the stack. In theory, it shouldn't matter what the
1650 * locals are, as long as the stack has an exception for the athrow bit.
1651 * However, it turns out that if the code being modified falls into an
1652 * exception handler, it causes problems. Therefore, if it does, then
1653 * we steal the locals from the exception block.
1654 *
1655 * If the block itself is an exception handler, we remove it from the
1656 * exception table to simplify block dependencies.
1657 */
1658 private void killSuperBlock(SuperBlock sb) {
1659 int[] locals = new int[0];
1660 int[] stack = new int[] { TypeInfo.OBJECT("java/lang/Throwable",
1661 itsConstantPool) };
1662
1663 // If the super block is handled by any exception handler, use its
1664 // locals as the killed block's locals. Ignore uninitialized
1665 // handlers, because they will also be killed and removed from the
1666 // exception table.
1667 for (int i = 0; i < itsExceptionTableTop; i++) {
1668 ExceptionTableEntry ete = itsExceptionTable[i];
1669 int eteStart = getLabelPC(ete.itsStartLabel);
1670 int eteEnd = getLabelPC(ete.itsEndLabel);
1671 int handlerPC = getLabelPC(ete.itsHandlerLabel);
1672 SuperBlock handlerSB = getSuperBlockFromOffset(handlerPC);
1673 if ((sb.getStart() > eteStart && sb.getStart() < eteEnd) ||
1674 (eteStart > sb.getStart() && eteStart < sb.getEnd()) &&
1675 handlerSB.isInitialized()) {
1676 locals = handlerSB.getLocals();
1677 break;
1678 }
1679 }
1680
1681 // Remove any exception table entry whose handler is the killed
1682 // block. This removes block dependencies to make stack maps for
1683 // dead blocks easier to create.
1684 for (int i = 0; i < itsExceptionTableTop; i++) {
1685 ExceptionTableEntry ete = itsExceptionTable[i];
1686 int eteStart = getLabelPC(ete.itsStartLabel);
1687 if (eteStart == sb.getStart()) {
1688 for (int j = i + 1; j < itsExceptionTableTop; j++) {
1689 itsExceptionTable[j - 1] = itsExceptionTable[j];
1690 }
1691 itsExceptionTableTop--;
1692 i--;
1693 }
1694 }
1695
1696 sb.merge(locals, locals.length, stack, stack.length,
1697 itsConstantPool);
1698
1699 int end = sb.getEnd() - 1;
1700 itsCodeBuffer[end] = (byte) ByteCode.ATHROW;
1701 for (int bci = sb.getStart(); bci < end; bci++) {
1702 itsCodeBuffer[bci] = (byte) ByteCode.NOP;
1703 }
1704 }
1705
1706 private void executeWorkList() {
1707 while (workListTop > 0) {
1708 SuperBlock work = workList[--workListTop];
1709 work.setInQueue(false);
1710 locals = work.getLocals();
1711 stack = work.getStack();
1712 localsTop = locals.length;
1713 stackTop = stack.length;
1714 executeBlock(work);
1715 }
1716 }
1717
1718 /**
1719 * Simulate the local variable and op stack for a super block.
1720 */
1721 private void executeBlock(SuperBlock work) {
1722 int bc = 0;
1723 int next = 0;
1724
1725 if (DEBUGSTACKMAP) {
1726 System.out.println("working on sb " + work.getIndex());
1727 System.out.println("initial type state:");
1728 TypeInfo.print(locals, localsTop, stack, stackTop,
1729 itsConstantPool);
1730 }
1731
1732 for (int bci = work.getStart(); bci < work.getEnd(); bci += next) {
1733 bc = itsCodeBuffer[bci] & 0xFF;
1734 next = execute(bci);
1735
1736 // If we have a branch to some super block, we need to merge
1737 // the current state of the local table and op stack with what's
1738 // currently stored as the initial state of the super block. If
1739 // something actually changed, we need to add it to the work
1740 // list.
1741 if (isBranch(bc)) {
1742 SuperBlock targetSB = getBranchTarget(bci);
1743 if (DEBUGSTACKMAP) {
1744 System.out.println("sb " + work.getIndex() +
1745 " points to sb " +
1746 targetSB.getIndex() +
1747 " (offset " + bci + " -> " +
1748 targetSB.getStart() + ")");
1749 System.out.println("type state at " + bci + ":");
1750 TypeInfo.print(locals, localsTop, stack, stackTop,
1751 itsConstantPool);
1752 }
1753 flowInto(targetSB);
1754 if (DEBUGSTACKMAP) {
1755 System.out.println("type state of " + targetSB +
1756 " after merge:");
1757 TypeInfo.print(targetSB.getLocals(),
1758 targetSB.getStack(), itsConstantPool);
1759 }
1760 } else if (bc == ByteCode.TABLESWITCH) {
1761 int switchStart = bci + 1 + (3 & ~bci); // 3 - bci % 4
1762 int defaultOffset = getOperand(switchStart, 4);
1763 SuperBlock targetSB =
1764 getSuperBlockFromOffset(bci + defaultOffset);
1765 if (DEBUGSTACK) {
1766 System.out.println("merging sb " + work.getIndex() +
1767 " with sb " + targetSB.getIndex());
1768 }
1769 flowInto(targetSB);
1770 int low = getOperand(switchStart + 4, 4);
1771 int high = getOperand(switchStart + 8, 4);
1772 int numCases = high - low + 1;
1773 int caseBase = switchStart + 12;
1774 for (int i = 0; i < numCases; i++) {
1775 int label = bci + getOperand(caseBase + 4 * i, 4);
1776 targetSB = getSuperBlockFromOffset(label);
1777 if (DEBUGSTACKMAP) {
1778 System.out.println("merging sb " +
1779 work.getIndex() + " with sb " +
1780 targetSB.getIndex());
1781 }
1782 flowInto(targetSB);
1783 }
1784 }
1785
1786 for (int i = 0; i < itsExceptionTableTop; i++) {
1787 ExceptionTableEntry ete = itsExceptionTable[i];
1788 short startPC = (short) getLabelPC(ete.itsStartLabel);
1789 short endPC = (short) getLabelPC(ete.itsEndLabel);
1790 if (bci < startPC || bci >= endPC) {
1791 continue;
1792 }
1793 short handlerPC =
1794 (short) getLabelPC(ete.itsHandlerLabel);
1795 SuperBlock sb = getSuperBlockFromOffset(handlerPC);
1796 int exceptionType;
1797
1798 if (ete.itsCatchType == 0) {
1799 exceptionType = TypeInfo.OBJECT(
1800 itsConstantPool.addClass("java/lang/Throwable"));
1801 } else {
1802 exceptionType = TypeInfo.OBJECT(ete.itsCatchType);
1803 }
1804 sb.merge(locals, localsTop, new int[] { exceptionType }, 1,
1805 itsConstantPool);
1806 addToWorkList(sb);
1807 }
1808 }
1809
1810 if (DEBUGSTACKMAP) {
1811 System.out.println("end of sb " + work.getIndex() + ":");
1812 TypeInfo.print(locals, localsTop, stack, stackTop,
1813 itsConstantPool);
1814 }
1815
1816 // Check the last instruction to see if it is a true end of a
1817 // super block (ie., if the instruction is a return). If it
1818 // isn't, we need to continue processing the next chunk.
1819 if (!isSuperBlockEnd(bc)) {
1820 int nextIndex = work.getIndex() + 1;
1821 if (nextIndex < superBlocks.length) {
1822 if (DEBUGSTACKMAP) {
1823 System.out.println("continuing from sb " +
1824 work.getIndex() + " into sb " +
1825 nextIndex);
1826 }
1827 flowInto(superBlocks[nextIndex]);
1828 }
1829 }
1830 }
1831
1832 /**
1833 * Perform a merge of type state and add the super block to the work
1834 * list if the merge changed anything.
1835 */
1836 private void flowInto(SuperBlock sb) {
1837 if (sb.merge(locals, localsTop, stack, stackTop, itsConstantPool)) {
1838 addToWorkList(sb);
1839 }
1840 }
1841
1842 private void addToWorkList(SuperBlock sb) {
1843 if (!sb.isInQueue()) {
1844 sb.setInQueue(true);
1845 sb.setInitialized(true);
1846 if (workListTop == workList.length) {
1847 SuperBlock[] tmp = new SuperBlock[workListTop * 2];
1848 System.arraycopy(workList, 0, tmp, 0, workListTop);
1849 workList = tmp;
1850 }
1851 workList[workListTop++] = sb;
1852 }
1853 }
1854
1855 /**
1856 * Execute a single byte code instruction.
1857 *
1858 * @param bci the index of the byte code instruction to execute
1859 * @return the length of the byte code instruction
1860 */
1861 private int execute(int bci) {
1862 int bc = itsCodeBuffer[bci] & 0xFF;
1863 int type, type2, index;
1864 int length = 0;
1865 long lType, lType2;
1866 String className;
1867
1868 switch (bc) {
1869 case ByteCode.NOP:
1870 case ByteCode.IINC:
1871 case ByteCode.GOTO:
1872 case ByteCode.GOTO_W:
1873 // No change
1874 break;
1875 case ByteCode.CHECKCAST:
1876 pop();
1877 push(TypeInfo.OBJECT(getOperand(bci + 1, 2)));
1878 break;
1879 case ByteCode.IASTORE: // pop; pop; pop
1880 case ByteCode.LASTORE:
1881 case ByteCode.FASTORE:
1882 case ByteCode.DASTORE:
1883 case ByteCode.AASTORE:
1884 case ByteCode.BASTORE:
1885 case ByteCode.CASTORE:
1886 case ByteCode.SASTORE:
1887 pop();
1888 // fallthru
1889 case ByteCode.PUTFIELD: // pop; pop
1890 case ByteCode.IF_ICMPEQ:
1891 case ByteCode.IF_ICMPNE:
1892 case ByteCode.IF_ICMPLT:
1893 case ByteCode.IF_ICMPGE:
1894 case ByteCode.IF_ICMPGT:
1895 case ByteCode.IF_ICMPLE:
1896 case ByteCode.IF_ACMPEQ:
1897 case ByteCode.IF_ACMPNE:
1898 pop();
1899 // fallthru
1900 case ByteCode.IFEQ: // pop
1901 case ByteCode.IFNE:
1902 case ByteCode.IFLT:
1903 case ByteCode.IFGE:
1904 case ByteCode.IFGT:
1905 case ByteCode.IFLE:
1906 case ByteCode.IFNULL:
1907 case ByteCode.IFNONNULL:
1908 case ByteCode.POP:
1909 case ByteCode.MONITORENTER:
1910 case ByteCode.MONITOREXIT:
1911 case ByteCode.PUTSTATIC:
1912 pop();
1913 break;
1914 case ByteCode.POP2:
1915 pop2();
1916 break;
1917 case ByteCode.ACONST_NULL:
1918 push(TypeInfo.NULL);
1919 break;
1920 case ByteCode.IALOAD: // pop; pop; push(INTEGER)
1921 case ByteCode.BALOAD:
1922 case ByteCode.CALOAD:
1923 case ByteCode.SALOAD:
1924 case ByteCode.IADD:
1925 case ByteCode.ISUB:
1926 case ByteCode.IMUL:
1927 case ByteCode.IDIV:
1928 case ByteCode.IREM:
1929 case ByteCode.ISHL:
1930 case ByteCode.ISHR:
1931 case ByteCode.IUSHR:
1932 case ByteCode.IAND:
1933 case ByteCode.IOR:
1934 case ByteCode.IXOR:
1935 case ByteCode.LCMP:
1936 case ByteCode.FCMPL:
1937 case ByteCode.FCMPG:
1938 case ByteCode.DCMPL:
1939 case ByteCode.DCMPG:
1940 pop();
1941 // fallthru
1942 case ByteCode.INEG: // pop; push(INTEGER)
1943 case ByteCode.L2I:
1944 case ByteCode.F2I:
1945 case ByteCode.D2I:
1946 case ByteCode.I2B:
1947 case ByteCode.I2C:
1948 case ByteCode.I2S:
1949 case ByteCode.ARRAYLENGTH:
1950 case ByteCode.INSTANCEOF:
1951 pop();
1952 // fallthru
1953 case ByteCode.ICONST_M1: // push(INTEGER)
1954 case ByteCode.ICONST_0:
1955 case ByteCode.ICONST_1:
1956 case ByteCode.ICONST_2:
1957 case ByteCode.ICONST_3:
1958 case ByteCode.ICONST_4:
1959 case ByteCode.ICONST_5:
1960 case ByteCode.ILOAD:
1961 case ByteCode.ILOAD_0:
1962 case ByteCode.ILOAD_1:
1963 case ByteCode.ILOAD_2:
1964 case ByteCode.ILOAD_3:
1965 case ByteCode.BIPUSH:
1966 case ByteCode.SIPUSH:
1967 push(TypeInfo.INTEGER);
1968 break;
1969 case ByteCode.LALOAD: // pop; pop; push(LONG)
1970 case ByteCode.LADD:
1971 case ByteCode.LSUB:
1972 case ByteCode.LMUL:
1973 case ByteCode.LDIV:
1974 case ByteCode.LREM:
1975 case ByteCode.LSHL:
1976 case ByteCode.LSHR:
1977 case ByteCode.LUSHR:
1978 case ByteCode.LAND:
1979 case ByteCode.LOR:
1980 case ByteCode.LXOR:
1981 pop();
1982 // fallthru
1983 case ByteCode.LNEG: // pop; push(LONG)
1984 case ByteCode.I2L:
1985 case ByteCode.F2L:
1986 case ByteCode.D2L:
1987 pop();
1988 // fallthru
1989 case ByteCode.LCONST_0: // push(LONG)
1990 case ByteCode.LCONST_1:
1991 case ByteCode.LLOAD:
1992 case ByteCode.LLOAD_0:
1993 case ByteCode.LLOAD_1:
1994 case ByteCode.LLOAD_2:
1995 case ByteCode.LLOAD_3:
1996 push(TypeInfo.LONG);
1997 break;
1998 case ByteCode.FALOAD: // pop; pop; push(FLOAT)
1999 case ByteCode.FADD:
2000 case ByteCode.FSUB:
2001 case ByteCode.FMUL:
2002 case ByteCode.FDIV:
2003 case ByteCode.FREM:
2004 pop();
2005 // fallthru
2006 case ByteCode.FNEG: // pop; push(FLOAT)
2007 case ByteCode.I2F:
2008 case ByteCode.L2F:
2009 case ByteCode.D2F:
2010 pop();
2011 // fallthru
2012 case ByteCode.FCONST_0: // push(FLOAT)
2013 case ByteCode.FCONST_1:
2014 case ByteCode.FCONST_2:
2015 case ByteCode.FLOAD:
2016 case ByteCode.FLOAD_0:
2017 case ByteCode.FLOAD_1:
2018 case ByteCode.FLOAD_2:
2019 case ByteCode.FLOAD_3:
2020 push(TypeInfo.FLOAT);
2021 break;
2022 case ByteCode.DALOAD: // pop; pop; push(DOUBLE)
2023 case ByteCode.DADD:
2024 case ByteCode.DSUB:
2025 case ByteCode.DMUL:
2026 case ByteCode.DDIV:
2027 case ByteCode.DREM:
2028 pop();
2029 // fallthru
2030 case ByteCode.DNEG: // pop; push(DOUBLE)
2031 case ByteCode.I2D:
2032 case ByteCode.L2D:
2033 case ByteCode.F2D:
2034 pop();
2035 // fallthru
2036 case ByteCode.DCONST_0: // push(DOUBLE)
2037 case ByteCode.DCONST_1:
2038 case ByteCode.DLOAD:
2039 case ByteCode.DLOAD_0:
2040 case ByteCode.DLOAD_1:
2041 case ByteCode.DLOAD_2:
2042 case ByteCode.DLOAD_3:
2043 push(TypeInfo.DOUBLE);
2044 break;
2045 case ByteCode.ISTORE:
2046 executeStore(getOperand(bci + 1, wide ? 2 : 1), TypeInfo.INTEGER);
2047 break;
2048 case ByteCode.ISTORE_0:
2049 case ByteCode.ISTORE_1:
2050 case ByteCode.ISTORE_2:
2051 case ByteCode.ISTORE_3:
2052 executeStore(bc - ByteCode.ISTORE_0, TypeInfo.INTEGER);
2053 break;
2054 case ByteCode.LSTORE:
2055 executeStore(getOperand(bci + 1, wide ? 2 : 1), TypeInfo.LONG);
2056 break;
2057 case ByteCode.LSTORE_0:
2058 case ByteCode.LSTORE_1:
2059 case ByteCode.LSTORE_2:
2060 case ByteCode.LSTORE_3:
2061 executeStore(bc - ByteCode.LSTORE_0, TypeInfo.LONG);
2062 break;
2063 case ByteCode.FSTORE:
2064 executeStore(getOperand(bci + 1, wide ? 2 : 1), TypeInfo.FLOAT);
2065 break;
2066 case ByteCode.FSTORE_0:
2067 case ByteCode.FSTORE_1:
2068 case ByteCode.FSTORE_2:
2069 case ByteCode.FSTORE_3:
2070 executeStore(bc - ByteCode.FSTORE_0, TypeInfo.FLOAT);
2071 break;
2072 case ByteCode.DSTORE:
2073 executeStore(getOperand(bci + 1, wide ? 2 : 1), TypeInfo.DOUBLE);
2074 break;
2075 case ByteCode.DSTORE_0:
2076 case ByteCode.DSTORE_1:
2077 case ByteCode.DSTORE_2:
2078 case ByteCode.DSTORE_3:
2079 executeStore(bc - ByteCode.DSTORE_0, TypeInfo.DOUBLE);
2080 break;
2081 case ByteCode.ALOAD:
2082 executeALoad(getOperand(bci + 1, wide ? 2 : 1));
2083 break;
2084 case ByteCode.ALOAD_0:
2085 case ByteCode.ALOAD_1:
2086 case ByteCode.ALOAD_2:
2087 case ByteCode.ALOAD_3:
2088 executeALoad(bc - ByteCode.ALOAD_0);
2089 break;
2090 case ByteCode.ASTORE:
2091 executeAStore(getOperand(bci + 1, wide ? 2 : 1));
2092 break;
2093 case ByteCode.ASTORE_0:
2094 case ByteCode.ASTORE_1:
2095 case ByteCode.ASTORE_2:
2096 case ByteCode.ASTORE_3:
2097 executeAStore(bc - ByteCode.ASTORE_0);
2098 break;
2099 case ByteCode.IRETURN:
2100 case ByteCode.LRETURN:
2101 case ByteCode.FRETURN:
2102 case ByteCode.DRETURN:
2103 case ByteCode.ARETURN:
2104 case ByteCode.RETURN:
2105 clearStack();
2106 break;
2107 case ByteCode.ATHROW:
2108 type = pop();
2109 clearStack();
2110 push(type);
2111 break;
2112 case ByteCode.SWAP:
2113 type = pop();
2114 type2 = pop();
2115 push(type);
2116 push(type2);
2117 break;
2118 case ByteCode.LDC:
2119 case ByteCode.LDC_W:
2120 case ByteCode.LDC2_W:
2121 if (bc == ByteCode.LDC) {
2122 index = getOperand(bci + 1);
2123 } else {
2124 index = getOperand(bci + 1, 2);
2125 }
2126 byte constType = itsConstantPool.getConstantType(index);
2127 switch (constType) {
2128 case ConstantPool.CONSTANT_Double:
2129 push(TypeInfo.DOUBLE);
2130 break;
2131 case ConstantPool.CONSTANT_Float:
2132 push(TypeInfo.FLOAT);
2133 break;
2134 case ConstantPool.CONSTANT_Long:
2135 push(TypeInfo.LONG);
2136 break;
2137 case ConstantPool.CONSTANT_Integer:
2138 push(TypeInfo.INTEGER);
2139 break;
2140 case ConstantPool.CONSTANT_String:
2141 push(TypeInfo.OBJECT("java/lang/String",
2142 itsConstantPool));
2143 break;
2144 default:
2145 throw new IllegalArgumentException(
2146 "bad const type " + constType);
2147 }
2148 break;
2149 case ByteCode.NEW:
2150 push(TypeInfo.UNINITIALIZED_VARIABLE(bci));
2151 break;
2152 case ByteCode.NEWARRAY:
2153 pop();
2154 char componentType =
2155 arrayTypeToName(itsCodeBuffer[bci + 1]);
2156 index = itsConstantPool.addClass("[" + componentType);
2157 push(TypeInfo.OBJECT((short) index));
2158 break;
2159 case ByteCode.ANEWARRAY:
2160 index = getOperand(bci + 1, 2);
2161 className = (String) itsConstantPool.getConstantData(index);
2162 pop();
2163 push(TypeInfo.OBJECT("[L" + className + ';',
2164 itsConstantPool));
2165 break;
2166 case ByteCode.INVOKEVIRTUAL:
2167 case ByteCode.INVOKESPECIAL:
2168 case ByteCode.INVOKESTATIC:
2169 case ByteCode.INVOKEINTERFACE:
2170 index = getOperand(bci + 1, 2);
2171 FieldOrMethodRef m = (FieldOrMethodRef)
2172 itsConstantPool.getConstantData(index);
2173 String methodType = m.getType();
2174 String methodName = m.getName();
2175 int parameterCount = sizeOfParameters(methodType) >>> 16;
2176 for (int i = 0; i < parameterCount; i++) {
2177 pop();
2178 }
2179 if (bc != ByteCode.INVOKESTATIC) {
2180 int instType = pop();
2181 int tag = TypeInfo.getTag(instType);
2182 if (tag == TypeInfo.UNINITIALIZED_VARIABLE(0) ||
2183 tag == TypeInfo.UNINITIALIZED_THIS) {
2184 if ("<init>".equals(methodName)) {
2185 int newType =
2186 TypeInfo.OBJECT(itsThisClassIndex);
2187 initializeTypeInfo(instType, newType);
2188 } else {
2189 throw new IllegalStateException("bad instance");
2190 }
2191 }
2192 }
2193 int rParen = methodType.indexOf(')');
2194 String returnType = methodType.substring(rParen + 1);
2195 returnType = descriptorToInternalName(returnType);
2196 if (!returnType.equals("V")) {
2197 push(TypeInfo.fromType(returnType, itsConstantPool));
2198 }
2199 break;
2200 case ByteCode.GETFIELD:
2201 pop();
2202 // fallthru
2203 case ByteCode.GETSTATIC:
2204 index = getOperand(bci + 1, 2);
2205 FieldOrMethodRef f = (FieldOrMethodRef)
2206 itsConstantPool.getConstantData(index);
2207 String fieldType = descriptorToInternalName(f.getType());
2208 push(TypeInfo.fromType(fieldType, itsConstantPool));
2209 break;
2210 case ByteCode.DUP:
2211 type = pop();
2212 push(type);
2213 push(type);
2214 break;
2215 case ByteCode.DUP_X1:
2216 type = pop();
2217 type2 = pop();
2218 push(type);
2219 push(type2);
2220 push(type);
2221 break;
2222 case ByteCode.DUP_X2:
2223 type = pop();
2224 lType = pop2();
2225 push(type);
2226 push2(lType);
2227 push(type);
2228 break;
2229 case ByteCode.DUP2:
2230 lType = pop2();
2231 push2(lType);
2232 push2(lType);
2233 break;
2234 case ByteCode.DUP2_X1:
2235 lType = pop2();
2236 type = pop();
2237 push2(lType);
2238 push(type);
2239 push2(lType);
2240 break;
2241 case ByteCode.DUP2_X2:
2242 lType = pop2();
2243 lType2 = pop2();
2244 push2(lType);
2245 push2(lType2);
2246 push2(lType);
2247 break;
2248 case ByteCode.TABLESWITCH:
2249 int switchStart = bci + 1 + (3 & ~bci);
2250 int low = getOperand(switchStart + 4, 4);
2251 int high = getOperand(switchStart + 8, 4);
2252 length = 4 * (high - low + 4) + switchStart - bci;
2253 pop();
2254 break;
2255 case ByteCode.AALOAD:
2256 pop();
2257 int typeIndex = pop() >>> 8;
2258 className =
2259 (String) itsConstantPool.getConstantData(typeIndex);
2260 String arrayType = className;
2261 if (arrayType.charAt(0) != '[') {
2262 throw new IllegalStateException("bad array type");
2263 }
2264 String elementDesc = arrayType.substring(1);
2265 String elementType = descriptorToInternalName(elementDesc);
2266 typeIndex = itsConstantPool.addClass(elementType);
2267 push(TypeInfo.OBJECT(typeIndex));
2268 break;
2269 case ByteCode.WIDE:
2270 // Alters behaviour of next instruction
2271 wide = true;
2272 break;
2273 case ByteCode.MULTIANEWARRAY:
2274 case ByteCode.LOOKUPSWITCH:
2275 // Currently not used in any part of Rhino, so ignore it
2276 case ByteCode.JSR: // TODO: JSR is deprecated
2277 case ByteCode.RET:
2278 case ByteCode.JSR_W:
2279 default:
2280 throw new IllegalArgumentException("bad opcode: " + bc);
2281 }
2282
2283 if (length == 0) {
2284 length = opcodeLength(bc, wide);
2285 }
2286 if (wide && bc != ByteCode.WIDE) {
2287 wide = false;
2288 }
2289 return length;
2290 }
2291
2292 private void executeALoad(int localIndex) {
2293 int type = getLocal(localIndex);
2294 int tag = TypeInfo.getTag(type);
2295 if (tag == TypeInfo.OBJECT_TAG ||
2296 tag == TypeInfo.UNINITIALIZED_THIS ||
2297 tag == TypeInfo.UNINITIALIZED_VAR_TAG ||
2298 tag == TypeInfo.NULL) {
2299 push(type);
2300 } else {
2301 throw new IllegalStateException("bad local variable type: " +
2302 type + " at index: " +
2303 localIndex);
2304 }
2305 }
2306
2307 private void executeAStore(int localIndex) {
2308 setLocal(localIndex, pop());
2309 }
2310
2311 private void executeStore(int localIndex, int typeInfo) {
2312 pop();
2313 setLocal(localIndex, typeInfo);
2314 }
2315
2316 /**
2317 * Change an UNINITIALIZED_OBJECT or UNINITIALIZED_THIS to the proper
2318 * type of the object. This occurs when the proper constructor is
2319 * invoked.
2320 */
2321 private void initializeTypeInfo(int prevType, int newType) {
2322 initializeTypeInfo(prevType, newType, locals, localsTop);
2323 initializeTypeInfo(prevType, newType, stack, stackTop);
2324 }
2325
2326 private void initializeTypeInfo(int prevType, int newType, int[] data,
2327 int dataTop) {
2328 for (int i = 0; i < dataTop; i++) {
2329 if (data[i] == prevType) {
2330 data[i] = newType;
2331 }
2332 }
2333 }
2334
2335 private int getLocal(int localIndex) {
2336 if (localIndex < localsTop) {
2337 return locals[localIndex];
2338 } else {
2339 return TypeInfo.TOP;
2340 }
2341 }
2342
2343 private void setLocal(int localIndex, int typeInfo) {
2344 if (localIndex >= localsTop) {
2345 int[] tmp = new int[localIndex + 1];
2346 System.arraycopy(locals, 0, tmp, 0, localsTop);
2347 locals = tmp;
2348 localsTop = localIndex + 1;
2349 }
2350 locals[localIndex] = typeInfo;
2351 }
2352
2353 private void push(int typeInfo) {
2354 if (stackTop == stack.length) {
2355 int[] tmp = new int[Math.max(stackTop * 2, 4)];
2356 System.arraycopy(stack, 0, tmp, 0, stackTop);
2357 stack = tmp;
2358 }
2359 stack[stackTop++] = typeInfo;
2360 }
2361
2362 private int pop() {
2363 return stack[--stackTop];
2364 }
2365
2366 /**
2367 * Push two words onto the op stack.
2368 *
2369 * This is only meant to be used as a complement to pop2(), and both
2370 * methods are helpers for the more complex DUP operations.
2371 */
2372 private void push2(long typeInfo) {
2373 push((int) (typeInfo & 0xFFFFFF));
2374 typeInfo >>>= 32;
2375 if (typeInfo != 0) {
2376 push((int) (typeInfo & 0xFFFFFF));
2377 }
2378 }
2379
2380 /**
2381 * Pop two words from the op stack.
2382 *
2383 * If the top of the stack is a DOUBLE or LONG, then the bottom 32 bits
2384 * reflects the appropriate type and the top 32 bits are 0. Otherwise,
2385 * the top 32 bits are the first word on the stack and the lower 32
2386 * bits are the second word on the stack.
2387 */
2388 private long pop2() {
2389 long type = pop();
2390 if (TypeInfo.isTwoWords((int) type)) {
2391 return type;
2392 } else {
2393 return type << 32 | (pop() & 0xFFFFFF);
2394 }
2395 }
2396
2397 private void clearStack() {
2398 stackTop = 0;
2399 }
2400
2401 /**
2402 * Compute the output size of the stack map table.
2403 *
2404 * Because this would share much in common with actual writing of the
2405 * stack map table, we instead just write the stack map table to a
2406 * buffer and return the size from it. The buffer is later used in
2407 * the actual writing of bytecode.
2408 */
2409 int computeWriteSize() {
2410 // Allocate a buffer that can handle the worst case size of the
2411 // stack map to prevent lots of reallocations.
2412 int writeSize = getWorstCaseWriteSize();
2413 rawStackMap = new byte[writeSize];
2414 computeRawStackMap();
2415 return rawStackMapTop + 2;
2416 }
2417
2418 int write(byte[] data, int offset) {
2419 offset = putInt32(rawStackMapTop + 2, data, offset);
2420 offset = putInt16(superBlocks.length - 1, data, offset);
2421 System.arraycopy(rawStackMap, 0, data, offset, rawStackMapTop);
2422 return offset + rawStackMapTop;
2423 }
2424
2425 /**
2426 * Compute a space-optimal stack map table.
2427 */
2428 private void computeRawStackMap() {
2429 SuperBlock prev = superBlocks[0];
2430 int[] prevLocals = prev.getTrimmedLocals();
2431 int prevOffset = -1;
2432 for (int i = 1; i < superBlocks.length; i++) {
2433 SuperBlock current = superBlocks[i];
2434 int[] currentLocals = current.getTrimmedLocals();
2435 int[] currentStack = current.getStack();
2436 int offsetDelta = current.getStart() - prevOffset - 1;
2437
2438 if (currentStack.length == 0) {
2439 int last = prevLocals.length > currentLocals.length ?
2440 currentLocals.length : prevLocals.length;
2441 int delta = Math.abs(prevLocals.length -
2442 currentLocals.length);
2443 int j;
2444 // Compare locals until one is different or the end of a
2445 // local variable array is reached
2446 for (j = 0; j < last; j++) {
2447 if (prevLocals[j] != currentLocals[j]) {
2448 break;
2449 }
2450 }
2451 if (j == currentLocals.length && delta == 0) {
2452 // All of the compared locals are equal and the local
2453 // arrays are of equal size
2454 writeSameFrame(currentLocals, offsetDelta);
2455 } else if (j == currentLocals.length && delta <= 3) {
2456 // All of the compared locals are equal and the current
2457 // frame has less locals than the previous frame
2458 writeChopFrame(delta, offsetDelta);
2459 } else if (j == prevLocals.length && delta <= 3) {
2460 // All of the compared locals are equal and the current
2461 // frame has more locals than the previous frame
2462 writeAppendFrame(currentLocals, delta, offsetDelta);
2463 } else {
2464 // Not all locals were compared were equal, so a full
2465 // frame is necessary
2466 writeFullFrame(currentLocals, currentStack,
2467 offsetDelta);
2468 }
2469 } else if (currentStack.length == 1) {
2470 if (Arrays.equals(prevLocals, currentLocals)) {
2471 writeSameLocalsOneStackItemFrame(currentLocals,
2472 currentStack,
2473 offsetDelta);
2474 } else {
2475 // Output a full frame, since no other frame types have
2476 // one operand stack item.
2477 writeFullFrame(currentLocals, currentStack,
2478 offsetDelta);
2479 }
2480 } else {
2481 // Any stack map frame that has more than one operand stack
2482 // item has to be a full frame. All other frame types have
2483 // at most one item on the stack.
2484 writeFullFrame(currentLocals, currentStack, offsetDelta);
2485 }
2486
2487 prev = current;
2488 prevLocals = currentLocals;
2489 prevOffset = current.getStart();
2490 }
2491 }
2492
2493 /**
2494 * Get the worst case write size of the stack map table.
2495 *
2496 * This computes how much full frames would take, if each full frame
2497 * contained the maximum number of locals and stack operands, and each
2498 * verification type was 3 bytes.
2499 */
2500 private int getWorstCaseWriteSize() {
2501 return (superBlocks.length - 1) * (7 + itsMaxLocals * 3 +
2502 itsMaxStack * 3);
2503 }
2504
2505 private void writeSameFrame(int[] locals, int offsetDelta) {
2506 if (offsetDelta <= 63) {
2507 // Output a same_frame frame. Despite the name,
2508 // the operand stack may differ, but the current
2509 // operand stack must be empty.
2510 rawStackMap[rawStackMapTop++] = (byte) offsetDelta;
2511 } else {
2512 // Output a same_frame_extended frame. Similar to
2513 // the above, except with a larger offset delta.
2514 rawStackMap[rawStackMapTop++] = (byte) 251;
2515 rawStackMapTop = putInt16(offsetDelta, rawStackMap,
2516 rawStackMapTop);
2517 }
2518 }
2519
2520 private void writeSameLocalsOneStackItemFrame(int[] locals,
2521 int[] stack,
2522 int offsetDelta) {
2523 if (offsetDelta <= 63) {
2524 // Output a same_locals_1_stack_item frame. Similar
2525 // to same_frame, only with one item on the operand
2526 // stack instead of zero.
2527 rawStackMap[rawStackMapTop++] = (byte) (64 + offsetDelta);
2528 } else {
2529 // Output a same_locals_1_stack_item_extended frame.
2530 // Similar to same_frame_extended, only with one
2531 // item on the operand stack instead of zero.
2532 rawStackMap[rawStackMapTop++] = (byte) 247;
2533 rawStackMapTop = putInt16(offsetDelta, rawStackMap,
2534 rawStackMapTop);
2535 }
2536 writeType(stack[0]);
2537 }
2538
2539 private void writeFullFrame(int[] locals, int[] stack,
2540 int offsetDelta) {
2541 rawStackMap[rawStackMapTop++] = (byte) 255;
2542 rawStackMapTop = putInt16(offsetDelta, rawStackMap, rawStackMapTop);
2543 rawStackMapTop = putInt16(locals.length, rawStackMap,
2544 rawStackMapTop);
2545 rawStackMapTop = writeTypes(locals);
2546 rawStackMapTop = putInt16(stack.length, rawStackMap,
2547 rawStackMapTop);
2548 rawStackMapTop = writeTypes(stack);
2549 }
2550
2551 private void writeAppendFrame(int[] locals, int localsDelta,
2552 int offsetDelta) {
2553 int start = locals.length - localsDelta;
2554 rawStackMap[rawStackMapTop++] = (byte) (251 + localsDelta);
2555 rawStackMapTop = putInt16(offsetDelta, rawStackMap, rawStackMapTop);
2556 rawStackMapTop = writeTypes(locals, start);
2557 }
2558
2559 private void writeChopFrame(int localsDelta, int offsetDelta) {
2560 rawStackMap[rawStackMapTop++] = (byte) (251 - localsDelta);
2561 rawStackMapTop = putInt16(offsetDelta, rawStackMap, rawStackMapTop);
2562 }
2563
2564 private int writeTypes(int[] types) {
2565 return writeTypes(types, 0);
2566 }
2567
2568 private int writeTypes(int[] types, int start) {
2569 int startOffset = rawStackMapTop;
2570 for (int i = start; i < types.length; i++) {
2571 rawStackMapTop = writeType(types[i]);
2572 }
2573 return rawStackMapTop;
2574 }
2575
2576 private int writeType(int type) {
2577 int tag = type & 0xFF;
2578 rawStackMap[rawStackMapTop++] = (byte) tag;
2579 if (tag == TypeInfo.OBJECT_TAG ||
2580 tag == TypeInfo.UNINITIALIZED_VAR_TAG) {
2581 rawStackMapTop = putInt16(type >>> 8, rawStackMap,
2582 rawStackMapTop);
2583 }
2584 return rawStackMapTop;
2585 }
2586
2587 // Intermediate operand stack and local variable state. During
2588 // execution of a block, these are initialized to copies of the initial
2589 // block type state and are modified by the actual stack/local
2590 // emulation.
2591 private int[] locals;
2592 private int localsTop;
2593 private int[] stack;
2594 private int stackTop;
2595
2596 private SuperBlock[] workList;
2597 private int workListTop;
2598
2599 private SuperBlock[] superBlocks;
2600 private SuperBlock[] superBlockDeps;
2601
2602 private byte[] rawStackMap;
2603 private int rawStackMapTop;
2604
2605 private boolean wide;
2606
2607 static final boolean DEBUGSTACKMAP = false;
2608 }
2609
2610 /**
2611 * Convert a newarray operand into an internal type.
2612 */
2613 private static char arrayTypeToName(int type) {
2614 switch (type) {
2615 case ByteCode.T_BOOLEAN:
2616 return 'Z';
2617 case ByteCode.T_CHAR:
2618 return 'C';
2619 case ByteCode.T_FLOAT:
2620 return 'F';
2621 case ByteCode.T_DOUBLE:
2622 return 'D';
2623 case ByteCode.T_BYTE:
2624 return 'B';
2625 case ByteCode.T_SHORT:
2626 return 'S';
2627 case ByteCode.T_INT:
2628 return 'I';
2629 case ByteCode.T_LONG:
2630 return 'J';
2631 default:
2632 throw new IllegalArgumentException("bad operand");
2633 }
2634 }
2635
2636 /**
2637 * Convert a class descriptor into an internal name.
2638 *
2639 * For example, descriptor Ljava/lang/Object; becomes java/lang/Object.
2640 */
2641 private static String classDescriptorToInternalName(String descriptor) {
2642 return descriptor.substring(1, descriptor.length() - 1);
2643 }
2644
2645 /**
2646 * Convert a non-method type descriptor into an internal type.
2647 *
2648 * @param descriptor the simple type descriptor to convert
2649 */
2650 private static String descriptorToInternalName(String descriptor) {
2651 switch (descriptor.charAt(0)) {
2652 case 'B':
2653 case 'C':
2654 case 'D':
2655 case 'F':
2656 case 'I':
2657 case 'J':
2658 case 'S':
2659 case 'Z':
2660 case 'V':
2661 case '[':
2662 return descriptor;
2663 case 'L':
2664 return classDescriptorToInternalName(descriptor);
2665 default:
2666 throw new IllegalArgumentException("bad descriptor:" +
2667 descriptor);
2668 }
2669 }
2670
2671 /**
2672 * Compute the initial local variable array for the current method.
2673 *
2674 * Creates an array of the size of the method's max locals, regardless of
2675 * the number of parameters in the method.
2676 */
2677 private int[] createInitialLocals() {
2678 int[] initialLocals = new int[itsMaxLocals];
2679 int localsTop = 0;
2680 // Instance methods require the first local variable in the array
2681 // to be "this". However, if the method being created is a
2682 // constructor, aka the method is <init>, then the type of "this"
2683 // should be StackMapTable.UNINITIALIZED_THIS
2684 if ((itsCurrentMethod.getFlags() & ACC_STATIC) == 0) {
2685 if ("<init>".equals(itsCurrentMethod.getName())) {
2686 initialLocals[localsTop++] = TypeInfo.UNINITIALIZED_THIS;
2687 } else {
2688 initialLocals[localsTop++] = TypeInfo.OBJECT(itsThisClassIndex);
2689 }
2690 }
2691
2692 // No error checking should be necessary, sizeOfParameters does this
2693 String type = itsCurrentMethod.getType();
2694 int lParenIndex = type.indexOf('(');
2695 int rParenIndex = type.indexOf(')');
2696 if (lParenIndex != 0 || rParenIndex < 0) {
2697 throw new IllegalArgumentException("bad method type");
2698 }
2699 int start = lParenIndex + 1;
2700 StringBuilder paramType = new StringBuilder();
2701 while (start < rParenIndex) {
2702 switch (type.charAt(start)) {
2703 case 'B':
2704 case 'C':
2705 case 'D':
2706 case 'F':
2707 case 'I':
2708 case 'J':
2709 case 'S':
2710 case 'Z':
2711 paramType.append(type.charAt(start));
2712 ++start;
2713 break;
2714 case 'L':
2715 int end = type.indexOf(';', start) + 1;
2716 String name = type.substring(start, end);
2717 paramType.append(name);
2718 start = end;
2719 break;
2720 case '[':
2721 paramType.append('[');
2722 ++start;
2723 continue;
2724 }
2725 String internalType =
2726 descriptorToInternalName(paramType.toString());
2727 int typeInfo = TypeInfo.fromType(internalType, itsConstantPool);
2728 initialLocals[localsTop++] = typeInfo;
2729 if (TypeInfo.isTwoWords(typeInfo)) {
2730 localsTop++;
2731 }
2732 paramType.setLength(0);
2733 }
2734 return initialLocals;
2735 }
2736
2737 /**
2738 * Write the class file to the OutputStream.
2739 *
2740 * @param oStream the stream to write to
2741 * @throws IOException if writing to the stream produces an exception
2742 */
2743 public void write(OutputStream oStream)
2744 throws IOException
2745 {
2746 byte[] array = toByteArray();
2747 oStream.write(array);
2748 }
2749
2750 private int getWriteSize()
2751 {
2752 int size = 0;
2753
2754 if (itsSourceFileNameIndex != 0) {
2755 itsConstantPool.addUtf8("SourceFile");
2756 }
2757
2758 size += 8; //writeLong(FileHeaderConstant);
2759 size += itsConstantPool.getWriteSize();
2760 size += 2; //writeShort(itsFlags);
2761 size += 2; //writeShort(itsThisClassIndex);
2762 size += 2; //writeShort(itsSuperClassIndex);
2763 size += 2; //writeShort(itsInterfaces.size());
2764 size += 2 * itsInterfaces.size();
2765
2766 size += 2; //writeShort(itsFields.size());
2767 for (int i = 0; i < itsFields.size(); i++) {
2768 size += ((ClassFileField)(itsFields.get(i))).getWriteSize();
2769 }
2770
2771 size += 2; //writeShort(itsMethods.size());
2772 for (int i = 0; i < itsMethods.size(); i++) {
2773 size += ((ClassFileMethod)(itsMethods.get(i))).getWriteSize();
2774 }
2775
2776 if (itsSourceFileNameIndex != 0) {
2777 size += 2; //writeShort(1); attributes count
2778 size += 2; //writeShort(sourceFileAttributeNameIndex);
2779 size += 4; //writeInt(2);
2780 size += 2; //writeShort(itsSourceFileNameIndex);
2781 }else {
2782 size += 2; //out.writeShort(0); no attributes
2783 }
2784
2785 return size;
2786 }
2787
2788 /**
2789 * Get the class file as array of bytesto the OutputStream.
2790 */
2791 public byte[] toByteArray()
2792 {
2793 int dataSize = getWriteSize();
2794 byte[] data = new byte[dataSize];
2795 int offset = 0;
2796
2797 short sourceFileAttributeNameIndex = 0;
2798 if (itsSourceFileNameIndex != 0) {
2799 sourceFileAttributeNameIndex = itsConstantPool.addUtf8(
2800 "SourceFile");
2801 }
2802
2803 offset = putInt32(FileHeaderConstant, data, offset);
2804 offset = putInt16(MinorVersion, data, offset);
2805 offset = putInt16(MajorVersion, data, offset);
2806 offset = itsConstantPool.write(data, offset);
2807 offset = putInt16(itsFlags, data, offset);
2808 offset = putInt16(itsThisClassIndex, data, offset);
2809 offset = putInt16(itsSuperClassIndex, data, offset);
2810 offset = putInt16(itsInterfaces.size(), data, offset);
2811 for (int i = 0; i < itsInterfaces.size(); i++) {
2812 int interfaceIndex = ((Short)(itsInterfaces.get(i))).shortValue();
2813 offset = putInt16(interfaceIndex, data, offset);
2814 }
2815 offset = putInt16(itsFields.size(), data, offset);
2816 for (int i = 0; i < itsFields.size(); i++) {
2817 ClassFileField field = (ClassFileField)itsFields.get(i);
2818 offset = field.write(data, offset);
2819 }
2820 offset = putInt16(itsMethods.size(), data, offset);
2821 for (int i = 0; i < itsMethods.size(); i++) {
2822 ClassFileMethod method = (ClassFileMethod)itsMethods.get(i);
2823 offset = method.write(data, offset);
2824 }
2825 if (itsSourceFileNameIndex != 0) {
2826 offset = putInt16(1, data, offset); // attributes count
2827 offset = putInt16(sourceFileAttributeNameIndex, data, offset);
2828 offset = putInt32(2, data, offset);
2829 offset = putInt16(itsSourceFileNameIndex, data, offset);
2830 } else {
2831 offset = putInt16(0, data, offset); // no attributes
2832 }
2833
2834 if (offset != dataSize) {
2835 // Check getWriteSize is consistent with write!
2836 throw new RuntimeException();
2837 }
2838
2839 return data;
2840 }
2841
2842 static int putInt64(long value, byte[] array, int offset)
2843 {
2844 offset = putInt32((int)(value >>> 32), array, offset);
2845 return putInt32((int)value, array, offset);
2846 }
2847
2848 private static void badStack(int value)
2849 {
2850 String s;
2851 if (value < 0) { s = "Stack underflow: "+value; }
2852 else { s = "Too big stack: "+value; }
2853 throw new IllegalStateException(s);
2854 }
2855
2856 /*
2857 Really weird. Returns an int with # parameters in hi 16 bits, and
2858 stack difference removal of parameters from stack and pushing the
2859 result (it does not take into account removal of this in case of
2860 non-static methods).
2861 If Java really supported references we wouldn't have to be this
2862 perverted.
2863 */
2864 private static int sizeOfParameters(String pString)
2865 {
2866 int length = pString.length();
2867 int rightParenthesis = pString.lastIndexOf(')');
2868 if (3 <= length /* minimal signature takes at least 3 chars: ()V */
2869 && pString.charAt(0) == '('
2870 && 1 <= rightParenthesis && rightParenthesis + 1 < length)
2871 {
2872 boolean ok = true;
2873 int index = 1;
2874 int stackDiff = 0;
2875 int count = 0;
2876 stringLoop:
2877 while (index != rightParenthesis) {
2878 switch (pString.charAt(index)) {
2879 default:
2880 ok = false;
2881 break stringLoop;
2882 case 'J' :
2883 case 'D' :
2884 --stackDiff;
2885 // fallthru
2886 case 'B' :
2887 case 'S' :
2888 case 'C' :
2889 case 'I' :
2890 case 'Z' :
2891 case 'F' :
2892 --stackDiff;
2893 ++count;
2894 ++index;
2895 continue;
2896 case '[' :
2897 ++index;
2898 int c = pString.charAt(index);
2899 while (c == '[') {
2900 ++index;
2901 c = pString.charAt(index);
2902 }
2903 switch (c) {
2904 default:
2905 ok = false;
2906 break stringLoop;
2907 case 'J' :
2908 case 'D' :
2909 case 'B' :
2910 case 'S' :
2911 case 'C' :
2912 case 'I' :
2913 case 'Z' :
2914 case 'F' :
2915 --stackDiff;
2916 ++count;
2917 ++index;
2918 continue;
2919 case 'L':
2920 // fallthru
2921 }
2922 // fallthru
2923 case 'L' : {
2924 --stackDiff;
2925 ++count;
2926 ++index;
2927 int semicolon = pString.indexOf(';', index);
2928 if (!(index + 1 <= semicolon
2929 && semicolon < rightParenthesis))
2930 {
2931 ok = false;
2932 break stringLoop;
2933 }
2934 index = semicolon + 1;
2935 continue;
2936 }
2937 }
2938 }
2939 if (ok) {
2940 switch (pString.charAt(rightParenthesis + 1)) {
2941 default:
2942 ok = false;
2943 break;
2944 case 'J' :
2945 case 'D' :
2946 ++stackDiff;
2947 // fallthru
2948 case 'B' :
2949 case 'S' :
2950 case 'C' :
2951 case 'I' :
2952 case 'Z' :
2953 case 'F' :
2954 case 'L' :
2955 case '[' :
2956 ++stackDiff;
2957 // fallthru
2958 case 'V' :
2959 break;
2960 }
2961 if (ok) {
2962 return ((count << 16) | (0xFFFF & stackDiff));
2963 }
2964 }
2965 }
2966 throw new IllegalArgumentException(
2967 "Bad parameter signature: "+pString);
2968 }
2969
2970 static int putInt16(int value, byte[] array, int offset)
2971 {
2972 array[offset + 0] = (byte)(value >>> 8);
2973 array[offset + 1] = (byte)value;
2974 return offset + 2;
2975 }
2976
2977 static int putInt32(int value, byte[] array, int offset)
2978 {
2979 array[offset + 0] = (byte)(value >>> 24);
2980 array[offset + 1] = (byte)(value >>> 16);
2981 array[offset + 2] = (byte)(value >>> 8);
2982 array[offset + 3] = (byte)value;
2983 return offset + 4;
2984 }
2985
2986 /**
2987 * Size of a bytecode instruction, counting the opcode and its operands.
2988 *
2989 * This is different from opcodeCount, since opcodeCount counts logical
2990 * operands.
2991 */
2992 static int opcodeLength(int opcode, boolean wide) {
2993 switch (opcode) {
2994 case ByteCode.AALOAD:
2995 case ByteCode.AASTORE:
2996 case ByteCode.ACONST_NULL:
2997 case ByteCode.ALOAD_0:
2998 case ByteCode.ALOAD_1:
2999 case ByteCode.ALOAD_2:
3000 case ByteCode.ALOAD_3:
3001 case ByteCode.ARETURN:
3002 case ByteCode.ARRAYLENGTH:
3003 case ByteCode.ASTORE_0:
3004 case ByteCode.ASTORE_1:
3005 case ByteCode.ASTORE_2:
3006 case ByteCode.ASTORE_3:
3007 case ByteCode.ATHROW:
3008 case ByteCode.BALOAD:
3009 case ByteCode.BASTORE:
3010 case ByteCode.BREAKPOINT:
3011 case ByteCode.CALOAD:
3012 case ByteCode.CASTORE:
3013 case ByteCode.D2F:
3014 case ByteCode.D2I:
3015 case ByteCode.D2L:
3016 case ByteCode.DADD:
3017 case ByteCode.DALOAD:
3018 case ByteCode.DASTORE:
3019 case ByteCode.DCMPG:
3020 case ByteCode.DCMPL:
3021 case ByteCode.DCONST_0:
3022 case ByteCode.DCONST_1:
3023 case ByteCode.DDIV:
3024 case ByteCode.DLOAD_0:
3025 case ByteCode.DLOAD_1:
3026 case ByteCode.DLOAD_2:
3027 case ByteCode.DLOAD_3:
3028 case ByteCode.DMUL:
3029 case ByteCode.DNEG:
3030 case ByteCode.DREM:
3031 case ByteCode.DRETURN:
3032 case ByteCode.DSTORE_0:
3033 case ByteCode.DSTORE_1:
3034 case ByteCode.DSTORE_2:
3035 case ByteCode.DSTORE_3:
3036 case ByteCode.DSUB:
3037 case ByteCode.DUP:
3038 case ByteCode.DUP2:
3039 case ByteCode.DUP2_X1:
3040 case ByteCode.DUP2_X2:
3041 case ByteCode.DUP_X1:
3042 case ByteCode.DUP_X2:
3043 case ByteCode.F2D:
3044 case ByteCode.F2I:
3045 case ByteCode.F2L:
3046 case ByteCode.FADD:
3047 case ByteCode.FALOAD:
3048 case ByteCode.FASTORE:
3049 case ByteCode.FCMPG:
3050 case ByteCode.FCMPL:
3051 case ByteCode.FCONST_0:
3052 case ByteCode.FCONST_1:
3053 case ByteCode.FCONST_2:
3054 case ByteCode.FDIV:
3055 case ByteCode.FLOAD_0:
3056 case ByteCode.FLOAD_1:
3057 case ByteCode.FLOAD_2:
3058 case ByteCode.FLOAD_3:
3059 case ByteCode.FMUL:
3060 case ByteCode.FNEG:
3061 case ByteCode.FREM:
3062 case ByteCode.FRETURN:
3063 case ByteCode.FSTORE_0:
3064 case ByteCode.FSTORE_1:
3065 case ByteCode.FSTORE_2:
3066 case ByteCode.FSTORE_3:
3067 case ByteCode.FSUB:
3068 case ByteCode.I2B:
3069 case ByteCode.I2C:
3070 case ByteCode.I2D:
3071 case ByteCode.I2F:
3072 case ByteCode.I2L:
3073 case ByteCode.I2S:
3074 case ByteCode.IADD:
3075 case ByteCode.IALOAD:
3076 case ByteCode.IAND:
3077 case ByteCode.IASTORE:
3078 case ByteCode.ICONST_0:
3079 case ByteCode.ICONST_1:
3080 case ByteCode.ICONST_2:
3081 case ByteCode.ICONST_3:
3082 case ByteCode.ICONST_4:
3083 case ByteCode.ICONST_5:
3084 case ByteCode.ICONST_M1:
3085 case ByteCode.IDIV:
3086 case ByteCode.ILOAD_0:
3087 case ByteCode.ILOAD_1:
3088 case ByteCode.ILOAD_2:
3089 case ByteCode.ILOAD_3:
3090 case ByteCode.IMPDEP1:
3091 case ByteCode.IMPDEP2:
3092 case ByteCode.IMUL:
3093 case ByteCode.INEG:
3094 case ByteCode.IOR:
3095 case ByteCode.IREM:
3096 case ByteCode.IRETURN:
3097 case ByteCode.ISHL:
3098 case ByteCode.ISHR:
3099 case ByteCode.ISTORE_0:
3100 case ByteCode.ISTORE_1:
3101 case ByteCode.ISTORE_2:
3102 case ByteCode.ISTORE_3:
3103 case ByteCode.ISUB:
3104 case ByteCode.IUSHR:
3105 case ByteCode.IXOR:
3106 case ByteCode.L2D:
3107 case ByteCode.L2F:
3108 case ByteCode.L2I:
3109 case ByteCode.LADD:
3110 case ByteCode.LALOAD:
3111 case ByteCode.LAND:
3112 case ByteCode.LASTORE:
3113 case ByteCode.LCMP:
3114 case ByteCode.LCONST_0:
3115 case ByteCode.LCONST_1:
3116 case ByteCode.LDIV:
3117 case ByteCode.LLOAD_0:
3118 case ByteCode.LLOAD_1:
3119 case ByteCode.LLOAD_2:
3120 case ByteCode.LLOAD_3:
3121 case ByteCode.LMUL:
3122 case ByteCode.LNEG:
3123 case ByteCode.LOR:
3124 case ByteCode.LREM:
3125 case ByteCode.LRETURN:
3126 case ByteCode.LSHL:
3127 case ByteCode.LSHR:
3128 case ByteCode.LSTORE_0:
3129 case ByteCode.LSTORE_1:
3130 case ByteCode.LSTORE_2:
3131 case ByteCode.LSTORE_3:
3132 case ByteCode.LSUB:
3133 case ByteCode.LUSHR:
3134 case ByteCode.LXOR:
3135 case ByteCode.MONITORENTER:
3136 case ByteCode.MONITOREXIT:
3137 case ByteCode.NOP:
3138 case ByteCode.POP:
3139 case ByteCode.POP2:
3140 case ByteCode.RETURN:
3141 case ByteCode.SALOAD:
3142 case ByteCode.SASTORE:
3143 case ByteCode.SWAP:
3144 case ByteCode.WIDE:
3145 return 1;
3146 case ByteCode.BIPUSH:
3147 case ByteCode.LDC:
3148 case ByteCode.NEWARRAY:
3149 return 2;
3150 case ByteCode.ALOAD:
3151 case ByteCode.ASTORE:
3152 case ByteCode.DLOAD:
3153 case ByteCode.DSTORE:
3154 case ByteCode.FLOAD:
3155 case ByteCode.FSTORE:
3156 case ByteCode.ILOAD:
3157 case ByteCode.ISTORE:
3158 case ByteCode.LLOAD:
3159 case ByteCode.LSTORE:
3160 case ByteCode.RET:
3161 return wide ? 3 : 2;
3162
3163 case ByteCode.ANEWARRAY:
3164 case ByteCode.CHECKCAST:
3165 case ByteCode.GETFIELD:
3166 case ByteCode.GETSTATIC:
3167 case ByteCode.GOTO:
3168 case ByteCode.IFEQ:
3169 case ByteCode.IFGE:
3170 case ByteCode.IFGT:
3171 case ByteCode.IFLE:
3172 case ByteCode.IFLT:
3173 case ByteCode.IFNE:
3174 case ByteCode.IFNONNULL:
3175 case ByteCode.IFNULL:
3176 case ByteCode.IF_ACMPEQ:
3177 case ByteCode.IF_ACMPNE:
3178 case ByteCode.IF_ICMPEQ:
3179 case ByteCode.IF_ICMPGE:
3180 case ByteCode.IF_ICMPGT:
3181 case ByteCode.IF_ICMPLE:
3182 case ByteCode.IF_ICMPLT:
3183 case ByteCode.IF_ICMPNE:
3184 case ByteCode.INSTANCEOF:
3185 case ByteCode.INVOKESPECIAL:
3186 case ByteCode.INVOKESTATIC:
3187 case ByteCode.INVOKEVIRTUAL:
3188 case ByteCode.JSR:
3189 case ByteCode.LDC_W:
3190 case ByteCode.LDC2_W:
3191 case ByteCode.NEW:
3192 case ByteCode.PUTFIELD:
3193 case ByteCode.PUTSTATIC:
3194 case ByteCode.SIPUSH:
3195 return 3;
3196
3197 case ByteCode.IINC:
3198 return wide ? 5 : 3;
3199
3200 case ByteCode.MULTIANEWARRAY:
3201 return 4;
3202
3203 case ByteCode.GOTO_W:
3204 case ByteCode.INVOKEINTERFACE:
3205 case ByteCode.JSR_W:
3206 return 5;
3207
3208 /*
3209 case ByteCode.LOOKUPSWITCH:
3210 case ByteCode.TABLESWITCH:
3211 return -1;
3212 */
3213 }
3214 throw new IllegalArgumentException("Bad opcode: " + opcode);
3215 }
3216
3217 /**
3218 * Number of operands accompanying the opcode.
3219 */
3220 static int opcodeCount(int opcode)
3221 {
3222 switch (opcode) {
3223 case ByteCode.AALOAD:
3224 case ByteCode.AASTORE:
3225 case ByteCode.ACONST_NULL:
3226 case ByteCode.ALOAD_0:
3227 case ByteCode.ALOAD_1:
3228 case ByteCode.ALOAD_2:
3229 case ByteCode.ALOAD_3:
3230 case ByteCode.ARETURN:
3231 case ByteCode.ARRAYLENGTH:
3232 case ByteCode.ASTORE_0:
3233 case ByteCode.ASTORE_1:
3234 case ByteCode.ASTORE_2:
3235 case ByteCode.ASTORE_3:
3236 case ByteCode.ATHROW:
3237 case ByteCode.BALOAD:
3238 case ByteCode.BASTORE:
3239 case ByteCode.BREAKPOINT:
3240 case ByteCode.CALOAD:
3241 case ByteCode.CASTORE:
3242 case ByteCode.D2F:
3243 case ByteCode.D2I:
3244 case ByteCode.D2L:
3245 case ByteCode.DADD:
3246 case ByteCode.DALOAD:
3247 case ByteCode.DASTORE:
3248 case ByteCode.DCMPG:
3249 case ByteCode.DCMPL:
3250 case ByteCode.DCONST_0:
3251 case ByteCode.DCONST_1:
3252 case ByteCode.DDIV:
3253 case ByteCode.DLOAD_0:
3254 case ByteCode.DLOAD_1:
3255 case ByteCode.DLOAD_2:
3256 case ByteCode.DLOAD_3:
3257 case ByteCode.DMUL:
3258 case ByteCode.DNEG:
3259 case ByteCode.DREM:
3260 case ByteCode.DRETURN:
3261 case ByteCode.DSTORE_0:
3262 case ByteCode.DSTORE_1:
3263 case ByteCode.DSTORE_2:
3264 case ByteCode.DSTORE_3:
3265 case ByteCode.DSUB:
3266 case ByteCode.DUP:
3267 case ByteCode.DUP2:
3268 case ByteCode.DUP2_X1:
3269 case ByteCode.DUP2_X2:
3270 case ByteCode.DUP_X1:
3271 case ByteCode.DUP_X2:
3272 case ByteCode.F2D:
3273 case ByteCode.F2I:
3274 case ByteCode.F2L:
3275 case ByteCode.FADD:
3276 case ByteCode.FALOAD:
3277 case ByteCode.FASTORE:
3278 case ByteCode.FCMPG:
3279 case ByteCode.FCMPL:
3280 case ByteCode.FCONST_0:
3281 case ByteCode.FCONST_1:
3282 case ByteCode.FCONST_2:
3283 case ByteCode.FDIV:
3284 case ByteCode.FLOAD_0:
3285 case ByteCode.FLOAD_1:
3286 case ByteCode.FLOAD_2:
3287 case ByteCode.FLOAD_3:
3288 case ByteCode.FMUL:
3289 case ByteCode.FNEG:
3290 case ByteCode.FREM:
3291 case ByteCode.FRETURN:
3292 case ByteCode.FSTORE_0:
3293 case ByteCode.FSTORE_1:
3294 case ByteCode.FSTORE_2:
3295 case ByteCode.FSTORE_3:
3296 case ByteCode.FSUB:
3297 case ByteCode.I2B:
3298 case ByteCode.I2C:
3299 case ByteCode.I2D:
3300 case ByteCode.I2F:
3301 case ByteCode.I2L:
3302 case ByteCode.I2S:
3303 case ByteCode.IADD:
3304 case ByteCode.IALOAD:
3305 case ByteCode.IAND:
3306 case ByteCode.IASTORE:
3307 case ByteCode.ICONST_0:
3308 case ByteCode.ICONST_1:
3309 case ByteCode.ICONST_2:
3310 case ByteCode.ICONST_3:
3311 case ByteCode.ICONST_4:
3312 case ByteCode.ICONST_5:
3313 case ByteCode.ICONST_M1:
3314 case ByteCode.IDIV:
3315 case ByteCode.ILOAD_0:
3316 case ByteCode.ILOAD_1:
3317 case ByteCode.ILOAD_2:
3318 case ByteCode.ILOAD_3:
3319 case ByteCode.IMPDEP1:
3320 case ByteCode.IMPDEP2:
3321 case ByteCode.IMUL:
3322 case ByteCode.INEG:
3323 case ByteCode.IOR:
3324 case ByteCode.IREM:
3325 case ByteCode.IRETURN:
3326 case ByteCode.ISHL:
3327 case ByteCode.ISHR:
3328 case ByteCode.ISTORE_0:
3329 case ByteCode.ISTORE_1:
3330 case ByteCode.ISTORE_2:
3331 case ByteCode.ISTORE_3:
3332 case ByteCode.ISUB:
3333 case ByteCode.IUSHR:
3334 case ByteCode.IXOR:
3335 case ByteCode.L2D:
3336 case ByteCode.L2F:
3337 case ByteCode.L2I:
3338 case ByteCode.LADD:
3339 case ByteCode.LALOAD:
3340 case ByteCode.LAND:
3341 case ByteCode.LASTORE:
3342 case ByteCode.LCMP:
3343 case ByteCode.LCONST_0:
3344 case ByteCode.LCONST_1:
3345 case ByteCode.LDIV:
3346 case ByteCode.LLOAD_0:
3347 case ByteCode.LLOAD_1:
3348 case ByteCode.LLOAD_2:
3349 case ByteCode.LLOAD_3:
3350 case ByteCode.LMUL:
3351 case ByteCode.LNEG:
3352 case ByteCode.LOR:
3353 case ByteCode.LREM:
3354 case ByteCode.LRETURN:
3355 case ByteCode.LSHL:
3356 case ByteCode.LSHR:
3357 case ByteCode.LSTORE_0:
3358 case ByteCode.LSTORE_1:
3359 case ByteCode.LSTORE_2:
3360 case ByteCode.LSTORE_3:
3361 case ByteCode.LSUB:
3362 case ByteCode.LUSHR:
3363 case ByteCode.LXOR:
3364 case ByteCode.MONITORENTER:
3365 case ByteCode.MONITOREXIT:
3366 case ByteCode.NOP:
3367 case ByteCode.POP:
3368 case ByteCode.POP2:
3369 case ByteCode.RETURN:
3370 case ByteCode.SALOAD:
3371 case ByteCode.SASTORE:
3372 case ByteCode.SWAP:
3373 case ByteCode.WIDE:
3374 return 0;
3375 case ByteCode.ALOAD:
3376 case ByteCode.ANEWARRAY:
3377 case ByteCode.ASTORE:
3378 case ByteCode.BIPUSH:
3379 case ByteCode.CHECKCAST:
3380 case ByteCode.DLOAD:
3381 case ByteCode.DSTORE:
3382 case ByteCode.FLOAD:
3383 case ByteCode.FSTORE:
3384 case ByteCode.GETFIELD:
3385 case ByteCode.GETSTATIC:
3386 case ByteCode.GOTO:
3387 case ByteCode.GOTO_W:
3388 case ByteCode.IFEQ:
3389 case ByteCode.IFGE:
3390 case ByteCode.IFGT:
3391 case ByteCode.IFLE:
3392 case ByteCode.IFLT:
3393 case ByteCode.IFNE:
3394 case ByteCode.IFNONNULL:
3395 case ByteCode.IFNULL:
3396 case ByteCode.IF_ACMPEQ:
3397 case ByteCode.IF_ACMPNE:
3398 case ByteCode.IF_ICMPEQ:
3399 case ByteCode.IF_ICMPGE:
3400 case ByteCode.IF_ICMPGT:
3401 case ByteCode.IF_ICMPLE:
3402 case ByteCode.IF_ICMPLT:
3403 case ByteCode.IF_ICMPNE:
3404 case ByteCode.ILOAD:
3405 case ByteCode.INSTANCEOF:
3406 case ByteCode.INVOKEINTERFACE:
3407 case ByteCode.INVOKESPECIAL:
3408 case ByteCode.INVOKESTATIC:
3409 case ByteCode.INVOKEVIRTUAL:
3410 case ByteCode.ISTORE:
3411 case ByteCode.JSR:
3412 case ByteCode.JSR_W:
3413 case ByteCode.LDC:
3414 case ByteCode.LDC2_W:
3415 case ByteCode.LDC_W:
3416 case ByteCode.LLOAD:
3417 case ByteCode.LSTORE:
3418 case ByteCode.NEW:
3419 case ByteCode.NEWARRAY:
3420 case ByteCode.PUTFIELD:
3421 case ByteCode.PUTSTATIC:
3422 case ByteCode.RET:
3423 case ByteCode.SIPUSH:
3424 return 1;
3425
3426 case ByteCode.IINC:
3427 case ByteCode.MULTIANEWARRAY:
3428 return 2;
3429
3430 case ByteCode.LOOKUPSWITCH:
3431 case ByteCode.TABLESWITCH:
3432 return -1;
3433 }
3434 throw new IllegalArgumentException("Bad opcode: "+opcode);
3435 }
3436
3437 /**
3438 * The effect on the operand stack of a given opcode.
3439 */
3440 static int stackChange(int opcode)
3441 {
3442 // For INVOKE... accounts only for popping this (unless static),
3443 // ignoring parameters and return type
3444 switch (opcode) {
3445 case ByteCode.DASTORE:
3446 case ByteCode.LASTORE:
3447 return -4;
3448
3449 case ByteCode.AASTORE:
3450 case ByteCode.BASTORE:
3451 case ByteCode.CASTORE:
3452 case ByteCode.DCMPG:
3453 case ByteCode.DCMPL:
3454 case ByteCode.FASTORE:
3455 case ByteCode.IASTORE:
3456 case ByteCode.LCMP:
3457 case ByteCode.SASTORE:
3458 return -3;
3459
3460 case ByteCode.DADD:
3461 case ByteCode.DDIV:
3462 case ByteCode.DMUL:
3463 case ByteCode.DREM:
3464 case ByteCode.DRETURN:
3465 case ByteCode.DSTORE:
3466 case ByteCode.DSTORE_0:
3467 case ByteCode.DSTORE_1:
3468 case ByteCode.DSTORE_2:
3469 case ByteCode.DSTORE_3:
3470 case ByteCode.DSUB:
3471 case ByteCode.IF_ACMPEQ:
3472 case ByteCode.IF_ACMPNE:
3473 case ByteCode.IF_ICMPEQ:
3474 case ByteCode.IF_ICMPGE:
3475 case ByteCode.IF_ICMPGT:
3476 case ByteCode.IF_ICMPLE:
3477 case ByteCode.IF_ICMPLT:
3478 case ByteCode.IF_ICMPNE:
3479 case ByteCode.LADD:
3480 case ByteCode.LAND:
3481 case ByteCode.LDIV:
3482 case ByteCode.LMUL:
3483 case ByteCode.LOR:
3484 case ByteCode.LREM:
3485 case ByteCode.LRETURN:
3486 case ByteCode.LSTORE:
3487 case ByteCode.LSTORE_0:
3488 case ByteCode.LSTORE_1:
3489 case ByteCode.LSTORE_2:
3490 case ByteCode.LSTORE_3:
3491 case ByteCode.LSUB:
3492 case ByteCode.LXOR:
3493 case ByteCode.POP2:
3494 return -2;
3495
3496 case ByteCode.AALOAD:
3497 case ByteCode.ARETURN:
3498 case ByteCode.ASTORE:
3499 case ByteCode.ASTORE_0:
3500 case ByteCode.ASTORE_1:
3501 case ByteCode.ASTORE_2:
3502 case ByteCode.ASTORE_3:
3503 case ByteCode.ATHROW:
3504 case ByteCode.BALOAD:
3505 case ByteCode.CALOAD:
3506 case ByteCode.D2F:
3507 case ByteCode.D2I:
3508 case ByteCode.FADD:
3509 case ByteCode.FALOAD:
3510 case ByteCode.FCMPG:
3511 case ByteCode.FCMPL:
3512 case ByteCode.FDIV:
3513 case ByteCode.FMUL:
3514 case ByteCode.FREM:
3515 case ByteCode.FRETURN:
3516 case ByteCode.FSTORE:
3517 case ByteCode.FSTORE_0:
3518 case ByteCode.FSTORE_1:
3519 case ByteCode.FSTORE_2:
3520 case ByteCode.FSTORE_3:
3521 case ByteCode.FSUB:
3522 case ByteCode.GETFIELD:
3523 case ByteCode.IADD:
3524 case ByteCode.IALOAD:
3525 case ByteCode.IAND:
3526 case ByteCode.IDIV:
3527 case ByteCode.IFEQ:
3528 case ByteCode.IFGE:
3529 case ByteCode.IFGT:
3530 case ByteCode.IFLE:
3531 case ByteCode.IFLT:
3532 case ByteCode.IFNE:
3533 case ByteCode.IFNONNULL:
3534 case ByteCode.IFNULL:
3535 case ByteCode.IMUL:
3536 case ByteCode.INVOKEINTERFACE: //
3537 case ByteCode.INVOKESPECIAL: // but needs to account for
3538 case ByteCode.INVOKEVIRTUAL: // pops 'this' (unless static)
3539 case ByteCode.IOR:
3540 case ByteCode.IREM:
3541 case ByteCode.IRETURN:
3542 case ByteCode.ISHL:
3543 case ByteCode.ISHR:
3544 case ByteCode.ISTORE:
3545 case ByteCode.ISTORE_0:
3546 case ByteCode.ISTORE_1:
3547 case ByteCode.ISTORE_2:
3548 case ByteCode.ISTORE_3:
3549 case ByteCode.ISUB:
3550 case ByteCode.IUSHR:
3551 case ByteCode.IXOR:
3552 case ByteCode.L2F:
3553 case ByteCode.L2I:
3554 case ByteCode.LOOKUPSWITCH:
3555 case ByteCode.LSHL:
3556 case ByteCode.LSHR:
3557 case ByteCode.LUSHR:
3558 case ByteCode.MONITORENTER:
3559 case ByteCode.MONITOREXIT:
3560 case ByteCode.POP:
3561 case ByteCode.PUTFIELD:
3562 case ByteCode.SALOAD:
3563 case ByteCode.TABLESWITCH:
3564 return -1;
3565
3566 case ByteCode.ANEWARRAY:
3567 case ByteCode.ARRAYLENGTH:
3568 case ByteCode.BREAKPOINT:
3569 case ByteCode.CHECKCAST:
3570 case ByteCode.D2L:
3571 case ByteCode.DALOAD:
3572 case ByteCode.DNEG:
3573 case ByteCode.F2I:
3574 case ByteCode.FNEG:
3575 case ByteCode.GETSTATIC:
3576 case ByteCode.GOTO:
3577 case ByteCode.GOTO_W:
3578 case ByteCode.I2B:
3579 case ByteCode.I2C:
3580 case ByteCode.I2F:
3581 case ByteCode.I2S:
3582 case ByteCode.IINC:
3583 case ByteCode.IMPDEP1:
3584 case ByteCode.IMPDEP2:
3585 case ByteCode.INEG:
3586 case ByteCode.INSTANCEOF:
3587 case ByteCode.INVOKESTATIC:
3588 case ByteCode.L2D:
3589 case ByteCode.LALOAD:
3590 case ByteCode.LNEG:
3591 case ByteCode.NEWARRAY:
3592 case ByteCode.NOP:
3593 case ByteCode.PUTSTATIC:
3594 case ByteCode.RET:
3595 case ByteCode.RETURN:
3596 case ByteCode.SWAP:
3597 case ByteCode.WIDE:
3598 return 0;
3599
3600 case ByteCode.ACONST_NULL:
3601 case ByteCode.ALOAD:
3602 case ByteCode.ALOAD_0:
3603 case ByteCode.ALOAD_1:
3604 case ByteCode.ALOAD_2:
3605 case ByteCode.ALOAD_3:
3606 case ByteCode.BIPUSH:
3607 case ByteCode.DUP:
3608 case ByteCode.DUP_X1:
3609 case ByteCode.DUP_X2:
3610 case ByteCode.F2D:
3611 case ByteCode.F2L:
3612 case ByteCode.FCONST_0:
3613 case ByteCode.FCONST_1:
3614 case ByteCode.FCONST_2:
3615 case ByteCode.FLOAD:
3616 case ByteCode.FLOAD_0:
3617 case ByteCode.FLOAD_1:
3618 case ByteCode.FLOAD_2:
3619 case ByteCode.FLOAD_3:
3620 case ByteCode.I2D:
3621 case ByteCode.I2L:
3622 case ByteCode.ICONST_0:
3623 case ByteCode.ICONST_1:
3624 case ByteCode.ICONST_2:
3625 case ByteCode.ICONST_3:
3626 case ByteCode.ICONST_4:
3627 case ByteCode.ICONST_5:
3628 case ByteCode.ICONST_M1:
3629 case ByteCode.ILOAD:
3630 case ByteCode.ILOAD_0:
3631 case ByteCode.ILOAD_1:
3632 case ByteCode.ILOAD_2:
3633 case ByteCode.ILOAD_3:
3634 case ByteCode.JSR:
3635 case ByteCode.JSR_W:
3636 case ByteCode.LDC:
3637 case ByteCode.LDC_W:
3638 case ByteCode.MULTIANEWARRAY:
3639 case ByteCode.NEW:
3640 case ByteCode.SIPUSH:
3641 return 1;
3642
3643 case ByteCode.DCONST_0:
3644 case ByteCode.DCONST_1:
3645 case ByteCode.DLOAD:
3646 case ByteCode.DLOAD_0:
3647 case ByteCode.DLOAD_1:
3648 case ByteCode.DLOAD_2:
3649 case ByteCode.DLOAD_3:
3650 case ByteCode.DUP2:
3651 case ByteCode.DUP2_X1:
3652 case ByteCode.DUP2_X2:
3653 case ByteCode.LCONST_0:
3654 case ByteCode.LCONST_1:
3655 case ByteCode.LDC2_W:
3656 case ByteCode.LLOAD:
3657 case ByteCode.LLOAD_0:
3658 case ByteCode.LLOAD_1:
3659 case ByteCode.LLOAD_2:
3660 case ByteCode.LLOAD_3:
3661 return 2;
3662 }
3663 throw new IllegalArgumentException("Bad opcode: "+opcode);
3664 }
3665
3666 /*
3667 * Number of bytes of operands generated after the opcode.
3668 * Not in use currently.
3669 */
3670 /*
3671 int extra(int opcode)
3672 {
3673 switch (opcode) {
3674 case ByteCode.AALOAD:
3675 case ByteCode.AASTORE:
3676 case ByteCode.ACONST_NULL:
3677 case ByteCode.ALOAD_0:
3678 case ByteCode.ALOAD_1:
3679 case ByteCode.ALOAD_2:
3680 case ByteCode.ALOAD_3:
3681 case ByteCode.ARETURN:
3682 case ByteCode.ARRAYLENGTH:
3683 case ByteCode.ASTORE_0:
3684 case ByteCode.ASTORE_1:
3685 case ByteCode.ASTORE_2:
3686 case ByteCode.ASTORE_3:
3687 case ByteCode.ATHROW:
3688 case ByteCode.BALOAD:
3689 case ByteCode.BASTORE:
3690 case ByteCode.BREAKPOINT:
3691 case ByteCode.CALOAD:
3692 case ByteCode.CASTORE:
3693 case ByteCode.D2F:
3694 case ByteCode.D2I:
3695 case ByteCode.D2L:
3696 case ByteCode.DADD:
3697 case ByteCode.DALOAD:
3698 case ByteCode.DASTORE:
3699 case ByteCode.DCMPG:
3700 case ByteCode.DCMPL:
3701 case ByteCode.DCONST_0:
3702 case ByteCode.DCONST_1:
3703 case ByteCode.DDIV:
3704 case ByteCode.DLOAD_0:
3705 case ByteCode.DLOAD_1:
3706 case ByteCode.DLOAD_2:
3707 case ByteCode.DLOAD_3:
3708 case ByteCode.DMUL:
3709 case ByteCode.DNEG:
3710 case ByteCode.DREM:
3711 case ByteCode.DRETURN:
3712 case ByteCode.DSTORE_0:
3713 case ByteCode.DSTORE_1:
3714 case ByteCode.DSTORE_2:
3715 case ByteCode.DSTORE_3:
3716 case ByteCode.DSUB:
3717 case ByteCode.DUP2:
3718 case ByteCode.DUP2_X1:
3719 case ByteCode.DUP2_X2:
3720 case ByteCode.DUP:
3721 case ByteCode.DUP_X1:
3722 case ByteCode.DUP_X2:
3723 case ByteCode.F2D:
3724 case ByteCode.F2I:
3725 case ByteCode.F2L:
3726 case ByteCode.FADD:
3727 case ByteCode.FALOAD:
3728 case ByteCode.FASTORE:
3729 case ByteCode.FCMPG:
3730 case ByteCode.FCMPL:
3731 case ByteCode.FCONST_0:
3732 case ByteCode.FCONST_1:
3733 case ByteCode.FCONST_2:
3734 case ByteCode.FDIV:
3735 case ByteCode.FLOAD_0:
3736 case ByteCode.FLOAD_1:
3737 case ByteCode.FLOAD_2:
3738 case ByteCode.FLOAD_3:
3739 case ByteCode.FMUL:
3740 case ByteCode.FNEG:
3741 case ByteCode.FREM:
3742 case ByteCode.FRETURN:
3743 case ByteCode.FSTORE_0:
3744 case ByteCode.FSTORE_1:
3745 case ByteCode.FSTORE_2:
3746 case ByteCode.FSTORE_3:
3747 case ByteCode.FSUB:
3748 case ByteCode.I2B:
3749 case ByteCode.I2C:
3750 case ByteCode.I2D:
3751 case ByteCode.I2F:
3752 case ByteCode.I2L:
3753 case ByteCode.I2S:
3754 case ByteCode.IADD:
3755 case ByteCode.IALOAD:
3756 case ByteCode.IAND:
3757 case ByteCode.IASTORE:
3758 case ByteCode.ICONST_0:
3759 case ByteCode.ICONST_1:
3760 case ByteCode.ICONST_2:
3761 case ByteCode.ICONST_3:
3762 case ByteCode.ICONST_4:
3763 case ByteCode.ICONST_5:
3764 case ByteCode.ICONST_M1:
3765 case ByteCode.IDIV:
3766 case ByteCode.ILOAD_0:
3767 case ByteCode.ILOAD_1:
3768 case ByteCode.ILOAD_2:
3769 case ByteCode.ILOAD_3:
3770 case ByteCode.IMPDEP1:
3771 case ByteCode.IMPDEP2:
3772 case ByteCode.IMUL:
3773 case ByteCode.INEG:
3774 case ByteCode.IOR:
3775 case ByteCode.IREM:
3776 case ByteCode.IRETURN:
3777 case ByteCode.ISHL:
3778 case ByteCode.ISHR:
3779 case ByteCode.ISTORE_0:
3780 case ByteCode.ISTORE_1:
3781 case ByteCode.ISTORE_2:
3782 case ByteCode.ISTORE_3:
3783 case ByteCode.ISUB:
3784 case ByteCode.IUSHR:
3785 case ByteCode.IXOR:
3786 case ByteCode.L2D:
3787 case ByteCode.L2F:
3788 case ByteCode.L2I:
3789 case ByteCode.LADD:
3790 case ByteCode.LALOAD:
3791 case ByteCode.LAND:
3792 case ByteCode.LASTORE:
3793 case ByteCode.LCMP:
3794 case ByteCode.LCONST_0:
3795 case ByteCode.LCONST_1:
3796 case ByteCode.LDIV:
3797 case ByteCode.LLOAD_0:
3798 case ByteCode.LLOAD_1:
3799 case ByteCode.LLOAD_2:
3800 case ByteCode.LLOAD_3:
3801 case ByteCode.LMUL:
3802 case ByteCode.LNEG:
3803 case ByteCode.LOR:
3804 case ByteCode.LREM:
3805 case ByteCode.LRETURN:
3806 case ByteCode.LSHL:
3807 case ByteCode.LSHR:
3808 case ByteCode.LSTORE_0:
3809 case ByteCode.LSTORE_1:
3810 case ByteCode.LSTORE_2:
3811 case ByteCode.LSTORE_3:
3812 case ByteCode.LSUB:
3813 case ByteCode.LUSHR:
3814 case ByteCode.LXOR:
3815 case ByteCode.MONITORENTER:
3816 case ByteCode.MONITOREXIT:
3817 case ByteCode.NOP:
3818 case ByteCode.POP2:
3819 case ByteCode.POP:
3820 case ByteCode.RETURN:
3821 case ByteCode.SALOAD:
3822 case ByteCode.SASTORE:
3823 case ByteCode.SWAP:
3824 case ByteCode.WIDE:
3825 return 0;
3826
3827 case ByteCode.ALOAD:
3828 case ByteCode.ASTORE:
3829 case ByteCode.BIPUSH:
3830 case ByteCode.DLOAD:
3831 case ByteCode.DSTORE:
3832 case ByteCode.FLOAD:
3833 case ByteCode.FSTORE:
3834 case ByteCode.ILOAD:
3835 case ByteCode.ISTORE:
3836 case ByteCode.LDC:
3837 case ByteCode.LLOAD:
3838 case ByteCode.LSTORE:
3839 case ByteCode.NEWARRAY:
3840 case ByteCode.RET:
3841 return 1;
3842
3843 case ByteCode.ANEWARRAY:
3844 case ByteCode.CHECKCAST:
3845 case ByteCode.GETFIELD:
3846 case ByteCode.GETSTATIC:
3847 case ByteCode.GOTO:
3848 case ByteCode.IFEQ:
3849 case ByteCode.IFGE:
3850 case ByteCode.IFGT:
3851 case ByteCode.IFLE:
3852 case ByteCode.IFLT:
3853 case ByteCode.IFNE:
3854 case ByteCode.IFNONNULL:
3855 case ByteCode.IFNULL:
3856 case ByteCode.IF_ACMPEQ:
3857 case ByteCode.IF_ACMPNE:
3858 case ByteCode.IF_ICMPEQ:
3859 case ByteCode.IF_ICMPGE:
3860 case ByteCode.IF_ICMPGT:
3861 case ByteCode.IF_ICMPLE:
3862 case ByteCode.IF_ICMPLT:
3863 case ByteCode.IF_ICMPNE:
3864 case ByteCode.IINC:
3865 case ByteCode.INSTANCEOF:
3866 case ByteCode.INVOKEINTERFACE:
3867 case ByteCode.INVOKESPECIAL:
3868 case ByteCode.INVOKESTATIC:
3869 case ByteCode.INVOKEVIRTUAL:
3870 case ByteCode.JSR:
3871 case ByteCode.LDC2_W:
3872 case ByteCode.LDC_W:
3873 case ByteCode.NEW:
3874 case ByteCode.PUTFIELD:
3875 case ByteCode.PUTSTATIC:
3876 case ByteCode.SIPUSH:
3877 return 2;
3878
3879 case ByteCode.MULTIANEWARRAY:
3880 return 3;
3881
3882 case ByteCode.GOTO_W:
3883 case ByteCode.JSR_W:
3884 return 4;
3885
3886 case ByteCode.LOOKUPSWITCH: // depends on alignment
3887 case ByteCode.TABLESWITCH: // depends on alignment
3888 return -1;
3889 }
3890 throw new IllegalArgumentException("Bad opcode: "+opcode);
3891 }
3892 */
3893
3894 @SuppressWarnings("unused")
3895 private static String bytecodeStr(int code)
3896 {
3897 if (DEBUGSTACK || DEBUGCODE) {
3898 switch (code) {
3899 case ByteCode.NOP: return "nop";
3900 case ByteCode.ACONST_NULL: return "aconst_null";
3901 case ByteCode.ICONST_M1: return "iconst_m1";
3902 case ByteCode.ICONST_0: return "iconst_0";
3903 case ByteCode.ICONST_1: return "iconst_1";
3904 case ByteCode.ICONST_2: return "iconst_2";
3905 case ByteCode.ICONST_3: return "iconst_3";
3906 case ByteCode.ICONST_4: return "iconst_4";
3907 case ByteCode.ICONST_5: return "iconst_5";
3908 case ByteCode.LCONST_0: return "lconst_0";
3909 case ByteCode.LCONST_1: return "lconst_1";
3910 case ByteCode.FCONST_0: return "fconst_0";
3911 case ByteCode.FCONST_1: return "fconst_1";
3912 case ByteCode.FCONST_2: return "fconst_2";
3913 case ByteCode.DCONST_0: return "dconst_0";
3914 case ByteCode.DCONST_1: return "dconst_1";
3915 case ByteCode.BIPUSH: return "bipush";
3916 case ByteCode.SIPUSH: return "sipush";
3917 case ByteCode.LDC: return "ldc";
3918 case ByteCode.LDC_W: return "ldc_w";
3919 case ByteCode.LDC2_W: return "ldc2_w";
3920 case ByteCode.ILOAD: return "iload";
3921 case ByteCode.LLOAD: return "lload";
3922 case ByteCode.FLOAD: return "fload";
3923 case ByteCode.DLOAD: return "dload";
3924 case ByteCode.ALOAD: return "aload";
3925 case ByteCode.ILOAD_0: return "iload_0";
3926 case ByteCode.ILOAD_1: return "iload_1";
3927 case ByteCode.ILOAD_2: return "iload_2";
3928 case ByteCode.ILOAD_3: return "iload_3";
3929 case ByteCode.LLOAD_0: return "lload_0";
3930 case ByteCode.LLOAD_1: return "lload_1";
3931 case ByteCode.LLOAD_2: return "lload_2";
3932 case ByteCode.LLOAD_3: return "lload_3";
3933 case ByteCode.FLOAD_0: return "fload_0";
3934 case ByteCode.FLOAD_1: return "fload_1";
3935 case ByteCode.FLOAD_2: return "fload_2";
3936 case ByteCode.FLOAD_3: return "fload_3";
3937 case ByteCode.DLOAD_0: return "dload_0";
3938 case ByteCode.DLOAD_1: return "dload_1";
3939 case ByteCode.DLOAD_2: return "dload_2";
3940 case ByteCode.DLOAD_3: return "dload_3";
3941 case ByteCode.ALOAD_0: return "aload_0";
3942 case ByteCode.ALOAD_1: return "aload_1";
3943 case ByteCode.ALOAD_2: return "aload_2";
3944 case ByteCode.ALOAD_3: return "aload_3";
3945 case ByteCode.IALOAD: return "iaload";
3946 case ByteCode.LALOAD: return "laload";
3947 case ByteCode.FALOAD: return "faload";
3948 case ByteCode.DALOAD: return "daload";
3949 case ByteCode.AALOAD: return "aaload";
3950 case ByteCode.BALOAD: return "baload";
3951 case ByteCode.CALOAD: return "caload";
3952 case ByteCode.SALOAD: return "saload";
3953 case ByteCode.ISTORE: return "istore";
3954 case ByteCode.LSTORE: return "lstore";
3955 case ByteCode.FSTORE: return "fstore";
3956 case ByteCode.DSTORE: return "dstore";
3957 case ByteCode.ASTORE: return "astore";
3958 case ByteCode.ISTORE_0: return "istore_0";
3959 case ByteCode.ISTORE_1: return "istore_1";
3960 case ByteCode.ISTORE_2: return "istore_2";
3961 case ByteCode.ISTORE_3: return "istore_3";
3962 case ByteCode.LSTORE_0: return "lstore_0";
3963 case ByteCode.LSTORE_1: return "lstore_1";
3964 case ByteCode.LSTORE_2: return "lstore_2";
3965 case ByteCode.LSTORE_3: return "lstore_3";
3966 case ByteCode.FSTORE_0: return "fstore_0";
3967 case ByteCode.FSTORE_1: return "fstore_1";
3968 case ByteCode.FSTORE_2: return "fstore_2";
3969 case ByteCode.FSTORE_3: return "fstore_3";
3970 case ByteCode.DSTORE_0: return "dstore_0";
3971 case ByteCode.DSTORE_1: return "dstore_1";
3972 case ByteCode.DSTORE_2: return "dstore_2";
3973 case ByteCode.DSTORE_3: return "dstore_3";
3974 case ByteCode.ASTORE_0: return "astore_0";
3975 case ByteCode.ASTORE_1: return "astore_1";
3976 case ByteCode.ASTORE_2: return "astore_2";
3977 case ByteCode.ASTORE_3: return "astore_3";
3978 case ByteCode.IASTORE: return "iastore";
3979 case ByteCode.LASTORE: return "lastore";
3980 case ByteCode.FASTORE: return "fastore";
3981 case ByteCode.DASTORE: return "dastore";
3982 case ByteCode.AASTORE: return "aastore";
3983 case ByteCode.BASTORE: return "bastore";
3984 case ByteCode.CASTORE: return "castore";
3985 case ByteCode.SASTORE: return "sastore";
3986 case ByteCode.POP: return "pop";
3987 case ByteCode.POP2: return "pop2";
3988 case ByteCode.DUP: return "dup";
3989 case ByteCode.DUP_X1: return "dup_x1";
3990 case ByteCode.DUP_X2: return "dup_x2";
3991 case ByteCode.DUP2: return "dup2";
3992 case ByteCode.DUP2_X1: return "dup2_x1";
3993 case ByteCode.DUP2_X2: return "dup2_x2";
3994 case ByteCode.SWAP: return "swap";
3995 case ByteCode.IADD: return "iadd";
3996 case ByteCode.LADD: return "ladd";
3997 case ByteCode.FADD: return "fadd";
3998 case ByteCode.DADD: return "dadd";
3999 case ByteCode.ISUB: return "isub";
4000 case ByteCode.LSUB: return "lsub";
4001 case ByteCode.FSUB: return "fsub";
4002 case ByteCode.DSUB: return "dsub";
4003 case ByteCode.IMUL: return "imul";
4004 case ByteCode.LMUL: return "lmul";
4005 case ByteCode.FMUL: return "fmul";
4006 case ByteCode.DMUL: return "dmul";
4007 case ByteCode.IDIV: return "idiv";
4008 case ByteCode.LDIV: return "ldiv";
4009 case ByteCode.FDIV: return "fdiv";
4010 case ByteCode.DDIV: return "ddiv";
4011 case ByteCode.IREM: return "irem";
4012 case ByteCode.LREM: return "lrem";
4013 case ByteCode.FREM: return "frem";
4014 case ByteCode.DREM: return "drem";
4015 case ByteCode.INEG: return "ineg";
4016 case ByteCode.LNEG: return "lneg";
4017 case ByteCode.FNEG: return "fneg";
4018 case ByteCode.DNEG: return "dneg";
4019 case ByteCode.ISHL: return "ishl";
4020 case ByteCode.LSHL: return "lshl";
4021 case ByteCode.ISHR: return "ishr";
4022 case ByteCode.LSHR: return "lshr";
4023 case ByteCode.IUSHR: return "iushr";
4024 case ByteCode.LUSHR: return "lushr";
4025 case ByteCode.IAND: return "iand";
4026 case ByteCode.LAND: return "land";
4027 case ByteCode.IOR: return "ior";
4028 case ByteCode.LOR: return "lor";
4029 case ByteCode.IXOR: return "ixor";
4030 case ByteCode.LXOR: return "lxor";
4031 case ByteCode.IINC: return "iinc";
4032 case ByteCode.I2L: return "i2l";
4033 case ByteCode.I2F: return "i2f";
4034 case ByteCode.I2D: return "i2d";
4035 case ByteCode.L2I: return "l2i";
4036 case ByteCode.L2F: return "l2f";
4037 case ByteCode.L2D: return "l2d";
4038 case ByteCode.F2I: return "f2i";
4039 case ByteCode.F2L: return "f2l";
4040 case ByteCode.F2D: return "f2d";
4041 case ByteCode.D2I: return "d2i";
4042 case ByteCode.D2L: return "d2l";
4043 case ByteCode.D2F: return "d2f";
4044 case ByteCode.I2B: return "i2b";
4045 case ByteCode.I2C: return "i2c";
4046 case ByteCode.I2S: return "i2s";
4047 case ByteCode.LCMP: return "lcmp";
4048 case ByteCode.FCMPL: return "fcmpl";
4049 case ByteCode.FCMPG: return "fcmpg";
4050 case ByteCode.DCMPL: return "dcmpl";
4051 case ByteCode.DCMPG: return "dcmpg";
4052 case ByteCode.IFEQ: return "ifeq";
4053 case ByteCode.IFNE: return "ifne";
4054 case ByteCode.IFLT: return "iflt";
4055 case ByteCode.IFGE: return "ifge";
4056 case ByteCode.IFGT: return "ifgt";
4057 case ByteCode.IFLE: return "ifle";
4058 case ByteCode.IF_ICMPEQ: return "if_icmpeq";
4059 case ByteCode.IF_ICMPNE: return "if_icmpne";
4060 case ByteCode.IF_ICMPLT: return "if_icmplt";
4061 case ByteCode.IF_ICMPGE: return "if_icmpge";
4062 case ByteCode.IF_ICMPGT: return "if_icmpgt";
4063 case ByteCode.IF_ICMPLE: return "if_icmple";
4064 case ByteCode.IF_ACMPEQ: return "if_acmpeq";
4065 case ByteCode.IF_ACMPNE: return "if_acmpne";
4066 case ByteCode.GOTO: return "goto";
4067 case ByteCode.JSR: return "jsr";
4068 case ByteCode.RET: return "ret";
4069 case ByteCode.TABLESWITCH: return "tableswitch";
4070 case ByteCode.LOOKUPSWITCH: return "lookupswitch";
4071 case ByteCode.IRETURN: return "ireturn";
4072 case ByteCode.LRETURN: return "lreturn";
4073 case ByteCode.FRETURN: return "freturn";
4074 case ByteCode.DRETURN: return "dreturn";
4075 case ByteCode.ARETURN: return "areturn";
4076 case ByteCode.RETURN: return "return";
4077 case ByteCode.GETSTATIC: return "getstatic";
4078 case ByteCode.PUTSTATIC: return "putstatic";
4079 case ByteCode.GETFIELD: return "getfield";
4080 case ByteCode.PUTFIELD: return "putfield";
4081 case ByteCode.INVOKEVIRTUAL: return "invokevirtual";
4082 case ByteCode.INVOKESPECIAL: return "invokespecial";
4083 case ByteCode.INVOKESTATIC: return "invokestatic";
4084 case ByteCode.INVOKEINTERFACE: return "invokeinterface";
4085 case ByteCode.NEW: return "new";
4086 case ByteCode.NEWARRAY: return "newarray";
4087 case ByteCode.ANEWARRAY: return "anewarray";
4088 case ByteCode.ARRAYLENGTH: return "arraylength";
4089 case ByteCode.ATHROW: return "athrow";
4090 case ByteCode.CHECKCAST: return "checkcast";
4091 case ByteCode.INSTANCEOF: return "instanceof";
4092 case ByteCode.MONITORENTER: return "monitorenter";
4093 case ByteCode.MONITOREXIT: return "monitorexit";
4094 case ByteCode.WIDE: return "wide";
4095 case ByteCode.MULTIANEWARRAY: return "multianewarray";
4096 case ByteCode.IFNULL: return "ifnull";
4097 case ByteCode.IFNONNULL: return "ifnonnull";
4098 case ByteCode.GOTO_W: return "goto_w";
4099 case ByteCode.JSR_W: return "jsr_w";
4100 case ByteCode.BREAKPOINT: return "breakpoint";
4101
4102 case ByteCode.IMPDEP1: return "impdep1";
4103 case ByteCode.IMPDEP2: return "impdep2";
4104 }
4105 }
4106 return "";
4107 }
4108
4109 final char[] getCharBuffer(int minimalSize)
4110 {
4111 if (minimalSize > tmpCharBuffer.length) {
4112 int newSize = tmpCharBuffer.length * 2;
4113 if (minimalSize > newSize) { newSize = minimalSize; }
4114 tmpCharBuffer = new char[newSize];
4115 }
4116 return tmpCharBuffer;
4117 }
4118
4119 /**
4120 * Add a pc as the start of super block.
4121 *
4122 * A pc is the beginning of a super block if:
4123 * - pc == 0
4124 * - it is the target of a branch instruction
4125 * - it is the beginning of an exception handler
4126 * - it is directly after an unconditional jump
4127 */
4128 private void addSuperBlockStart(int pc) {
4129 if (GenerateStackMap) {
4130 if (itsSuperBlockStarts == null) {
4131 itsSuperBlockStarts = new int[SuperBlockStartsSize];
4132 } else if (itsSuperBlockStarts.length == itsSuperBlockStartsTop) {
4133 int[] tmp = new int[itsSuperBlockStartsTop * 2];
4134 System.arraycopy(itsSuperBlockStarts, 0, tmp, 0,
4135 itsSuperBlockStartsTop);
4136 itsSuperBlockStarts = tmp;
4137 }
4138 itsSuperBlockStarts[itsSuperBlockStartsTop++] = pc;
4139 }
4140 }
4141
4142 /**
4143 * Sort the list of recorded super block starts and remove duplicates.
4144 *
4145 * Also adds exception handling blocks as block starts, since there is no
4146 * explicit control flow to these. Used for stack map table generation.
4147 */
4148 private void finalizeSuperBlockStarts() {
4149 if (GenerateStackMap) {
4150 for (int i = 0; i < itsExceptionTableTop; i++) {
4151 ExceptionTableEntry ete = itsExceptionTable[i];
4152 short handlerPC = (short) getLabelPC(ete.itsHandlerLabel);
4153 addSuperBlockStart(handlerPC);
4154 }
4155 Arrays.sort(itsSuperBlockStarts, 0, itsSuperBlockStartsTop);
4156 int prev = itsSuperBlockStarts[0];
4157 int copyTo = 1;
4158 for (int i = 1; i < itsSuperBlockStartsTop; i++) {
4159 int curr = itsSuperBlockStarts[i];
4160 if (prev != curr) {
4161 if (copyTo != i) {
4162 itsSuperBlockStarts[copyTo] = curr;
4163 }
4164 copyTo++;
4165 prev = curr;
4166 }
4167 }
4168 itsSuperBlockStartsTop = copyTo;
4169 if (itsSuperBlockStarts[copyTo - 1] == itsCodeBufferTop) {
4170 itsSuperBlockStartsTop--;
4171 }
4172 }
4173 }
4174
4175 private int[] itsSuperBlockStarts = null;
4176 private int itsSuperBlockStartsTop = 0;
4177 private static final int SuperBlockStartsSize = 4;
4178
4179 // Used to find blocks of code with no dependencies (aka dead code).
4180 // Necessary for generating type information for dead code, which is
4181 // expected by the Sun verifier. It is only necessary to store a single
4182 // jump source to determine if a block is reachable or not.
4183 private UintMap itsJumpFroms = null;
4184
4185 private static final int LineNumberTableSize = 16;
4186 private static final int ExceptionTableSize = 4;
4187
4188 private static final int MajorVersion;
4189 private static final int MinorVersion;
4190 private static final boolean GenerateStackMap;
4191
4192 static {
4193 // Figure out which classfile version should be generated. This assumes
4194 // that the runtime used to compile the JavaScript files is the same as
4195 // the one used to run them. This is important because there are cases
4196 // when bytecode is generated at runtime, where it is not easy to pass
4197 // along what version is necessary. Instead, we grab the version numbers
4198 // from the bytecode of this class and use that.
4199 //
4200 // Based on the version numbers we scrape, we can also determine what
4201 // bytecode features we need. For example, Java 6 bytecode (classfile
4202 // version 50) should have stack maps generated.
4203 InputStream is = null;
4204 int major = 48, minor = 0;
4205 try {
4206 is = ClassFileWriter.class.getResourceAsStream("ClassFileWriter.class");
4207 if (is == null) {
4208 is = ClassLoader.getSystemResourceAsStream(
4209 "org/mozilla/classfile/ClassFileWriter.class");
4210 }
4211 byte[] header = new byte[8];
4212 // read loop is required since JDK7 will only provide 2 bytes
4213 // on the first read() - see bug #630111
4214 int read = 0;
4215 while (read < 8) {
4216 int c = is.read(header, read, 8 - read);
4217 if (c < 0) throw new IOException();
4218 read += c;
4219 }
4220 minor = (header[4] << 8) | (header[5] & 0xff);
4221 major = (header[6] << 8) | (header[7] & 0xff);
4222 } catch (Exception e) {
4223 // Unable to get class file, use default bytecode version
4224 } finally {
4225 MinorVersion = minor;
4226 MajorVersion = major;
4227 GenerateStackMap = major >= 50;
4228 if (is != null) {
4229 try {
4230 is.close();
4231 } catch (IOException e) {
4232 }
4233 }
4234 }
4235 }
4236
4237 private final static int FileHeaderConstant = 0xCAFEBABE;
4238 // Set DEBUG flags to true to get better checking and progress info.
4239 private static final boolean DEBUGSTACK = false;
4240 private static final boolean DEBUGLABELS = false;
4241 private static final boolean DEBUGCODE = false;
4242
4243 private String generatedClassName;
4244
4245 private ExceptionTableEntry itsExceptionTable[];
4246 private int itsExceptionTableTop;
4247
4248 private int itsLineNumberTable[]; // pack start_pc & line_number together
4249 private int itsLineNumberTableTop;
4250
4251 private byte[] itsCodeBuffer = new byte[256];
4252 private int itsCodeBufferTop;
4253
4254 private ConstantPool itsConstantPool;
4255
4256 private ClassFileMethod itsCurrentMethod;
4257 private short itsStackTop;
4258
4259 private short itsMaxStack;
4260 private short itsMaxLocals;
4261
4262 private ObjArray itsMethods = new ObjArray();
4263 private ObjArray itsFields = new ObjArray();
4264 private ObjArray itsInterfaces = new ObjArray();
4265
4266 private short itsFlags;
4267 private short itsThisClassIndex;
4268 private short itsSuperClassIndex;
4269 private short itsSourceFileNameIndex;
4270
4271 private static final int MIN_LABEL_TABLE_SIZE = 32;
4272 private int[] itsLabelTable;
4273 private int itsLabelTableTop;
4274
4275 // itsFixupTable[i] = (label_index << 32) | fixup_site
4276 private static final int MIN_FIXUP_TABLE_SIZE = 40;
4277 private long[] itsFixupTable;
4278 private int itsFixupTableTop;
4279 private ObjArray itsVarDescriptors;
4280
4281 private char[] tmpCharBuffer = new char[64];
4282 }
4283
4284 final class ExceptionTableEntry
4285 {
4286
4287 ExceptionTableEntry(int startLabel, int endLabel,
4288 int handlerLabel, short catchType)
4289 {
4290 itsStartLabel = startLabel;
4291 itsEndLabel = endLabel;
4292 itsHandlerLabel = handlerLabel;
4293 itsCatchType = catchType;
4294 }
4295
4296 int itsStartLabel;
4297 int itsEndLabel;
4298 int itsHandlerLabel;
4299 short itsCatchType;
4300 }
4301
4302 final class ClassFileField
4303 {
4304
4305 ClassFileField(short nameIndex, short typeIndex, short flags)
4306 {
4307 itsNameIndex = nameIndex;
4308 itsTypeIndex = typeIndex;
4309 itsFlags = flags;
4310 itsHasAttributes = false;
4311 }
4312
4313 void setAttributes(short attr1, short attr2, short attr3, int index)
4314 {
4315 itsHasAttributes = true;
4316 itsAttr1 = attr1;
4317 itsAttr2 = attr2;
4318 itsAttr3 = attr3;
4319 itsIndex = index;
4320 }
4321
4322 int write(byte[] data, int offset)
4323 {
4324 offset = ClassFileWriter.putInt16(itsFlags, data, offset);
4325 offset = ClassFileWriter.putInt16(itsNameIndex, data, offset);
4326 offset = ClassFileWriter.putInt16(itsTypeIndex, data, offset);
4327 if (!itsHasAttributes) {
4328 // write 0 attributes
4329 offset = ClassFileWriter.putInt16(0, data, offset);
4330 } else {
4331 offset = ClassFileWriter.putInt16(1, data, offset);
4332 offset = ClassFileWriter.putInt16(itsAttr1, data, offset);
4333 offset = ClassFileWriter.putInt16(itsAttr2, data, offset);
4334 offset = ClassFileWriter.putInt16(itsAttr3, data, offset);
4335 offset = ClassFileWriter.putInt16(itsIndex, data, offset);
4336 }
4337 return offset;
4338 }
4339
4340 int getWriteSize()
4341 {
4342 int size = 2 * 3;
4343 if (!itsHasAttributes) {
4344 size += 2;
4345 } else {
4346 size += 2 + 2 * 4;
4347 }
4348 return size;
4349 }
4350
4351 private short itsNameIndex;
4352 private short itsTypeIndex;
4353 private short itsFlags;
4354 private boolean itsHasAttributes;
4355 private short itsAttr1, itsAttr2, itsAttr3;
4356 private int itsIndex;
4357 }
4358
4359 final class ClassFileMethod
4360 {
4361
4362 ClassFileMethod(String name, short nameIndex, String type, short typeIndex,
4363 short flags)
4364 {
4365 itsName = name;
4366 itsNameIndex = nameIndex;
4367 itsType = type;
4368 itsTypeIndex = typeIndex;
4369 itsFlags = flags;
4370 }
4371
4372 void setCodeAttribute(byte codeAttribute[])
4373 {
4374 itsCodeAttribute = codeAttribute;
4375 }
4376
4377 int write(byte[] data, int offset)
4378 {
4379 offset = ClassFileWriter.putInt16(itsFlags, data, offset);
4380 offset = ClassFileWriter.putInt16(itsNameIndex, data, offset);
4381 offset = ClassFileWriter.putInt16(itsTypeIndex, data, offset);
4382 // Code attribute only
4383 offset = ClassFileWriter.putInt16(1, data, offset);
4384 System.arraycopy(itsCodeAttribute, 0, data, offset,
4385 itsCodeAttribute.length);
4386 offset += itsCodeAttribute.length;
4387 return offset;
4388 }
4389
4390 int getWriteSize()
4391 {
4392 return 2 * 4 + itsCodeAttribute.length;
4393 }
4394
4395 String getName()
4396 {
4397 return itsName;
4398 }
4399
4400 String getType()
4401 {
4402 return itsType;
4403 }
4404
4405 short getFlags()
4406 {
4407 return itsFlags;
4408 }
4409
4410 private String itsName;
4411 private String itsType;
4412 private short itsNameIndex;
4413 private short itsTypeIndex;
4414 private short itsFlags;
4415 private byte[] itsCodeAttribute;
4416
4417 }
4418
4419 final class ConstantPool
4420 {
4421
4422 ConstantPool(ClassFileWriter cfw)
4423 {
4424 this.cfw = cfw;
4425 itsTopIndex = 1; // the zero'th entry is reserved
4426 itsPool = new byte[ConstantPoolSize];
4427 itsTop = 0;
4428 }
4429
4430 private static final int ConstantPoolSize = 256;
4431 static final byte
4432 CONSTANT_Class = 7,
4433 CONSTANT_Fieldref = 9,
4434 CONSTANT_Methodref = 10,
4435 CONSTANT_InterfaceMethodref = 11,
4436 CONSTANT_String = 8,
4437 CONSTANT_Integer = 3,
4438 CONSTANT_Float = 4,
4439 CONSTANT_Long = 5,
4440 CONSTANT_Double = 6,
4441 CONSTANT_NameAndType = 12,
4442 CONSTANT_Utf8 = 1;
4443
4444 int write(byte[] data, int offset)
4445 {
4446 offset = ClassFileWriter.putInt16((short)itsTopIndex, data, offset);
4447 System.arraycopy(itsPool, 0, data, offset, itsTop);
4448 offset += itsTop;
4449 return offset;
4450 }
4451
4452 int getWriteSize()
4453 {
4454 return 2 + itsTop;
4455 }
4456
4457 int addConstant(int k)
4458 {
4459 ensure(5);
4460 itsPool[itsTop++] = CONSTANT_Integer;
4461 itsTop = ClassFileWriter.putInt32(k, itsPool, itsTop);
4462 itsPoolTypes.put(itsTopIndex, CONSTANT_Integer);
4463 return (short)(itsTopIndex++);
4464 }
4465
4466 int addConstant(long k)
4467 {
4468 ensure(9);
4469 itsPool[itsTop++] = CONSTANT_Long;
4470 itsTop = ClassFileWriter.putInt64(k, itsPool, itsTop);
4471 int index = itsTopIndex;
4472 itsTopIndex += 2;
4473 itsPoolTypes.put(index, CONSTANT_Long);
4474 return index;
4475 }
4476
4477 int addConstant(float k)
4478 {
4479 ensure(5);
4480 itsPool[itsTop++] = CONSTANT_Float;
4481 int bits = Float.floatToIntBits(k);
4482 itsTop = ClassFileWriter.putInt32(bits, itsPool, itsTop);
4483 itsPoolTypes.put(itsTopIndex, CONSTANT_Float);
4484 return itsTopIndex++;
4485 }
4486
4487 int addConstant(double k)
4488 {
4489 ensure(9);
4490 itsPool[itsTop++] = CONSTANT_Double;
4491 long bits = Double.doubleToLongBits(k);
4492 itsTop = ClassFileWriter.putInt64(bits, itsPool, itsTop);
4493 int index = itsTopIndex;
4494 itsTopIndex += 2;
4495 itsPoolTypes.put(index, CONSTANT_Double);
4496 return index;
4497 }
4498
4499 int addConstant(String k)
4500 {
4501 int utf8Index = 0xFFFF & addUtf8(k);
4502 int theIndex = itsStringConstHash.getInt(utf8Index, -1);
4503 if (theIndex == -1) {
4504 theIndex = itsTopIndex++;
4505 ensure(3);
4506 itsPool[itsTop++] = CONSTANT_String;
4507 itsTop = ClassFileWriter.putInt16(utf8Index, itsPool, itsTop);
4508 itsStringConstHash.put(utf8Index, theIndex);
4509 }
4510 itsPoolTypes.put(theIndex, CONSTANT_String);
4511 return theIndex;
4512 }
4513
4514 boolean isUnderUtfEncodingLimit(String s)
4515 {
4516 int strLen = s.length();
4517 if (strLen * 3 <= MAX_UTF_ENCODING_SIZE) {
4518 return true;
4519 } else if (strLen > MAX_UTF_ENCODING_SIZE) {
4520 return false;
4521 }
4522 return strLen == getUtfEncodingLimit(s, 0, strLen);
4523 }
4524
4525 /**
4526 * Get maximum i such that <tt>start <= i <= end</tt> and
4527 * <tt>s.substring(start, i)</tt> fits JVM UTF string encoding limit.
4528 */
4529 int getUtfEncodingLimit(String s, int start, int end)
4530 {
4531 if ((end - start) * 3 <= MAX_UTF_ENCODING_SIZE) {
4532 return end;
4533 }
4534 int limit = MAX_UTF_ENCODING_SIZE;
4535 for (int i = start; i != end; i++) {
4536 int c = s.charAt(i);
4537 if (0 != c && c <= 0x7F) {
4538 --limit;
4539 } else if (c < 0x7FF) {
4540 limit -= 2;
4541 } else {
4542 limit -= 3;
4543 }
4544 if (limit < 0) {
4545 return i;
4546 }
4547 }
4548 return end;
4549 }
4550
4551 short addUtf8(String k)
4552 {
4553 int theIndex = itsUtf8Hash.get(k, -1);
4554 if (theIndex == -1) {
4555 int strLen = k.length();
4556 boolean tooBigString;
4557 if (strLen > MAX_UTF_ENCODING_SIZE) {
4558 tooBigString = true;
4559 } else {
4560 tooBigString = false;
4561 // Ask for worst case scenario buffer when each char takes 3
4562 // bytes
4563 ensure(1 + 2 + strLen * 3);
4564 int top = itsTop;
4565
4566 itsPool[top++] = CONSTANT_Utf8;
4567 top += 2; // skip length
4568
4569 char[] chars = cfw.getCharBuffer(strLen);
4570 k.getChars(0, strLen, chars, 0);
4571
4572 for (int i = 0; i != strLen; i++) {
4573 int c = chars[i];
4574 if (c != 0 && c <= 0x7F) {
4575 itsPool[top++] = (byte)c;
4576 } else if (c > 0x7FF) {
4577 itsPool[top++] = (byte)(0xE0 | (c >> 12));
4578 itsPool[top++] = (byte)(0x80 | ((c >> 6) & 0x3F));
4579 itsPool[top++] = (byte)(0x80 | (c & 0x3F));
4580 } else {
4581 itsPool[top++] = (byte)(0xC0 | (c >> 6));
4582 itsPool[top++] = (byte)(0x80 | (c & 0x3F));
4583 }
4584 }
4585
4586 int utfLen = top - (itsTop + 1 + 2);
4587 if (utfLen > MAX_UTF_ENCODING_SIZE) {
4588 tooBigString = true;
4589 } else {
4590 // Write back length
4591 itsPool[itsTop + 1] = (byte)(utfLen >>> 8);
4592 itsPool[itsTop + 2] = (byte)utfLen;
4593
4594 itsTop = top;
4595 theIndex = itsTopIndex++;
4596 itsUtf8Hash.put(k, theIndex);
4597 }
4598 }
4599 if (tooBigString) {
4600 throw new IllegalArgumentException("Too big string");
4601 }
4602 }
4603 setConstantData(theIndex, k);
4604 itsPoolTypes.put(theIndex, CONSTANT_Utf8);
4605 return (short)theIndex;
4606 }
4607
4608 private short addNameAndType(String name, String type)
4609 {
4610 short nameIndex = addUtf8(name);
4611 short typeIndex = addUtf8(type);
4612 ensure(5);
4613 itsPool[itsTop++] = CONSTANT_NameAndType;
4614 itsTop = ClassFileWriter.putInt16(nameIndex, itsPool, itsTop);
4615 itsTop = ClassFileWriter.putInt16(typeIndex, itsPool, itsTop);
4616 itsPoolTypes.put(itsTopIndex, CONSTANT_NameAndType);
4617 return (short)(itsTopIndex++);
4618 }
4619
4620 short addClass(String className)
4621 {
4622 int theIndex = itsClassHash.get(className, -1);
4623 if (theIndex == -1) {
4624 String slashed = className;
4625 if (className.indexOf('.') > 0) {
4626 slashed = ClassFileWriter.getSlashedForm(className);
4627 theIndex = itsClassHash.get(slashed, -1);
4628 if (theIndex != -1) {
4629 itsClassHash.put(className, theIndex);
4630 }
4631 }
4632 if (theIndex == -1) {
4633 int utf8Index = addUtf8(slashed);
4634 ensure(3);
4635 itsPool[itsTop++] = CONSTANT_Class;
4636 itsTop = ClassFileWriter.putInt16(utf8Index, itsPool, itsTop);
4637 theIndex = itsTopIndex++;
4638 itsClassHash.put(slashed, theIndex);
4639 if (className != slashed) {
4640 itsClassHash.put(className, theIndex);
4641 }
4642 }
4643 }
4644 setConstantData(theIndex, className);
4645 itsPoolTypes.put(theIndex, CONSTANT_Class);
4646 return (short)theIndex;
4647 }
4648
4649 short addFieldRef(String className, String fieldName, String fieldType)
4650 {
4651 FieldOrMethodRef ref = new FieldOrMethodRef(className, fieldName,
4652 fieldType);
4653
4654 int theIndex = itsFieldRefHash.get(ref, -1);
4655 if (theIndex == -1) {
4656 short ntIndex = addNameAndType(fieldName, fieldType);
4657 short classIndex = addClass(className);
4658 ensure(5);
4659 itsPool[itsTop++] = CONSTANT_Fieldref;
4660 itsTop = ClassFileWriter.putInt16(classIndex, itsPool, itsTop);
4661 itsTop = ClassFileWriter.putInt16(ntIndex, itsPool, itsTop);
4662 theIndex = itsTopIndex++;
4663 itsFieldRefHash.put(ref, theIndex);
4664 }
4665 setConstantData(theIndex, ref);
4666 itsPoolTypes.put(theIndex, CONSTANT_Fieldref);
4667 return (short)theIndex;
4668 }
4669
4670 short addMethodRef(String className, String methodName,
4671 String methodType)
4672 {
4673 FieldOrMethodRef ref = new FieldOrMethodRef(className, methodName,
4674 methodType);
4675
4676 int theIndex = itsMethodRefHash.get(ref, -1);
4677 if (theIndex == -1) {
4678 short ntIndex = addNameAndType(methodName, methodType);
4679 short classIndex = addClass(className);
4680 ensure(5);
4681 itsPool[itsTop++] = CONSTANT_Methodref;
4682 itsTop = ClassFileWriter.putInt16(classIndex, itsPool, itsTop);
4683 itsTop = ClassFileWriter.putInt16(ntIndex, itsPool, itsTop);
4684 theIndex = itsTopIndex++;
4685 itsMethodRefHash.put(ref, theIndex);
4686 }
4687 setConstantData(theIndex, ref);
4688 itsPoolTypes.put(theIndex, CONSTANT_Methodref);
4689 return (short)theIndex;
4690 }
4691
4692 short addInterfaceMethodRef(String className,
4693 String methodName, String methodType)
4694 {
4695 short ntIndex = addNameAndType(methodName, methodType);
4696 short classIndex = addClass(className);
4697 ensure(5);
4698 itsPool[itsTop++] = CONSTANT_InterfaceMethodref;
4699 itsTop = ClassFileWriter.putInt16(classIndex, itsPool, itsTop);
4700 itsTop = ClassFileWriter.putInt16(ntIndex, itsPool, itsTop);
4701 FieldOrMethodRef r = new FieldOrMethodRef(className, methodName,
4702 methodType);
4703 setConstantData(itsTopIndex, r);
4704 itsPoolTypes.put(itsTopIndex, CONSTANT_InterfaceMethodref);
4705 return (short)(itsTopIndex++);
4706 }
4707
4708 Object getConstantData(int index)
4709 {
4710 return itsConstantData.getObject(index);
4711 }
4712
4713 void setConstantData(int index, Object data)
4714 {
4715 itsConstantData.put(index, data);
4716 }
4717
4718 byte getConstantType(int index)
4719 {
4720 return (byte) itsPoolTypes.getInt(index, 0);
4721 }
4722
4723 void ensure(int howMuch)
4724 {
4725 if (itsTop + howMuch > itsPool.length) {
4726 int newCapacity = itsPool.length * 2;
4727 if (itsTop + howMuch > newCapacity) {
4728 newCapacity = itsTop + howMuch;
4729 }
4730 byte[] tmp = new byte[newCapacity];
4731 System.arraycopy(itsPool, 0, tmp, 0, itsTop);
4732 itsPool = tmp;
4733 }
4734 }
4735
4736 private ClassFileWriter cfw;
4737
4738 private static final int MAX_UTF_ENCODING_SIZE = 65535;
4739
4740 private UintMap itsStringConstHash = new UintMap();
4741 private ObjToIntMap itsUtf8Hash = new ObjToIntMap();
4742 private ObjToIntMap itsFieldRefHash = new ObjToIntMap();
4743 private ObjToIntMap itsMethodRefHash = new ObjToIntMap();
4744 private ObjToIntMap itsClassHash = new ObjToIntMap();
4745
4746 private int itsTop;
4747 private int itsTopIndex;
4748 private UintMap itsConstantData = new UintMap();
4749 private UintMap itsPoolTypes = new UintMap();
4750 private byte itsPool[];
4751 }
4752
4753 final class FieldOrMethodRef
4754 {
4755 FieldOrMethodRef(String className, String name, String type)
4756 {
4757 this.className = className;
4758 this.name = name;
4759 this.type = type;
4760 }
4761
4762 public String getClassName()
4763 {
4764 return className;
4765 }
4766
4767 public String getName()
4768 {
4769 return name;
4770 }
4771
4772 public String getType()
4773 {
4774 return type;
4775 }
4776
4777 @Override
4778 public boolean equals(Object obj)
4779 {
4780 if (!(obj instanceof FieldOrMethodRef)) { return false; }
4781 FieldOrMethodRef x = (FieldOrMethodRef)obj;
4782 return className.equals(x.className)
4783 && name.equals(x.name)
4784 && type.equals(x.type);
4785 }
4786
4787 @Override
4788 public int hashCode()
4789 {
4790 if (hashCode == -1) {
4791 int h1 = className.hashCode();
4792 int h2 = name.hashCode();
4793 int h3 = type.hashCode();
4794 hashCode = h1 ^ h2 ^ h3;
4795 }
4796 return hashCode;
4797 }
4798
4799 private String className;
4800 private String name;
4801 private String type;
4802 private int hashCode = -1;
4803 }
4804
4805 /**
4806 * A super block is defined as a contiguous chunk of code with a single entry
4807 * point and multiple exit points (therefore ending in an unconditional jump
4808 * or the end of the method). This is used to emulate OpenJDK's compiler, which
4809 * outputs stack map frames at the start of every super block except the method
4810 * start.
4811 */
4812 final class SuperBlock {
4813 SuperBlock(int index, int start, int end, int[] initialLocals) {
4814 this.index = index;
4815 this.start = start;
4816 this.end = end;
4817 locals = new int[initialLocals.length];
4818 System.arraycopy(initialLocals, 0, locals, 0, initialLocals.length);
4819 stack = new int[0];
4820 isInitialized = false;
4821 isInQueue = false;
4822 }
4823
4824 int getIndex() {
4825 return index;
4826 }
4827
4828 int[] getLocals() {
4829 int[] copy = new int[locals.length];
4830 System.arraycopy(locals, 0, copy, 0, locals.length);
4831 return copy;
4832 }
4833
4834 /**
4835 * Get a copy of the super block's locals without any trailing TOP types.
4836 *
4837 * This is useful for actual writing stack maps; during the computation of
4838 * stack map types, all local arrays have the same size; the max locals for
4839 * the method. In addition, DOUBLE and LONG types have trailing TOP types
4840 * because they occupy two words. For writing purposes, these are not
4841 * useful.
4842 */
4843 int[] getTrimmedLocals() {
4844 int last = locals.length - 1;
4845 // Exclude all of the trailing TOPs not bound to a DOUBLE/LONG
4846 while (last >= 0 && locals[last] == TypeInfo.TOP &&
4847 !TypeInfo.isTwoWords(locals[last - 1])) {
4848 last--;
4849 }
4850 last++;
4851 // Exclude trailing TOPs following a DOUBLE/LONG
4852 int size = last;
4853 for (int i = 0; i < last; i++) {
4854 if (TypeInfo.isTwoWords(locals[i])) {
4855 size--;
4856 }
4857 }
4858 int[] copy = new int[size];
4859 for (int i = 0, j = 0; i < size; i++, j++) {
4860 copy[i] = locals[j];
4861 if (TypeInfo.isTwoWords(locals[j])) {
4862 j++;
4863 }
4864 }
4865 return copy;
4866 }
4867
4868 int[] getStack() {
4869 int[] copy = new int[stack.length];
4870 System.arraycopy(stack, 0, copy, 0, stack.length);
4871 return copy;
4872 }
4873
4874 boolean merge(int[] locals, int localsTop, int[] stack, int stackTop,
4875 ConstantPool pool) {
4876 if (!isInitialized) {
4877 System.arraycopy(locals, 0, this.locals, 0, localsTop);
4878 this.stack = new int[stackTop];
4879 System.arraycopy(stack, 0, this.stack, 0, stackTop);
4880 isInitialized = true;
4881 return true;
4882 } else if (this.locals.length == localsTop &&
4883 this.stack.length == stackTop) {
4884 boolean localsChanged = mergeState(this.locals, locals, localsTop,
4885 pool);
4886 boolean stackChanged = mergeState(this.stack, stack, stackTop,
4887 pool);
4888 return localsChanged || stackChanged;
4889 } else {
4890 if (ClassFileWriter.StackMapTable.DEBUGSTACKMAP) {
4891 System.out.println("bad merge");
4892 System.out.println("current type state:");
4893 TypeInfo.print(this.locals, this.stack, pool);
4894 System.out.println("incoming type state:");
4895 TypeInfo.print(locals, localsTop, stack, stackTop, pool);
4896 }
4897 throw new IllegalArgumentException("bad merge attempt");
4898 }
4899 }
4900
4901 /**
4902 * Merge an operand stack or local variable array with incoming state.
4903 *
4904 * They are treated the same way; by this point, it should already be
4905 * ensured that the array sizes are the same, which is the only additional
4906 * constraint that is imposed on merging operand stacks (the local variable
4907 * array is always the same size).
4908 */
4909 private boolean mergeState(int[] current, int[] incoming, int size,
4910 ConstantPool pool) {
4911 boolean changed = false;
4912 for (int i = 0; i < size; i++) {
4913 int currentType = current[i];
4914
4915 current[i] = TypeInfo.merge(current[i], incoming[i], pool);
4916 if (currentType != current[i]) {
4917 changed = true;
4918 }
4919 }
4920 return changed;
4921 }
4922
4923 int getStart() {
4924 return start;
4925 }
4926
4927 int getEnd() {
4928 return end;
4929 }
4930
4931 @Override
4932 public String toString() {
4933 return "sb " + index;
4934 }
4935
4936 boolean isInitialized() {
4937 return isInitialized;
4938 }
4939
4940 void setInitialized(boolean b) {
4941 isInitialized = b;
4942 }
4943
4944 boolean isInQueue() {
4945 return isInQueue;
4946 }
4947
4948 void setInQueue(boolean b) {
4949 isInQueue = b;
4950 }
4951
4952 private int index;
4953 private int start;
4954 private int end;
4955 private int[] locals;
4956 private int[] stack;
4957 private boolean isInitialized;
4958 private boolean isInQueue;
4959 }
4960
4961 /**
4962 * Helper class for internal representations of type information. In most
4963 * cases, type information can be represented by a constant, but in some
4964 * cases, a payload is included. Despite the payload coming after the type
4965 * tag in the output, we store it in bits 8-23 for uniformity; the tag is
4966 * always in bits 0-7.
4967 */
4968 final class TypeInfo {
4969 private TypeInfo() { }
4970
4971 static final int TOP = 0;
4972 static final int INTEGER = 1;
4973 static final int FLOAT = 2;
4974 static final int DOUBLE = 3;
4975 static final int LONG = 4;
4976 static final int NULL = 5;
4977 static final int UNINITIALIZED_THIS = 6;
4978 static final int OBJECT_TAG = 7;
4979 static final int UNINITIALIZED_VAR_TAG = 8;
4980
4981 static final int OBJECT(int constantPoolIndex) {
4982 return ((constantPoolIndex & 0xFFFF) << 8) | OBJECT_TAG;
4983 }
4984
4985 static final int OBJECT(String type, ConstantPool pool) {
4986 return OBJECT(pool.addClass(type));
4987 }
4988
4989 static final int UNINITIALIZED_VARIABLE(int bytecodeOffset) {
4990 return ((bytecodeOffset & 0xFFFF) << 8) | UNINITIALIZED_VAR_TAG;
4991 }
4992
4993 static final int getTag(int typeInfo) {
4994 return typeInfo & 0xFF;
4995 }
4996
4997 static final int getPayload(int typeInfo) {
4998 return typeInfo >>> 8;
4999 }
5000
5001 /**
5002 * Treat the result of getPayload as a constant pool index and fetch the
5003 * corresponding String mapped to it.
5004 *
5005 * Only works on OBJECT types.
5006 */
5007 static final String getPayloadAsType(int typeInfo, ConstantPool pool) {
5008 if (getTag(typeInfo) == OBJECT_TAG) {
5009 return (String) pool.getConstantData(getPayload(typeInfo));
5010 }
5011 throw new IllegalArgumentException("expecting object type");
5012 }
5013
5014 /**
5015 * Create type information from an internal type.
5016 */
5017 static final int fromType(String type, ConstantPool pool) {
5018 if (type.length() == 1) {
5019 switch (type.charAt(0)) {
5020 case 'B': // sbyte
5021 case 'C': // unicode char
5022 case 'S': // short
5023 case 'Z': // boolean
5024 case 'I': // all of the above are verified as integers
5025 return INTEGER;
5026 case 'D':
5027 return DOUBLE;
5028 case 'F':
5029 return FLOAT;
5030 case 'J':
5031 return LONG;
5032 default:
5033 throw new IllegalArgumentException("bad type");
5034 }
5035 }
5036 return TypeInfo.OBJECT(type, pool);
5037 }
5038
5039 static boolean isTwoWords(int type) {
5040 return type == DOUBLE || type == LONG;
5041 }
5042
5043 /**
5044 * Merge two verification types.
5045 *
5046 * In most cases, the verification types must be the same. For example,
5047 * INTEGER and DOUBLE cannot be merged and an exception will be thrown.
5048 * The basic rules are:
5049 *
5050 * - If the types are equal, simply return one.
5051 * - If either type is TOP, return TOP.
5052 * - If either type is NULL, return the other type.
5053 * - If both types are objects, find the lowest common ancestor in the
5054 * class hierarchy.
5055 *
5056 * This method uses reflection to traverse the class hierarchy. Therefore,
5057 * it is assumed that the current class being generated is never the target
5058 * of a full object-object merge, which would need to load the current
5059 * class reflectively.
5060 */
5061 static int merge(int current, int incoming, ConstantPool pool) {
5062 int currentTag = getTag(current);
5063 int incomingTag = getTag(incoming);
5064 boolean currentIsObject = currentTag == TypeInfo.OBJECT_TAG;
5065 boolean incomingIsObject = incomingTag == TypeInfo.OBJECT_TAG;
5066
5067 if (current == incoming || (currentIsObject && incoming == NULL)) {
5068 return current;
5069 } else if (currentTag == TypeInfo.TOP ||
5070 incomingTag == TypeInfo.TOP) {
5071 return TypeInfo.TOP;
5072 } else if (current == NULL && incomingIsObject) {
5073 return incoming;
5074 } else if (currentIsObject && incomingIsObject) {
5075 String currentName = getPayloadAsType(current, pool);
5076 String incomingName = getPayloadAsType(incoming, pool);
5077 // The class file always has the class and super names in the same
5078 // spot. The constant order is: class_data, class_name, super_data,
5079 // super_name.
5080 String currentlyGeneratedName = (String) pool.getConstantData(2);
5081 String currentlyGeneratedSuperName =
5082 (String) pool.getConstantData(4);
5083
5084 // If any of the merged types are the class that's currently being
5085 // generated, automatically start at the super class instead. At
5086 // this point, we already know the classes are different, so we
5087 // don't need to handle that case.
5088 if (currentName.equals(currentlyGeneratedName)) {
5089 currentName = currentlyGeneratedSuperName;
5090 }
5091 if (incomingName.equals(currentlyGeneratedName)) {
5092 incomingName = currentlyGeneratedSuperName;
5093 }
5094
5095 Class<?> currentClass = getClassFromInternalName(currentName);
5096 Class<?> incomingClass = getClassFromInternalName(incomingName);
5097
5098 if (currentClass.isAssignableFrom(incomingClass)) {
5099 return current;
5100 } else if (incomingClass.isAssignableFrom(currentClass)) {
5101 return incoming;
5102 } else if (incomingClass.isInterface() ||
5103 currentClass.isInterface()) {
5104 // For verification purposes, Sun specifies that interfaces are
5105 // subtypes of Object. Therefore, we know that the merge result
5106 // involving interfaces where one is not assignable to the
5107 // other results in Object.
5108 return OBJECT("java/lang/Object", pool);
5109 } else {
5110 Class<?> commonClass = incomingClass.getSuperclass();
5111 while (commonClass != null) {
5112 if (commonClass.isAssignableFrom(currentClass)) {
5113 String name = commonClass.getName();
5114 name = ClassFileWriter.getSlashedForm(name);
5115 return OBJECT(name, pool);
5116 }
5117 commonClass = commonClass.getSuperclass();
5118 }
5119 }
5120 }
5121 throw new IllegalArgumentException("bad merge attempt between " +
5122 toString(current, pool) + " and " +
5123 toString(incoming, pool));
5124 }
5125
5126 static String toString(int type, ConstantPool pool) {
5127 int tag = getTag(type);
5128 switch (tag) {
5129 case TypeInfo.TOP:
5130 return "top";
5131 case TypeInfo.INTEGER:
5132 return "int";
5133 case TypeInfo.FLOAT:
5134 return "float";
5135 case TypeInfo.DOUBLE:
5136 return "double";
5137 case TypeInfo.LONG:
5138 return "long";
5139 case TypeInfo.NULL:
5140 return "null";
5141 case TypeInfo.UNINITIALIZED_THIS:
5142 return "uninitialized_this";
5143 default:
5144 if (tag == TypeInfo.OBJECT_TAG) {
5145 return getPayloadAsType(type, pool);
5146 } else if (tag == TypeInfo.UNINITIALIZED_VAR_TAG) {
5147 return "uninitialized";
5148 } else {
5149 throw new IllegalArgumentException("bad type");
5150 }
5151 }
5152 }
5153
5154 /**
5155 * Take an internal name and return a java.lang.Class instance that
5156 * represents it.
5157 *
5158 * For example, given "java/lang/Object", returns the equivalent of
5159 * Class.forName("java.lang.Object"), but also handles exceptions.
5160 */
5161 static Class<?> getClassFromInternalName(String internalName) {
5162 try {
5163 return Class.forName(internalName.replace('/', '.'));
5164 } catch (ClassNotFoundException e) {
5165 throw new RuntimeException(e);
5166 }
5167 }
5168
5169 static String toString(int[] types, ConstantPool pool) {
5170 return toString(types, types.length, pool);
5171 }
5172
5173 static String toString(int[] types, int typesTop, ConstantPool pool) {
5174 StringBuilder sb = new StringBuilder();
5175 sb.append("[");
5176 for (int i = 0; i < typesTop; i++) {
5177 if (i > 0) {
5178 sb.append(", ");
5179 }
5180 sb.append(toString(types[i], pool));
5181 }
5182 sb.append("]");
5183 return sb.toString();
5184 }
5185
5186 static void print(int[] locals, int[] stack, ConstantPool pool) {
5187 print(locals, locals.length, stack, stack.length, pool);
5188 }
5189
5190 static void print(int[] locals, int localsTop, int[] stack, int stackTop,
5191 ConstantPool pool) {
5192 System.out.print("locals: ");
5193 System.out.println(toString(locals, localsTop, pool));
5194 System.out.print("stack: ");
5195 System.out.println(toString(stack, stackTop, pool));
5196 System.out.println();
5197 }
5198 }