KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > logicalcobwebs > asm > CodeWriter


1 /***
2  * ASM: a very small and fast Java bytecode manipulation framework
3  * Copyright (c) 2000,2002,2003 INRIA, France Telecom
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the copyright holders nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28  * THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Contact: Eric.Bruneton@rd.francetelecom.com
31  *
32  * Author: Eric Bruneton
33  */

34
35 package org.logicalcobwebs.asm;
36
37 /**
38  * A {@link CodeVisitor CodeVisitor} that generates Java bytecode instructions.
39  * Each visit method of this class appends the bytecode corresponding to the
40  * visited instruction to a byte vector, in the order these methods are called.
41  */

42
43 public class CodeWriter implements CodeVisitor {
44
45   /**
46    * <tt>true</tt> if preconditions must be checked at runtime or not.
47    */

48
49   final static boolean CHECK = false;
50
51   /**
52    * Next code writer (see {@link ClassWriter#firstMethod firstMethod}).
53    */

54
55   CodeWriter next;
56
57   /**
58    * The class writer to which this method must be added.
59    */

60
61   private ClassWriter cw;
62
63   /**
64    * The index of the constant pool item that contains the name of this method.
65    */

66
67   private int name;
68
69   /**
70    * The index of the constant pool item that contains the descriptor of this
71    * method.
72    */

73
74   private int desc;
75
76   /**
77    * Access flags of this method.
78    */

79
80   private int access;
81
82   /**
83    * Maximum stack size of this method.
84    */

85
86   private int maxStack;
87
88   /**
89    * Maximum number of local variables for this method.
90    */

91
92   private int maxLocals;
93
94   /**
95    * The bytecode of this method.
96    */

97
98   private ByteVector code = new ByteVector();
99
100   /**
101    * Number of entries in the catch table of this method.
102    */

103
104   private int catchCount;
105
106   /**
107    * The catch table of this method.
108    */

109
110   private ByteVector catchTable;
111
112   /**
113    * Number of exceptions that can be thrown by this method.
114    */

115
116   private int exceptionCount;
117
118   /**
119    * The exceptions that can be thrown by this method. More
120    * precisely, this array contains the indexes of the constant pool items
121    * that contain the internal names of these exception classes.
122    */

123
124   private int[] exceptions;
125
126   /**
127    * The non standard attributes of the method.
128    */

129
130   private Attribute attrs;
131
132   /**
133    * Number of entries in the LocalVariableTable attribute.
134    */

135
136   private int localVarCount;
137
138   /**
139    * The LocalVariableTable attribute.
140    */

141
142   private ByteVector localVar;
143
144   /**
145    * Number of entries in the LineNumberTable attribute.
146    */

147
148   private int lineNumberCount;
149
150   /**
151    * The LineNumberTable attribute.
152    */

153
154   private ByteVector lineNumber;
155
156   /**
157    * The non standard attributes of the method's code.
158    */

159
160   private Attribute cattrs;
161
162   /**
163    * Indicates if some jump instructions are too small and need to be resized.
164    */

165
166   private boolean resize;
167
168   // --------------------------------------------------------------------------
169
// Fields for the control flow graph analysis algorithm (used to compute the
170
// maximum stack size). A control flow graph contains one node per "basic
171
// block", and one edge per "jump" from one basic block to another. Each node
172
// (i.e., each basic block) is represented by the Label object that
173
// corresponds to the first instruction of this basic block. Each node also
174
// stores the list of its successors in the graph, as a linked list of Edge
175
// objects.
176
// --------------------------------------------------------------------------
177

178   /**
179    * <tt>true</tt> if the maximum stack size and number of local variables must
180    * be automatically computed.
181    */

182
183   private final boolean computeMaxs;
184
185   /**
186    * The (relative) stack size after the last visited instruction. This size is
187    * relative to the beginning of the current basic block, i.e., the true stack
188    * size after the last visited instruction is equal to the {@link
189    * Label#beginStackSize beginStackSize} of the current basic block plus
190    * <tt>stackSize</tt>.
191    */

192
193   private int stackSize;
194
195   /**
196    * The (relative) maximum stack size after the last visited instruction. This
197    * size is relative to the beginning of the current basic block, i.e., the
198    * true maximum stack size after the last visited instruction is equal to the
199    * {@link Label#beginStackSize beginStackSize} of the current basic block plus
200    * <tt>stackSize</tt>.
201    */

202
203   private int maxStackSize;
204
205   /**
206    * The current basic block. This block is the basic block to which the next
207    * instruction to be visited must be added.
208    */

209
210   private Label currentBlock;
211
212   /**
213    * The basic block stack used by the control flow analysis algorithm. This
214    * stack is represented by a linked list of {@link Label Label} objects,
215    * linked to each other by their {@link Label#next} field. This stack must
216    * not be confused with the JVM stack used to execute the JVM instructions!
217    */

218
219   private Label blockStack;
220
221   /**
222    * The stack size variation corresponding to each JVM instruction. This stack
223    * variation is equal to the size of the values produced by an instruction,
224    * minus the size of the values consumed by this instruction.
225    */

226
227   private final static int[] SIZE;
228
229   // --------------------------------------------------------------------------
230
// Fields to optimize the creation of {@link Edge Edge} objects by using a
231
// pool of reusable objects. The (shared) pool is a linked list of Edge
232
// objects, linked to each other by their {@link Edge#poolNext} field. Each
233
// time a CodeWriter needs to allocate an Edge, it removes the first Edge
234
// of the pool and adds it to a private list of Edge objects. After the end
235
// of the control flow analysis algorithm, the Edge objects in the private
236
// list of the CodeWriter are added back to the pool (by appending this
237
// private list to the pool list; in order to do this in constant time, both
238
// head and tail of the private list are stored in this CodeWriter).
239
// --------------------------------------------------------------------------
240

241   /**
242    * The head of the list of {@link Edge Edge} objects used by this {@link
243    * CodeWriter CodeWriter}. These objects, linked to each other by their
244    * {@link Edge#poolNext} field, are added back to the shared pool at the
245    * end of the control flow analysis algorithm.
246    */

247
248   private Edge head;
249
250   /**
251    * The tail of the list of {@link Edge Edge} objects used by this {@link
252    * CodeWriter CodeWriter}. These objects, linked to each other by their
253    * {@link Edge#poolNext} field, are added back to the shared pool at the
254    * end of the control flow analysis algorithm.
255    */

256
257   private Edge tail;
258
259   /**
260    * The shared pool of {@link Edge Edge} objects. This pool is a linked list
261    * of Edge objects, linked to each other by their {@link Edge#poolNext} field.
262    */

263
264   private static Edge pool;
265
266   // --------------------------------------------------------------------------
267
// Static initializer
268
// --------------------------------------------------------------------------
269

270   /**
271    * Computes the stack size variation corresponding to each JVM instruction.
272    */

273
274   static {
275     int i;
276     int[] b = new int[202];
277     String JavaDoc s =
278       "EFFFFFFFFGGFFFGGFFFEEFGFGFEEEEEEEEEEEEEEEEEEEEDEDEDDDDDCDCDEEEEEEEEE" +
279       "EEEEEEEEEEEBABABBBBDCFFFGGGEDCDCDCDCDCDCDCDCDCDCEEEEDDDDDDDCDCDCEFEF" +
280       "DDEEFFDEDEEEBDDBBDDDDDDCCCCCCCCEFEDDDCDCDEEEEEEEEEEFEEEEEEDDEEDDEE";
281     for (i = 0; i < b.length; ++i) {
282       b[i] = s.charAt(i) - 'E';
283     }
284     SIZE = b;
285
286     /* code to generate the above string
287
288     int NA = 0; // not applicable (unused opcode or variable size opcode)
289
290     b = new int[] {
291       0, //NOP, // visitInsn
292       1, //ACONST_NULL, // -
293       1, //ICONST_M1, // -
294       1, //ICONST_0, // -
295       1, //ICONST_1, // -
296       1, //ICONST_2, // -
297       1, //ICONST_3, // -
298       1, //ICONST_4, // -
299       1, //ICONST_5, // -
300       2, //LCONST_0, // -
301       2, //LCONST_1, // -
302       1, //FCONST_0, // -
303       1, //FCONST_1, // -
304       1, //FCONST_2, // -
305       2, //DCONST_0, // -
306       2, //DCONST_1, // -
307       1, //BIPUSH, // visitIntInsn
308       1, //SIPUSH, // -
309       1, //LDC, // visitLdcInsn
310       NA, //LDC_W, // -
311       NA, //LDC2_W, // -
312       1, //ILOAD, // visitVarInsn
313       2, //LLOAD, // -
314       1, //FLOAD, // -
315       2, //DLOAD, // -
316       1, //ALOAD, // -
317       NA, //ILOAD_0, // -
318       NA, //ILOAD_1, // -
319       NA, //ILOAD_2, // -
320       NA, //ILOAD_3, // -
321       NA, //LLOAD_0, // -
322       NA, //LLOAD_1, // -
323       NA, //LLOAD_2, // -
324       NA, //LLOAD_3, // -
325       NA, //FLOAD_0, // -
326       NA, //FLOAD_1, // -
327       NA, //FLOAD_2, // -
328       NA, //FLOAD_3, // -
329       NA, //DLOAD_0, // -
330       NA, //DLOAD_1, // -
331       NA, //DLOAD_2, // -
332       NA, //DLOAD_3, // -
333       NA, //ALOAD_0, // -
334       NA, //ALOAD_1, // -
335       NA, //ALOAD_2, // -
336       NA, //ALOAD_3, // -
337       -1, //IALOAD, // visitInsn
338       0, //LALOAD, // -
339       -1, //FALOAD, // -
340       0, //DALOAD, // -
341       -1, //AALOAD, // -
342       -1, //BALOAD, // -
343       -1, //CALOAD, // -
344       -1, //SALOAD, // -
345       -1, //ISTORE, // visitVarInsn
346       -2, //LSTORE, // -
347       -1, //FSTORE, // -
348       -2, //DSTORE, // -
349       -1, //ASTORE, // -
350       NA, //ISTORE_0, // -
351       NA, //ISTORE_1, // -
352       NA, //ISTORE_2, // -
353       NA, //ISTORE_3, // -
354       NA, //LSTORE_0, // -
355       NA, //LSTORE_1, // -
356       NA, //LSTORE_2, // -
357       NA, //LSTORE_3, // -
358       NA, //FSTORE_0, // -
359       NA, //FSTORE_1, // -
360       NA, //FSTORE_2, // -
361       NA, //FSTORE_3, // -
362       NA, //DSTORE_0, // -
363       NA, //DSTORE_1, // -
364       NA, //DSTORE_2, // -
365       NA, //DSTORE_3, // -
366       NA, //ASTORE_0, // -
367       NA, //ASTORE_1, // -
368       NA, //ASTORE_2, // -
369       NA, //ASTORE_3, // -
370       -3, //IASTORE, // visitInsn
371       -4, //LASTORE, // -
372       -3, //FASTORE, // -
373       -4, //DASTORE, // -
374       -3, //AASTORE, // -
375       -3, //BASTORE, // -
376       -3, //CASTORE, // -
377       -3, //SASTORE, // -
378       -1, //POP, // -
379       -2, //POP2, // -
380       1, //DUP, // -
381       1, //DUP_X1, // -
382       1, //DUP_X2, // -
383       2, //DUP2, // -
384       2, //DUP2_X1, // -
385       2, //DUP2_X2, // -
386       0, //SWAP, // -
387       -1, //IADD, // -
388       -2, //LADD, // -
389       -1, //FADD, // -
390       -2, //DADD, // -
391       -1, //ISUB, // -
392       -2, //LSUB, // -
393       -1, //FSUB, // -
394       -2, //DSUB, // -
395       -1, //IMUL, // -
396       -2, //LMUL, // -
397       -1, //FMUL, // -
398       -2, //DMUL, // -
399       -1, //IDIV, // -
400       -2, //LDIV, // -
401       -1, //FDIV, // -
402       -2, //DDIV, // -
403       -1, //IREM, // -
404       -2, //LREM, // -
405       -1, //FREM, // -
406       -2, //DREM, // -
407       0, //INEG, // -
408       0, //LNEG, // -
409       0, //FNEG, // -
410       0, //DNEG, // -
411       -1, //ISHL, // -
412       -1, //LSHL, // -
413       -1, //ISHR, // -
414       -1, //LSHR, // -
415       -1, //IUSHR, // -
416       -1, //LUSHR, // -
417       -1, //IAND, // -
418       -2, //LAND, // -
419       -1, //IOR, // -
420       -2, //LOR, // -
421       -1, //IXOR, // -
422       -2, //LXOR, // -
423       0, //IINC, // visitIincInsn
424       1, //I2L, // visitInsn
425       0, //I2F, // -
426       1, //I2D, // -
427       -1, //L2I, // -
428       -1, //L2F, // -
429       0, //L2D, // -
430       0, //F2I, // -
431       1, //F2L, // -
432       1, //F2D, // -
433       -1, //D2I, // -
434       0, //D2L, // -
435       -1, //D2F, // -
436       0, //I2B, // -
437       0, //I2C, // -
438       0, //I2S, // -
439       -3, //LCMP, // -
440       -1, //FCMPL, // -
441       -1, //FCMPG, // -
442       -3, //DCMPL, // -
443       -3, //DCMPG, // -
444       -1, //IFEQ, // visitJumpInsn
445       -1, //IFNE, // -
446       -1, //IFLT, // -
447       -1, //IFGE, // -
448       -1, //IFGT, // -
449       -1, //IFLE, // -
450       -2, //IF_ICMPEQ, // -
451       -2, //IF_ICMPNE, // -
452       -2, //IF_ICMPLT, // -
453       -2, //IF_ICMPGE, // -
454       -2, //IF_ICMPGT, // -
455       -2, //IF_ICMPLE, // -
456       -2, //IF_ACMPEQ, // -
457       -2, //IF_ACMPNE, // -
458       0, //GOTO, // -
459       1, //JSR, // -
460       0, //RET, // visitVarInsn
461       -1, //TABLESWITCH, // visiTableSwitchInsn
462       -1, //LOOKUPSWITCH, // visitLookupSwitch
463       -1, //IRETURN, // visitInsn
464       -2, //LRETURN, // -
465       -1, //FRETURN, // -
466       -2, //DRETURN, // -
467       -1, //ARETURN, // -
468       0, //RETURN, // -
469       NA, //GETSTATIC, // visitFieldInsn
470       NA, //PUTSTATIC, // -
471       NA, //GETFIELD, // -
472       NA, //PUTFIELD, // -
473       NA, //INVOKEVIRTUAL, // visitMethodInsn
474       NA, //INVOKESPECIAL, // -
475       NA, //INVOKESTATIC, // -
476       NA, //INVOKEINTERFACE, // -
477       NA, //UNUSED, // NOT VISITED
478       1, //NEW, // visitTypeInsn
479       0, //NEWARRAY, // visitIntInsn
480       0, //ANEWARRAY, // visitTypeInsn
481       0, //ARRAYLENGTH, // visitInsn
482       NA, //ATHROW, // -
483       0, //CHECKCAST, // visitTypeInsn
484       0, //INSTANCEOF, // -
485       -1, //MONITORENTER, // visitInsn
486       -1, //MONITOREXIT, // -
487       NA, //WIDE, // NOT VISITED
488       NA, //MULTIANEWARRAY, // visitMultiANewArrayInsn
489       -1, //IFNULL, // visitJumpInsn
490       -1, //IFNONNULL, // -
491       NA, //GOTO_W, // -
492       NA, //JSR_W, // -
493     };
494     for (i = 0; i < b.length; ++i) {
495       System.err.print((char)('E' + b[i]));
496     }
497     System.err.println();
498     */

499   }
500
501   // --------------------------------------------------------------------------
502
// Constructor
503
// --------------------------------------------------------------------------
504

505   /**
506    * Constructs a CodeWriter.
507    *
508    * @param cw the class writer in which the method must be added.
509    * @param computeMaxs <tt>true</tt> if the maximum stack size and number of
510    * local variables must be automatically computed.
511    */

512
513   protected CodeWriter (final ClassWriter cw, final boolean computeMaxs) {
514     if (cw.firstMethod == null) {
515       cw.firstMethod = this;
516       cw.lastMethod = this;
517     } else {
518       cw.lastMethod.next = this;
519       cw.lastMethod = this;
520     }
521     this.cw = cw;
522     this.computeMaxs = computeMaxs;
523     if (computeMaxs) {
524       // pushes the first block onto the stack of blocks to be visited
525
currentBlock = new Label();
526       currentBlock.pushed = true;
527       blockStack = currentBlock;
528     }
529   }
530
531   /**
532    * Initializes this CodeWriter to define the bytecode of the specified method.
533    *
534    * @param access the method's access flags (see {@link Constants}).
535    * @param name the method's name.
536    * @param desc the method's descriptor (see {@link Type Type}).
537    * @param exceptions the internal names of the method's exceptions. May be
538    * <tt>null</tt>.
539    * @param attrs the non standard attributes of the method.
540    */

541
542   protected void init (
543     final int access,
544     final String JavaDoc name,
545     final String JavaDoc desc,
546     final String JavaDoc[] exceptions,
547     final Attribute attrs)
548   {
549     this.access = access;
550     this.name = cw.newUTF8(name);
551     this.desc = cw.newUTF8(desc);
552     if (exceptions != null && exceptions.length > 0) {
553       exceptionCount = exceptions.length;
554       this.exceptions = new int[exceptionCount];
555       for (int i = 0; i < exceptionCount; ++i) {
556         this.exceptions[i] = cw.newClass(exceptions[i]);
557       }
558     }
559     this.attrs = attrs;
560     if (computeMaxs) {
561       // updates maxLocals
562
int size = getArgumentsAndReturnSizes(desc) >> 2;
563       if ((access & Constants.ACC_STATIC) != 0) {
564         --size;
565       }
566       if (size > maxLocals) {
567         maxLocals = size;
568       }
569     }
570   }
571
572   // --------------------------------------------------------------------------
573
// Implementation of the CodeVisitor interface
574
// --------------------------------------------------------------------------
575

576   public void visitInsn (final int opcode) {
577     if (computeMaxs) {
578       // updates current and max stack sizes
579
int size = stackSize + SIZE[opcode];
580       if (size > maxStackSize) {
581         maxStackSize = size;
582       }
583       stackSize = size;
584       // if opcode == ATHROW or xRETURN, ends current block (no successor)
585
if ((opcode >= Constants.IRETURN && opcode <= Constants.RETURN) ||
586           opcode == Constants.ATHROW)
587       {
588         if (currentBlock != null) {
589           currentBlock.maxStackSize = maxStackSize;
590           currentBlock = null;
591         }
592       }
593     }
594     // adds the instruction to the bytecode of the method
595
code.put1(opcode);
596   }
597
598   public void visitIntInsn (final int opcode, final int operand) {
599     if (computeMaxs && opcode != Constants.NEWARRAY) {
600       // updates current and max stack sizes only if opcode == NEWARRAY
601
// (stack size variation = 0 for BIPUSH or SIPUSH)
602
int size = stackSize + 1;
603       if (size > maxStackSize) {
604         maxStackSize = size;
605       }
606       stackSize = size;
607     }
608     // adds the instruction to the bytecode of the method
609
if (opcode == Constants.SIPUSH) {
610       code.put12(opcode, operand);
611     } else { // BIPUSH or NEWARRAY
612
code.put11(opcode, operand);
613     }
614   }
615
616   public void visitVarInsn (final int opcode, final int var) {
617     if (computeMaxs) {
618       // updates current and max stack sizes
619
if (opcode == Constants.RET) {
620         // no stack change, but end of current block (no successor)
621
if (currentBlock != null) {
622           currentBlock.maxStackSize = maxStackSize;
623           currentBlock = null;
624         }
625       } else { // xLOAD or xSTORE
626
int size = stackSize + SIZE[opcode];
627         if (size > maxStackSize) {
628           maxStackSize = size;
629         }
630         stackSize = size;
631       }
632       // updates max locals
633
int n;
634       if (opcode == Constants.LLOAD || opcode == Constants.DLOAD ||
635           opcode == Constants.LSTORE || opcode == Constants.DSTORE)
636       {
637         n = var + 2;
638       } else {
639         n = var + 1;
640       }
641       if (n > maxLocals) {
642         maxLocals = n;
643       }
644     }
645     // adds the instruction to the bytecode of the method
646
if (var < 4 && opcode != Constants.RET) {
647       int opt;
648       if (opcode < Constants.ISTORE) {
649         opt = 26 /*ILOAD_0*/ + ((opcode - Constants.ILOAD) << 2) + var;
650       } else {
651         opt = 59 /*ISTORE_0*/ + ((opcode - Constants.ISTORE) << 2) + var;
652       }
653       code.put1(opt);
654     } else if (var >= 256) {
655       code.put1(196 /*WIDE*/).put12(opcode, var);
656     } else {
657       code.put11(opcode, var);
658     }
659   }
660
661   public void visitTypeInsn (final int opcode, final String JavaDoc desc) {
662     if (computeMaxs && opcode == Constants.NEW) {
663       // updates current and max stack sizes only if opcode == NEW
664
// (stack size variation = 0 for ANEWARRAY, CHECKCAST, INSTANCEOF)
665
int size = stackSize + 1;
666       if (size > maxStackSize) {
667         maxStackSize = size;
668       }
669       stackSize = size;
670     }
671     // adds the instruction to the bytecode of the method
672
code.put12(opcode, cw.newClass(desc));
673   }
674
675   public void visitFieldInsn (
676     final int opcode,
677     final String JavaDoc owner,
678     final String JavaDoc name,
679     final String JavaDoc desc)
680   {
681     if (computeMaxs) {
682       int size;
683       // computes the stack size variation
684
char c = desc.charAt(0);
685       switch (opcode) {
686         case Constants.GETSTATIC:
687           size = stackSize + (c == 'D' || c == 'J' ? 2 : 1);
688           break;
689         case Constants.PUTSTATIC:
690           size = stackSize + (c == 'D' || c == 'J' ? -2 : -1);
691           break;
692         case Constants.GETFIELD:
693           size = stackSize + (c == 'D' || c == 'J' ? 1 : 0);
694           break;
695         //case Constants.PUTFIELD:
696
default:
697           size = stackSize + (c == 'D' || c == 'J' ? -3 : -2);
698           break;
699       }
700       // updates current and max stack sizes
701
if (size > maxStackSize) {
702         maxStackSize = size;
703       }
704       stackSize = size;
705     }
706     // adds the instruction to the bytecode of the method
707
code.put12(opcode, cw.newField(owner, name, desc));
708   }
709
710   public void visitMethodInsn (
711     final int opcode,
712     final String JavaDoc owner,
713     final String JavaDoc name,
714     final String JavaDoc desc)
715   {
716     boolean itf = opcode == Constants.INVOKEINTERFACE;
717     Item i = cw.newMethodItem(owner, name, desc, itf);
718     int argSize = i.intVal;
719     if (computeMaxs) {
720       // computes the stack size variation. In order not to recompute several
721
// times this variation for the same Item, we use the intVal field of
722
// this item to store this variation, once it has been computed. More
723
// precisely this intVal field stores the sizes of the arguments and of
724
// the return value corresponding to desc.
725
if (argSize == 0) {
726         // the above sizes have not been computed yet, so we compute them...
727
argSize = getArgumentsAndReturnSizes(desc);
728         // ... and we save them in order not to recompute them in the future
729
i.intVal = argSize;
730       }
731       int size;
732       if (opcode == Constants.INVOKESTATIC) {
733         size = stackSize - (argSize >> 2) + (argSize & 0x03) + 1;
734       } else {
735         size = stackSize - (argSize >> 2) + (argSize & 0x03);
736       }
737       // updates current and max stack sizes
738
if (size > maxStackSize) {
739         maxStackSize = size;
740       }
741       stackSize = size;
742     }
743     // adds the instruction to the bytecode of the method
744
if (itf) {
745       if (!computeMaxs) {
746         if (argSize == 0) {
747           argSize = getArgumentsAndReturnSizes(desc);
748           i.intVal = argSize;
749         }
750       }
751       code.put12(Constants.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0);
752     } else {
753       code.put12(opcode, i.index);
754     }
755   }
756
757   public void visitJumpInsn (final int opcode, final Label label) {
758     if (CHECK) {
759       if (label.owner == null) {
760         label.owner = this;
761       } else if (label.owner != this) {
762         throw new IllegalArgumentException JavaDoc();
763       }
764     }
765     if (computeMaxs) {
766       if (opcode == Constants.GOTO) {
767         // no stack change, but end of current block (with one new successor)
768
if (currentBlock != null) {
769           currentBlock.maxStackSize = maxStackSize;
770           addSuccessor(stackSize, label);
771           currentBlock = null;
772         }
773       } else if (opcode == Constants.JSR) {
774         if (currentBlock != null) {
775           addSuccessor(stackSize + 1, label);
776         }
777       } else {
778         // updates current stack size (max stack size unchanged because stack
779
// size variation always negative in this case)
780
stackSize += SIZE[opcode];
781         if (currentBlock != null) {
782           addSuccessor(stackSize, label);
783         }
784       }
785     }
786     // adds the instruction to the bytecode of the method
787
if (label.resolved && label.position - code.length < Short.MIN_VALUE) {
788       // case of a backward jump with an offset < -32768. In this case we
789
// automatically replace GOTO with GOTO_W, JSR with JSR_W and IFxxx <l>
790
// with IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is the "opposite" opcode
791
// of IFxxx (i.e., IFNE for IFEQ) and where <l'> designates the
792
// instruction just after the GOTO_W.
793
if (opcode == Constants.GOTO) {
794         code.put1(200); // GOTO_W
795
} else if (opcode == Constants.JSR) {
796         code.put1(201); // JSR_W
797
} else {
798         code.put1(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1);
799         code.put2(8); // jump offset
800
code.put1(200); // GOTO_W
801
}
802       label.put(this, code, code.length - 1, true);
803     } else {
804       // case of a backward jump with an offset >= -32768, or of a forward jump
805
// with, of course, an unknown offset. In these cases we store the offset
806
// in 2 bytes (which will be increased in resizeInstructions, if needed).
807
code.put1(opcode);
808       label.put(this, code, code.length - 1, false);
809     }
810   }
811
812   public void visitLabel (final Label label) {
813     if (CHECK) {
814       if (label.owner == null) {
815         label.owner = this;
816       } else if (label.owner != this) {
817         throw new IllegalArgumentException JavaDoc();
818       }
819     }
820     if (computeMaxs) {
821       if (currentBlock != null) {
822         // ends current block (with one new successor)
823
currentBlock.maxStackSize = maxStackSize;
824         addSuccessor(stackSize, label);
825       }
826       // begins a new current block,
827
// resets the relative current and max stack sizes
828
currentBlock = label;
829       stackSize = 0;
830       maxStackSize = 0;
831     }
832     // resolves previous forward references to label, if any
833
resize |= label.resolve(this, code.length, code.data);
834   }
835
836   public void visitLdcInsn (final Object JavaDoc cst) {
837     Item i = cw.newConst(cst);
838     if (computeMaxs) {
839       int size;
840       // computes the stack size variation
841
if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) {
842         size = stackSize + 2;
843       } else {
844         size = stackSize + 1;
845       }
846       // updates current and max stack sizes
847
if (size > maxStackSize) {
848         maxStackSize = size;
849       }
850       stackSize = size;
851     }
852     // adds the instruction to the bytecode of the method
853
int index = i.index;
854     if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) {
855       code.put12(20 /*LDC2_W*/, index);
856     } else if (index >= 256) {
857       code.put12(19 /*LDC_W*/, index);
858     } else {
859       code.put11(Constants.LDC, index);
860     }
861   }
862
863   public void visitIincInsn (final int var, final int increment) {
864     if (computeMaxs) {
865       // updates max locals only (no stack change)
866
int n = var + 1;
867       if (n > maxLocals) {
868         maxLocals = n;
869       }
870     }
871     // adds the instruction to the bytecode of the method
872
if ((var > 255) || (increment > 127) || (increment < -128)) {
873       code.put1(196 /*WIDE*/).put12(Constants.IINC, var).put2(increment);
874     } else {
875       code.put1(Constants.IINC).put11(var, increment);
876     }
877   }
878
879   public void visitTableSwitchInsn (
880     final int min,
881     final int max,
882     final Label dflt,
883     final Label labels[])
884   {
885     if (computeMaxs) {
886       // updates current stack size (max stack size unchanged)
887
--stackSize;
888       // ends current block (with many new successors)
889
if (currentBlock != null) {
890         currentBlock.maxStackSize = maxStackSize;
891         addSuccessor(stackSize, dflt);
892         for (int i = 0; i < labels.length; ++i) {
893           addSuccessor(stackSize, labels[i]);
894         }
895         currentBlock = null;
896       }
897     }
898     // adds the instruction to the bytecode of the method
899
int source = code.length;
900     code.put1(Constants.TABLESWITCH);
901     while (code.length % 4 != 0) {
902       code.put1(0);
903     }
904     dflt.put(this, code, source, true);
905     code.put4(min).put4(max);
906     for (int i = 0; i < labels.length; ++i) {
907       labels[i].put(this, code, source, true);
908     }
909   }
910
911   public void visitLookupSwitchInsn (
912     final Label dflt,
913     final int keys[],
914     final Label labels[])
915   {
916     if (computeMaxs) {
917       // updates current stack size (max stack size unchanged)
918
--stackSize;
919       // ends current block (with many new successors)
920
if (currentBlock != null) {
921         currentBlock.maxStackSize = maxStackSize;
922         addSuccessor(stackSize, dflt);
923         for (int i = 0; i < labels.length; ++i) {
924           addSuccessor(stackSize, labels[i]);
925         }
926         currentBlock = null;
927       }
928     }
929     // adds the instruction to the bytecode of the method
930
int source = code.length;
931     code.put1(Constants.LOOKUPSWITCH);
932     while (code.length % 4 != 0) {
933       code.put1(0);
934     }
935     dflt.put(this, code, source, true);
936     code.put4(labels.length);
937     for (int i = 0; i < labels.length; ++i) {
938       code.put4(keys[i]);
939       labels[i].put(this, code, source, true);
940     }
941   }
942
943   public void visitMultiANewArrayInsn (final String JavaDoc desc, final int dims) {
944     if (computeMaxs) {
945       // updates current stack size (max stack size unchanged because stack
946
// size variation always negative or null)
947
stackSize += 1 - dims;
948     }
949     // adds the instruction to the bytecode of the method
950
code.put12(Constants.MULTIANEWARRAY, cw.newClass(desc)).put1(dims);
951   }
952
953   public void visitTryCatchBlock (
954     final Label start,
955     final Label end,
956     final Label handler,
957     final String JavaDoc type)
958   {
959     if (CHECK) {
960       if (start.owner != this || end.owner != this || handler.owner != this) {
961         throw new IllegalArgumentException JavaDoc();
962       }
963       if (!start.resolved || !end.resolved || !handler.resolved) {
964         throw new IllegalArgumentException JavaDoc();
965       }
966     }
967     if (computeMaxs) {
968       // pushes handler block onto the stack of blocks to be visited
969
if (!handler.pushed) {
970         handler.beginStackSize = 1;
971         handler.pushed = true;
972         handler.next = blockStack;
973         blockStack = handler;
974       }
975     }
976     ++catchCount;
977     if (catchTable == null) {
978       catchTable = new ByteVector();
979     }
980     catchTable.put2(start.position);
981     catchTable.put2(end.position);
982     catchTable.put2(handler.position);
983     catchTable.put2(type != null ? cw.newClass(type) : 0);
984   }
985
986   public void visitMaxs (final int maxStack, final int maxLocals) {
987     if (computeMaxs) {
988       // true (non relative) max stack size
989
int max = 0;
990       // control flow analysis algorithm: while the block stack is not empty,
991
// pop a block from this stack, update the max stack size, compute
992
// the true (non relative) begin stack size of the successors of this
993
// block, and push these successors onto the stack (unless they have
994
// already been pushed onto the stack). Note: by hypothesis, the {@link
995
// Label#beginStackSize} of the blocks in the block stack are the true
996
// (non relative) beginning stack sizes of these blocks.
997
Label stack = blockStack;
998       while (stack != null) {
999         // pops a block from the stack
1000
Label l = stack;
1001        stack = stack.next;
1002        // computes the true (non relative) max stack size of this block
1003
int start = l.beginStackSize;
1004        int blockMax = start + l.maxStackSize;
1005        // updates the global max stack size
1006
if (blockMax > max) {
1007          max = blockMax;
1008        }
1009        // analyses the successors of the block
1010
Edge b = l.successors;
1011        while (b != null) {
1012          l = b.successor;
1013          // if this successor has not already been pushed onto the stack...
1014
if (!l.pushed) {
1015            // computes the true beginning stack size of this successor block
1016
l.beginStackSize = start + b.stackSize;
1017            // pushes this successor onto the stack
1018
l.pushed = true;
1019            l.next = stack;
1020            stack = l;
1021          }
1022          b = b.next;
1023        }
1024      }
1025      this.maxStack = max;
1026      // releases all the Edge objects used by this CodeWriter
1027
synchronized (SIZE) {
1028        // appends the [head ... tail] list at the beginning of the pool list
1029
if (tail != null) {
1030          tail.poolNext = pool;
1031          pool = head;
1032        }
1033      }
1034    } else {
1035      this.maxStack = maxStack;
1036      this.maxLocals = maxLocals;
1037    }
1038  }
1039
1040  public void visitLocalVariable (
1041    final String JavaDoc name,
1042    final String JavaDoc desc,
1043    final Label start,
1044    final Label end,
1045    final int index)
1046  {
1047    if (CHECK) {
1048      if (start.owner != this || !start.resolved) {
1049        throw new IllegalArgumentException JavaDoc();
1050      }
1051      if (end.owner != this || !end.resolved) {
1052        throw new IllegalArgumentException JavaDoc();
1053      }
1054    }
1055    if (localVar == null) {
1056      cw.newUTF8("LocalVariableTable");
1057      localVar = new ByteVector();
1058    }
1059    ++localVarCount;
1060    localVar.put2(start.position);
1061    localVar.put2(end.position - start.position);
1062    localVar.put2(cw.newUTF8(name));
1063    localVar.put2(cw.newUTF8(desc));
1064    localVar.put2(index);
1065  }
1066
1067  public void visitLineNumber (final int line, final Label start) {
1068    if (CHECK) {
1069      if (start.owner != this || !start.resolved) {
1070        throw new IllegalArgumentException JavaDoc();
1071      }
1072    }
1073    if (lineNumber == null) {
1074      cw.newUTF8("LineNumberTable");
1075      lineNumber = new ByteVector();
1076    }
1077    ++lineNumberCount;
1078    lineNumber.put2(start.position);
1079    lineNumber.put2(line);
1080  }
1081
1082  public void visitAttribute (final Attribute attr) {
1083    attr.next = cattrs;
1084    cattrs = attr;
1085  }
1086
1087  // --------------------------------------------------------------------------
1088
// Utility methods: control flow analysis algorithm
1089
// --------------------------------------------------------------------------
1090

1091  /**
1092   * Computes the size of the arguments and of the return value of a method.
1093   *
1094   * @param desc the descriptor of a method.
1095   * @return the size of the arguments of the method (plus one for the implicit
1096   * this argument), argSize, and the size of its return value, retSize,
1097   * packed into a single int i = <tt>(argSize << 2) | retSize</tt>
1098   * (argSize is therefore equal to <tt>i >> 2</tt>, and retSize to
1099   * <tt>i & 0x03</tt>).
1100   */

1101
1102  private static int getArgumentsAndReturnSizes (final String JavaDoc desc) {
1103    int n = 1;
1104    int c = 1;
1105    while (true) {
1106      char car = desc.charAt(c++);
1107      if (car == ')') {
1108        car = desc.charAt(c);
1109        return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1));
1110      } else if (car == 'L') {
1111        while (desc.charAt(c++) != ';') {
1112        }
1113        n += 1;
1114      } else if (car == '[') {
1115        while ((car = desc.charAt(c)) == '[') {
1116          ++c;
1117        }
1118        if (car == 'D' || car == 'J') {
1119          n -= 1;
1120        }
1121      } else if (car == 'D' || car == 'J') {
1122        n += 2;
1123      } else {
1124        n += 1;
1125      }
1126    }
1127  }
1128
1129  /**
1130   * Adds a successor to the {@link #currentBlock currentBlock} block.
1131   *
1132   * @param stackSize the current (relative) stack size in the current block.
1133   * @param successor the successor block to be added to the current block.
1134   */

1135
1136  private void addSuccessor (final int stackSize, final Label successor) {
1137    Edge b;
1138    // creates a new Edge object or reuses one from the shared pool
1139
synchronized (SIZE) {
1140      if (pool == null) {
1141        b = new Edge();
1142      } else {
1143        b = pool;
1144        // removes b from the pool
1145
pool = pool.poolNext;
1146      }
1147    }
1148    // adds the previous Edge to the list of Edges used by this CodeWriter
1149
if (tail == null) {
1150      tail = b;
1151    }
1152    b.poolNext = head;
1153    head = b;
1154    // initializes the previous Edge object...
1155
b.stackSize = stackSize;
1156    b.successor = successor;
1157    // ...and adds it to the successor list of the currentBlock block
1158
b.next = currentBlock.successors;
1159    currentBlock.successors = b;
1160  }
1161
1162  // --------------------------------------------------------------------------
1163
// Utility methods: dump bytecode array
1164
// --------------------------------------------------------------------------
1165

1166  /**
1167   * Returns the size of the bytecode of this method.
1168   *
1169   * @return the size of the bytecode of this method.
1170   */

1171
1172  final int getSize () {
1173    if (resize) {
1174      // replaces the temporary jump opcodes introduced by Label.resolve.
1175
resizeInstructions(new int[0], new int[0], 0);
1176    }
1177    int size = 8;
1178    if (code.length > 0) {
1179      cw.newUTF8("Code");
1180      size += 18 + code.length + 8 * catchCount;
1181      if (localVar != null) {
1182        size += 8 + localVar.length;
1183      }
1184      if (lineNumber != null) {
1185        size += 8 + lineNumber.length;
1186      }
1187      if (cattrs != null) {
1188        size += cattrs.getSize(cw);
1189      }
1190    }
1191    if (exceptionCount > 0) {
1192      cw.newUTF8("Exceptions");
1193      size += 8 + 2 * exceptionCount;
1194    }
1195    if ((access & Constants.ACC_SYNTHETIC) != 0) {
1196      cw.newUTF8("Synthetic");
1197      size += 6;
1198    }
1199    if ((access & Constants.ACC_DEPRECATED) != 0) {
1200      cw.newUTF8("Deprecated");
1201      size += 6;
1202    }
1203    if (attrs != null) {
1204      size += attrs.getSize(cw);
1205    }
1206    return size;
1207  }
1208
1209  /**
1210   * Puts the bytecode of this method in the given byte vector.
1211   *
1212   * @param out the byte vector into which the bytecode of this method must be
1213   * copied.
1214   */

1215
1216  final void put (final ByteVector out) {
1217    out.put2(access).put2(name).put2(desc);
1218    int attributeCount = 0;
1219    if (code.length > 0) {
1220      ++attributeCount;
1221    }
1222    if (exceptionCount > 0) {
1223      ++attributeCount;
1224    }
1225    if ((access & Constants.ACC_SYNTHETIC) != 0) {
1226      ++attributeCount;
1227    }
1228    if ((access & Constants.ACC_DEPRECATED) != 0) {
1229      ++attributeCount;
1230    }
1231    if (attrs != null) {
1232      attributeCount += attrs.getCount();
1233    }
1234    out.put2(attributeCount);
1235    if (code.length > 0) {
1236      int size = 12 + code.length + 8 * catchCount;
1237      if (localVar != null) {
1238        size += 8 + localVar.length;
1239      }
1240      if (lineNumber != null) {
1241        size += 8 + lineNumber.length;
1242      }
1243      if (cattrs != null) {
1244        size += cattrs.getSize(cw);
1245      }
1246      out.put2(cw.newUTF8("Code")).put4(size);
1247      out.put2(maxStack).put2(maxLocals);
1248      out.put4(code.length).putByteArray(code.data, 0, code.length);
1249      out.put2(catchCount);
1250      if (catchCount > 0) {
1251        out.putByteArray(catchTable.data, 0, catchTable.length);
1252      }
1253      attributeCount = 0;
1254      if (localVar != null) {
1255        ++attributeCount;
1256      }
1257      if (lineNumber != null) {
1258        ++attributeCount;
1259      }
1260      if (cattrs != null) {
1261        attributeCount += cattrs.getCount();
1262      }
1263      out.put2(attributeCount);
1264      if (localVar != null) {
1265        out.put2(cw.newUTF8("LocalVariableTable"));
1266        out.put4(localVar.length + 2).put2(localVarCount);
1267        out.putByteArray(localVar.data, 0, localVar.length);
1268      }
1269      if (lineNumber != null) {
1270        out.put2(cw.newUTF8("LineNumberTable"));
1271        out.put4(lineNumber.length + 2).put2(lineNumberCount);
1272        out.putByteArray(lineNumber.data, 0, lineNumber.length);
1273      }
1274      if (cattrs != null) {
1275        cattrs.put(cw, out);
1276      }
1277    }
1278    if (exceptionCount > 0) {
1279      out.put2(cw.newUTF8("Exceptions")).put4(2 * exceptionCount + 2);
1280      out.put2(exceptionCount);
1281      for (int i = 0; i < exceptionCount; ++i) {
1282        out.put2(exceptions[i]);
1283      }
1284    }
1285    if ((access & Constants.ACC_SYNTHETIC) != 0) {
1286      out.put2(cw.newUTF8("Synthetic")).put4(0);
1287    }
1288    if ((access & Constants.ACC_DEPRECATED) != 0) {
1289      out.put2(cw.newUTF8("Deprecated")).put4(0);
1290    }
1291    if (attrs != null) {
1292      attrs.put(cw, out);
1293    }
1294  }
1295
1296  // --------------------------------------------------------------------------
1297
// Utility methods: instruction resizing (used to handle GOTO_W and JSR_W)
1298
// --------------------------------------------------------------------------
1299

1300  /**
1301   * Resizes the designated instructions, while keeping jump offsets and
1302   * instruction addresses consistent. This may require to resize other existing
1303   * instructions, or even to introduce new instructions: for example,
1304   * increasing the size of an instruction by 2 at the middle of a method can
1305   * increases the offset of an IFEQ instruction from 32766 to 32768, in which
1306   * case IFEQ 32766 must be replaced with IFNEQ 8 GOTO_W 32765. This, in turn,
1307   * may require to increase the size of another jump instruction, and so on...
1308   * All these operations are handled automatically by this method.
1309   * <p>
1310   * <i>This method must be called after all the method that is being built has
1311   * been visited</i>. In particular, the {@link Label Label} objects used to
1312   * construct the method are no longer valid after this method has been called.
1313   *
1314   * @param indexes current positions of the instructions to be resized. Each
1315   * instruction must be designated by the index of its <i>last</i> byte,
1316   * plus one (or, in other words, by the index of the <i>first</i> byte of
1317   * the <i>next</i> instruction).
1318   * @param sizes the number of bytes to be <i>added</i> to the above
1319   * instructions. More precisely, for each i &lt; <tt>len</tt>,
1320   * <tt>sizes</tt>[i] bytes will be added at the end of the instruction
1321   * designated by <tt>indexes</tt>[i] or, if <tt>sizes</tt>[i] is
1322   * negative, the <i>last</i> |<tt>sizes[i]</tt>| bytes of the instruction
1323   * will be removed (the instruction size <i>must not</i> become negative
1324   * or null). The gaps introduced by this method must be filled in
1325   * "manually" in the array returned by the {@link #getCode getCode}
1326   * method.
1327   * @param len the number of instruction to be resized. Must be smaller than or
1328   * equal to <tt>indexes</tt>.length and <tt>sizes</tt>.length.
1329   * @return the <tt>indexes</tt> array, which now contains the new positions of
1330   * the resized instructions (designated as above).
1331   */

1332
1333  protected int[] resizeInstructions (
1334    final int[] indexes,
1335    final int[] sizes,
1336    final int len)
1337  {
1338    byte[] b = code.data; // bytecode of the method
1339
int u, v, label; // indexes in b
1340
int i, j; // loop indexes
1341

1342    // 1st step:
1343
// As explained above, resizing an instruction may require to resize another
1344
// one, which may require to resize yet another one, and so on. The first
1345
// step of the algorithm consists in finding all the instructions that
1346
// need to be resized, without modifying the code. This is done by the
1347
// following "fix point" algorithm:
1348
// - parse the code to find the jump instructions whose offset will need
1349
// more than 2 bytes to be stored (the future offset is computed from the
1350
// current offset and from the number of bytes that will be inserted or
1351
// removed between the source and target instructions). For each such
1352
// instruction, adds an entry in (a copy of) the indexes and sizes arrays
1353
// (if this has not already been done in a previous iteration!)
1354
// - if at least one entry has been added during the previous step, go back
1355
// to the beginning, otherwise stop.
1356
// In fact the real algorithm is complicated by the fact that the size of
1357
// TABLESWITCH and LOOKUPSWITCH instructions depends on their position in
1358
// the bytecode (because of padding). In order to ensure the convergence of
1359
// the algorithm, the number of bytes to be added or removed from these
1360
// instructions is over estimated during the previous loop, and computed
1361
// exactly only after the loop is finished (this requires another pass to
1362
// parse the bytecode of the method).
1363

1364    int[] allIndexes = new int[len]; // copy of indexes
1365
int[] allSizes = new int[len]; // copy of sizes
1366
boolean[] resize; // instructions to be resized
1367
int newOffset; // future offset of a jump instruction
1368

1369    System.arraycopy(indexes, 0, allIndexes, 0, len);
1370    System.arraycopy(sizes, 0, allSizes, 0, len);
1371    resize = new boolean[code.length];
1372
1373    int state = 3; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done
1374
do {
1375      if (state == 3) {
1376        state = 2;
1377      }
1378      u = 0;
1379      while (u < b.length) {
1380        int opcode = b[u] & 0xFF; // opcode of current instruction
1381
int insert = 0; // bytes to be added after this instruction
1382

1383        switch (ClassWriter.TYPE[opcode]) {
1384          case ClassWriter.NOARG_INSN:
1385          case ClassWriter.IMPLVAR_INSN:
1386            u += 1;
1387            break;
1388          case ClassWriter.LABEL_INSN:
1389            if (opcode > 201) {
1390              // converts temporary opcodes 202 to 217 (inclusive), 218 and 219
1391
// to IFEQ ... JSR (inclusive), IFNULL and IFNONNULL
1392
opcode = opcode < 218 ? opcode - 49 : opcode - 20;
1393              label = u + readUnsignedShort(b, u + 1);
1394            } else {
1395              label = u + readShort(b, u + 1);
1396            }
1397            newOffset = getNewOffset(allIndexes, allSizes, u, label);
1398            if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) {
1399              if (!resize[u]) {
1400                if (opcode == Constants.GOTO || opcode == Constants.JSR) {
1401                  // two additional bytes will be required to replace this
1402
// GOTO or JSR instruction with a GOTO_W or a JSR_W
1403
insert = 2;
1404                } else {
1405                  // five additional bytes will be required to replace this
1406
// IFxxx <l> instruction with IFNOTxxx <l'> GOTO_W <l>, where
1407
// IFNOTxxx is the "opposite" opcode of IFxxx (i.e., IFNE for
1408
// IFEQ) and where <l'> designates the instruction just after
1409
// the GOTO_W.
1410
insert = 5;
1411                }
1412                resize[u] = true;
1413              }
1414            }
1415            u += 3;
1416            break;
1417          case ClassWriter.LABELW_INSN:
1418            u += 5;
1419            break;
1420          case ClassWriter.TABL_INSN:
1421            if (state == 1) {
1422              // true number of bytes to be added (or removed) from this
1423
// instruction = (future number of padding bytes - current number
1424
// of padding byte) - previously over estimated variation =
1425
// = ((3 - newOffset%4) - (3 - u%4)) - u%4
1426
// = (-newOffset%4 + u%4) - u%4
1427
// = -(newOffset & 3)
1428
newOffset = getNewOffset(allIndexes, allSizes, 0, u);
1429              insert = -(newOffset & 3);
1430            } else if (!resize[u]) {
1431              // over estimation of the number of bytes to be added to this
1432
// instruction = 3 - current number of padding bytes = 3 - (3 -
1433
// u%4) = u%4 = u & 3
1434
insert = u & 3;
1435              resize[u] = true;
1436            }
1437            // skips instruction
1438
u = u + 4 - (u & 3);
1439            u += 4*(readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12;
1440            break;
1441          case ClassWriter.LOOK_INSN:
1442            if (state == 1) {
1443              // like TABL_INSN
1444
newOffset = getNewOffset(allIndexes, allSizes, 0, u);
1445              insert = -(newOffset & 3);
1446            } else if (!resize[u]) {
1447              // like TABL_INSN
1448
insert = u & 3;
1449              resize[u] = true;
1450            }
1451            // skips instruction
1452
u = u + 4 - (u & 3);
1453            u += 8*readInt(b, u + 4) + 8;
1454            break;
1455          case ClassWriter.WIDE_INSN:
1456            opcode = b[u + 1] & 0xFF;
1457            if (opcode == Constants.IINC) {
1458              u += 6;
1459            } else {
1460              u += 4;
1461            }
1462            break;
1463          case ClassWriter.VAR_INSN:
1464          case ClassWriter.SBYTE_INSN:
1465          case ClassWriter.LDC_INSN:
1466            u += 2;
1467            break;
1468          case ClassWriter.SHORT_INSN:
1469          case ClassWriter.LDCW_INSN:
1470          case ClassWriter.FIELDORMETH_INSN:
1471          case ClassWriter.TYPE_INSN:
1472          case ClassWriter.IINC_INSN:
1473            u += 3;
1474            break;
1475          case ClassWriter.ITFMETH_INSN:
1476            u += 5;
1477            break;
1478          // case ClassWriter.MANA_INSN:
1479
default:
1480            u += 4;
1481            break;
1482        }
1483        if (insert != 0) {
1484          // adds a new (u, insert) entry in the allIndexes and allSizes arrays
1485
int[] newIndexes = new int[allIndexes.length + 1];
1486          int[] newSizes = new int[allSizes.length + 1];
1487          System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length);
1488          System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length);
1489          newIndexes[allIndexes.length] = u;
1490          newSizes[allSizes.length] = insert;
1491          allIndexes = newIndexes;
1492          allSizes = newSizes;
1493          if (insert > 0) {
1494            state = 3;
1495          }
1496        }
1497      }
1498      if (state < 3) {
1499        --state;
1500      }
1501    } while (state != 0);
1502
1503    // 2nd step:
1504
// copies the bytecode of the method into a new bytevector, updates the
1505
// offsets, and inserts (or removes) bytes as requested.
1506

1507    ByteVector newCode = new ByteVector(code.length);
1508
1509    u = 0;
1510    while (u < code.length) {
1511      for (i = allIndexes.length - 1; i >= 0; --i) {
1512        if (allIndexes[i] == u) {
1513          if (i < len) {
1514            if (sizes[i] > 0) {
1515              newCode.putByteArray(null, 0, sizes[i]);
1516            } else {
1517              newCode.length += sizes[i];
1518            }
1519            indexes[i] = newCode.length;
1520          }
1521        }
1522      }
1523      int opcode = b[u] & 0xFF;
1524      switch (ClassWriter.TYPE[opcode]) {
1525        case ClassWriter.NOARG_INSN:
1526        case ClassWriter.IMPLVAR_INSN:
1527          newCode.put1(opcode);
1528          u += 1;
1529          break;
1530        case ClassWriter.LABEL_INSN:
1531          if (opcode > 201) {
1532            // changes temporary opcodes 202 to 217 (inclusive), 218 and 219
1533
// to IFEQ ... JSR (inclusive), IFNULL and IFNONNULL
1534
opcode = opcode < 218 ? opcode - 49 : opcode - 20;
1535            label = u + readUnsignedShort(b, u + 1);
1536          } else {
1537            label = u + readShort(b, u + 1);
1538          }
1539          newOffset = getNewOffset(allIndexes, allSizes, u, label);
1540          if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) {
1541            // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx <l> with
1542
// IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is the "opposite" opcode
1543
// of IFxxx (i.e., IFNE for IFEQ) and where <l'> designates the
1544
// instruction just after the GOTO_W.
1545
if (opcode == Constants.GOTO) {
1546              newCode.put1(200); // GOTO_W
1547
} else if (opcode == Constants.JSR) {
1548              newCode.put1(201); // JSR_W
1549
} else {
1550              newCode.put1(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1);
1551              newCode.put2(8); // jump offset
1552
newCode.put1(200); // GOTO_W
1553
newOffset -= 3; // newOffset now computed from start of GOTO_W
1554
}
1555            newCode.put4(newOffset);
1556          } else {
1557            newCode.put1(opcode);
1558            newCode.put2(newOffset);
1559          }
1560          u += 3;
1561          break;
1562        case ClassWriter.LABELW_INSN:
1563          label = u + readInt(b, u + 1);
1564          newOffset = getNewOffset(allIndexes, allSizes, u, label);
1565          newCode.put1(opcode);
1566          newCode.put4(newOffset);
1567          u += 5;
1568          break;
1569        case ClassWriter.TABL_INSN:
1570          // skips 0 to 3 padding bytes
1571
v = u;
1572          u = u + 4 - (v & 3);
1573          // reads and copies instruction
1574
int source = newCode.length;
1575          newCode.put1(Constants.TABLESWITCH);
1576          while (newCode.length % 4 != 0) {
1577            newCode.put1(0);
1578          }
1579          label = v + readInt(b, u); u += 4;
1580          newOffset = getNewOffset(allIndexes, allSizes, v, label);
1581          newCode.put4(newOffset);
1582          j = readInt(b, u); u += 4;
1583          newCode.put4(j);
1584          j = readInt(b, u) - j + 1; u += 4;
1585          newCode.put4(readInt(b, u - 4));
1586          for ( ; j > 0; --j) {
1587            label = v + readInt(b, u); u += 4;
1588            newOffset = getNewOffset(allIndexes, allSizes, v, label);
1589            newCode.put4(newOffset);
1590          }
1591          break;
1592        case ClassWriter.LOOK_INSN:
1593          // skips 0 to 3 padding bytes
1594
v = u;
1595          u = u + 4 - (v & 3);
1596          // reads and copies instruction
1597
source = newCode.length;
1598          newCode.put1(Constants.LOOKUPSWITCH);
1599          while (newCode.length % 4 != 0) {
1600            newCode.put1(0);
1601          }
1602          label = v + readInt(b, u); u += 4;
1603          newOffset = getNewOffset(allIndexes, allSizes, v, label);
1604          newCode.put4(newOffset);
1605          j = readInt(b, u); u += 4;
1606          newCode.put4(j);
1607          for ( ; j > 0; --j) {
1608            newCode.put4(readInt(b, u)); u += 4;
1609            label = v + readInt(b, u); u += 4;
1610            newOffset = getNewOffset(allIndexes, allSizes, v, label);
1611            newCode.put4(newOffset);
1612          }
1613          break;
1614        case ClassWriter.WIDE_INSN:
1615          opcode = b[u + 1] & 0xFF;
1616          if (opcode == Constants.IINC) {
1617            newCode.putByteArray(b, u, 6);
1618            u += 6;
1619          } else {
1620            newCode.putByteArray(b, u, 4);
1621            u += 4;
1622          }
1623          break;
1624        case ClassWriter.VAR_INSN:
1625        case ClassWriter.SBYTE_INSN:
1626        case ClassWriter.LDC_INSN:
1627          newCode.putByteArray(b, u, 2);
1628          u += 2;
1629          break;
1630        case ClassWriter.SHORT_INSN:
1631        case ClassWriter.LDCW_INSN:
1632        case ClassWriter.FIELDORMETH_INSN:
1633        case ClassWriter.TYPE_INSN:
1634        case ClassWriter.IINC_INSN:
1635          newCode.putByteArray(b, u, 3);
1636          u += 3;
1637          break;
1638        case ClassWriter.ITFMETH_INSN:
1639          newCode.putByteArray(b, u, 5);
1640          u += 5;
1641          break;
1642        // case MANA_INSN:
1643
default:
1644          newCode.putByteArray(b, u, 4);
1645          u += 4;
1646          break;
1647      }
1648    }
1649
1650    // updates the instructions addresses in the
1651
// catch, local var and line number tables
1652
if (catchTable != null) {
1653      b = catchTable.data;
1654      u = 0;
1655      while (u < catchTable.length) {
1656        writeShort(b, u, getNewOffset(
1657          allIndexes, allSizes, 0, readUnsignedShort(b, u)));
1658        writeShort(b, u + 2, getNewOffset(
1659          allIndexes, allSizes, 0, readUnsignedShort(b, u + 2)));
1660        writeShort(b, u + 4, getNewOffset(
1661          allIndexes, allSizes, 0, readUnsignedShort(b, u + 4)));
1662        u += 8;
1663      }
1664    }
1665    if (localVar != null) {
1666      b = localVar.data;
1667      u = 0;
1668      while (u < localVar.length) {
1669        label = readUnsignedShort(b, u);
1670        newOffset = getNewOffset(allIndexes, allSizes, 0, label);
1671        writeShort(b, u, newOffset);
1672        label += readUnsignedShort(b, u + 2);
1673        newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset;
1674        writeShort(b, u, newOffset);
1675        u += 10;
1676      }
1677    }
1678    if (lineNumber != null) {
1679      b = lineNumber.data;
1680      u = 0;
1681      while (u < lineNumber.length) {
1682        writeShort(b, u, getNewOffset(
1683          allIndexes, allSizes, 0, readUnsignedShort(b, u)));
1684        u += 4;
1685      }
1686    }
1687
1688    // replaces old bytecodes with new ones
1689
code = newCode;
1690
1691    // returns the positions of the resized instructions
1692
return indexes;
1693  }
1694
1695  /**
1696   * Reads an unsigned short value in the given byte array.
1697   *
1698   * @param b a byte array.
1699   * @param index the start index of the value to be read.
1700   * @return the read value.
1701   */

1702
1703  static int readUnsignedShort (final byte[] b, final int index) {
1704    return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF);
1705  }
1706
1707  /**
1708   * Reads a signed short value in the given byte array.
1709   *
1710   * @param b a byte array.
1711   * @param index the start index of the value to be read.
1712   * @return the read value.
1713   */

1714
1715  static short readShort (final byte[] b, final int index) {
1716    return (short)(((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF));
1717  }
1718
1719  /**
1720   * Reads a signed int value in the given byte array.
1721   *
1722   * @param b a byte array.
1723   * @param index the start index of the value to be read.
1724   * @return the read value.
1725   */

1726
1727  static int readInt (final byte[] b, final int index) {
1728    return ((b[index] & 0xFF) << 24) |
1729           ((b[index + 1] & 0xFF) << 16) |
1730           ((b[index + 2] & 0xFF) << 8) |
1731           (b[index + 3] & 0xFF);
1732  }
1733
1734  /**
1735   * Writes a short value in the given byte array.
1736   *
1737   * @param b a byte array.
1738   * @param index where the first byte of the short value must be written.
1739   * @param s the value to be written in the given byte array.
1740   */

1741
1742  static void writeShort (final byte[] b, final int index, final int s) {
1743    b[index] = (byte)(s >>> 8);
1744    b[index + 1] = (byte)s;
1745  }
1746
1747  /**
1748   * Computes the future value of a bytecode offset.
1749   * <p>
1750   * Note: it is possible to have several entries for the same instruction
1751   * in the <tt>indexes</tt> and <tt>sizes</tt>: two entries (index=a,size=b)
1752   * and (index=a,size=b') are equivalent to a single entry (index=a,size=b+b').
1753   *
1754   * @param indexes current positions of the instructions to be resized. Each
1755   * instruction must be designated by the index of its <i>last</i> byte,
1756   * plus one (or, in other words, by the index of the <i>first</i> byte of
1757   * the <i>next</i> instruction).
1758   * @param sizes the number of bytes to be <i>added</i> to the above
1759   * instructions. More precisely, for each i < <tt>len</tt>,
1760   * <tt>sizes</tt>[i] bytes will be added at the end of the instruction
1761   * designated by <tt>indexes</tt>[i] or, if <tt>sizes</tt>[i] is
1762   * negative, the <i>last</i> |<tt>sizes[i]</tt>| bytes of the instruction
1763   * will be removed (the instruction size <i>must not</i> become negative
1764   * or null).
1765   * @param begin index of the first byte of the source instruction.
1766   * @param end index of the first byte of the target instruction.
1767   * @return the future value of the given bytecode offset.
1768   */

1769
1770  static int getNewOffset (
1771    final int[] indexes,
1772    final int[] sizes,
1773    final int begin,
1774    final int end)
1775  {
1776    int offset = end - begin;
1777    for (int i = 0; i < indexes.length; ++i) {
1778      if (begin < indexes[i] && indexes[i] <= end) { // forward jump
1779
offset += sizes[i];
1780      } else if (end < indexes[i] && indexes[i] <= begin) { // backward jump
1781
offset -= sizes[i];
1782      }
1783    }
1784    return offset;
1785  }
1786
1787  /**
1788   * Returns the current size of the bytecode of this method. This size just
1789   * includes the size of the bytecode instructions: it does not include the
1790   * size of the Exceptions, LocalVariableTable, LineNumberTable, Synthetic
1791   * and Deprecated attributes, if present.
1792   *
1793   * @return the current size of the bytecode of this method.
1794   */

1795
1796  protected int getCodeSize () {
1797    return code.length;
1798  }
1799
1800  /**
1801   * Returns the current bytecode of this method. This bytecode only contains
1802   * the instructions: it does not include the Exceptions, LocalVariableTable,
1803   * LineNumberTable, Synthetic and Deprecated attributes, if present.
1804   *
1805   * @return the current bytecode of this method. The bytecode is contained
1806   * between the index 0 (inclusive) and the index {@link #getCodeSize
1807   * getCodeSize} (exclusive).
1808   */

1809
1810  protected byte[] getCode () {
1811    return code.data;
1812  }
1813}
1814
Popular Tags