1/*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation.  Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25/*
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
29 * file:
30 *
31 * ASM: a very small and fast Java bytecode manipulation framework
32 * Copyright (c) 2000-2011 INRIA, France Telecom
33 * All rights reserved.
34 *
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
37 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 *    notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 *    notice, this list of conditions and the following disclaimer in the
42 *    documentation and/or other materials provided with the distribution.
43 * 3. Neither the name of the copyright holders nor the names of its
44 *    contributors may be used to endorse or promote products derived from
45 *    this software without specific prior written permission.
46 *
47 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
48 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
51 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
52 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
53 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
54 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
55 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
56 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
57 * THE POSSIBILITY OF SUCH DAMAGE.
58 */
59package jdk.internal.org.objectweb.asm;
60
61/**
62 * A {@link ClassVisitor} that generates classes in bytecode form. More
63 * precisely this visitor generates a byte array conforming to the Java class
64 * file format. It can be used alone, to generate a Java class "from scratch",
65 * or with one or more {@link ClassReader ClassReader} and adapter class visitor
66 * to generate a modified class from one or more existing Java classes.
67 *
68 * @author Eric Bruneton
69 */
70public class ClassWriter extends ClassVisitor {
71
72    /**
73     * Flag to automatically compute the maximum stack size and the maximum
74     * number of local variables of methods. If this flag is set, then the
75     * arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method of the
76     * {@link MethodVisitor} returned by the {@link #visitMethod visitMethod}
77     * method will be ignored, and computed automatically from the signature and
78     * the bytecode of each method.
79     *
80     * @see #ClassWriter(int)
81     */
82    public static final int COMPUTE_MAXS = 1;
83
84    /**
85     * Flag to automatically compute the stack map frames of methods from
86     * scratch. If this flag is set, then the calls to the
87     * {@link MethodVisitor#visitFrame} method are ignored, and the stack map
88     * frames are recomputed from the methods bytecode. The arguments of the
89     * {@link MethodVisitor#visitMaxs visitMaxs} method are also ignored and
90     * recomputed from the bytecode. In other words, computeFrames implies
91     * computeMaxs.
92     *
93     * @see #ClassWriter(int)
94     */
95    public static final int COMPUTE_FRAMES = 2;
96
97    /**
98     * Pseudo access flag to distinguish between the synthetic attribute and the
99     * synthetic access flag.
100     */
101    static final int ACC_SYNTHETIC_ATTRIBUTE = 0x40000;
102
103    /**
104     * Factor to convert from ACC_SYNTHETIC_ATTRIBUTE to Opcode.ACC_SYNTHETIC.
105     */
106    static final int TO_ACC_SYNTHETIC = ACC_SYNTHETIC_ATTRIBUTE
107            / Opcodes.ACC_SYNTHETIC;
108
109    /**
110     * The type of instructions without any argument.
111     */
112    static final int NOARG_INSN = 0;
113
114    /**
115     * The type of instructions with an signed byte argument.
116     */
117    static final int SBYTE_INSN = 1;
118
119    /**
120     * The type of instructions with an signed short argument.
121     */
122    static final int SHORT_INSN = 2;
123
124    /**
125     * The type of instructions with a local variable index argument.
126     */
127    static final int VAR_INSN = 3;
128
129    /**
130     * The type of instructions with an implicit local variable index argument.
131     */
132    static final int IMPLVAR_INSN = 4;
133
134    /**
135     * The type of instructions with a type descriptor argument.
136     */
137    static final int TYPE_INSN = 5;
138
139    /**
140     * The type of field and method invocations instructions.
141     */
142    static final int FIELDORMETH_INSN = 6;
143
144    /**
145     * The type of the INVOKEINTERFACE/INVOKEDYNAMIC instruction.
146     */
147    static final int ITFMETH_INSN = 7;
148
149    /**
150     * The type of the INVOKEDYNAMIC instruction.
151     */
152    static final int INDYMETH_INSN = 8;
153
154    /**
155     * The type of instructions with a 2 bytes bytecode offset label.
156     */
157    static final int LABEL_INSN = 9;
158
159    /**
160     * The type of instructions with a 4 bytes bytecode offset label.
161     */
162    static final int LABELW_INSN = 10;
163
164    /**
165     * The type of the LDC instruction.
166     */
167    static final int LDC_INSN = 11;
168
169    /**
170     * The type of the LDC_W and LDC2_W instructions.
171     */
172    static final int LDCW_INSN = 12;
173
174    /**
175     * The type of the IINC instruction.
176     */
177    static final int IINC_INSN = 13;
178
179    /**
180     * The type of the TABLESWITCH instruction.
181     */
182    static final int TABL_INSN = 14;
183
184    /**
185     * The type of the LOOKUPSWITCH instruction.
186     */
187    static final int LOOK_INSN = 15;
188
189    /**
190     * The type of the MULTIANEWARRAY instruction.
191     */
192    static final int MANA_INSN = 16;
193
194    /**
195     * The type of the WIDE instruction.
196     */
197    static final int WIDE_INSN = 17;
198
199    /**
200     * The instruction types of all JVM opcodes.
201     */
202    static final byte[] TYPE;
203
204    /**
205     * The type of CONSTANT_Class constant pool items.
206     */
207    static final int CLASS = 7;
208
209    /**
210     * The type of CONSTANT_Fieldref constant pool items.
211     */
212    static final int FIELD = 9;
213
214    /**
215     * The type of CONSTANT_Methodref constant pool items.
216     */
217    static final int METH = 10;
218
219    /**
220     * The type of CONSTANT_InterfaceMethodref constant pool items.
221     */
222    static final int IMETH = 11;
223
224    /**
225     * The type of CONSTANT_String constant pool items.
226     */
227    static final int STR = 8;
228
229    /**
230     * The type of CONSTANT_Integer constant pool items.
231     */
232    static final int INT = 3;
233
234    /**
235     * The type of CONSTANT_Float constant pool items.
236     */
237    static final int FLOAT = 4;
238
239    /**
240     * The type of CONSTANT_Long constant pool items.
241     */
242    static final int LONG = 5;
243
244    /**
245     * The type of CONSTANT_Double constant pool items.
246     */
247    static final int DOUBLE = 6;
248
249    /**
250     * The type of CONSTANT_NameAndType constant pool items.
251     */
252    static final int NAME_TYPE = 12;
253
254    /**
255     * The type of CONSTANT_Utf8 constant pool items.
256     */
257    static final int UTF8 = 1;
258
259    /**
260     * The type of CONSTANT_MethodType constant pool items.
261     */
262    static final int MTYPE = 16;
263
264    /**
265     * The type of CONSTANT_MethodHandle constant pool items.
266     */
267    static final int HANDLE = 15;
268
269    /**
270     * The type of CONSTANT_InvokeDynamic constant pool items.
271     */
272    static final int INDY = 18;
273
274    /**
275     * The type of CONSTANT_Module constant pool items.
276     */
277    static final int MODULE = 19;
278
279    /**
280     * The type of CONSTANT_Package constant pool items.
281     */
282    static final int PACKAGE = 20;
283
284    /**
285     * The base value for all CONSTANT_MethodHandle constant pool items.
286     * Internally, ASM store the 9 variations of CONSTANT_MethodHandle into 9
287     * different items.
288     */
289    static final int HANDLE_BASE = 20;
290
291    /**
292     * Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable},
293     * instead of the constant pool, in order to avoid clashes with normal
294     * constant pool items in the ClassWriter constant pool's hash table.
295     */
296    static final int TYPE_NORMAL = 30;
297
298    /**
299     * Uninitialized type Item stored in the ClassWriter
300     * {@link ClassWriter#typeTable}, instead of the constant pool, in order to
301     * avoid clashes with normal constant pool items in the ClassWriter constant
302     * pool's hash table.
303     */
304    static final int TYPE_UNINIT = 31;
305
306    /**
307     * Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable},
308     * instead of the constant pool, in order to avoid clashes with normal
309     * constant pool items in the ClassWriter constant pool's hash table.
310     */
311    static final int TYPE_MERGED = 32;
312
313    /**
314     * The type of BootstrapMethods items. These items are stored in a special
315     * class attribute named BootstrapMethods and not in the constant pool.
316     */
317    static final int BSM = 33;
318
319    /**
320     * The class reader from which this class writer was constructed, if any.
321     */
322    ClassReader cr;
323
324    /**
325     * Minor and major version numbers of the class to be generated.
326     */
327    int version;
328
329    /**
330     * Index of the next item to be added in the constant pool.
331     */
332    int index;
333
334    /**
335     * The constant pool of this class.
336     */
337    final ByteVector pool;
338
339    /**
340     * The constant pool's hash table data.
341     */
342    Item[] items;
343
344    /**
345     * The threshold of the constant pool's hash table.
346     */
347    int threshold;
348
349    /**
350     * A reusable key used to look for items in the {@link #items} hash table.
351     */
352    final Item key;
353
354    /**
355     * A reusable key used to look for items in the {@link #items} hash table.
356     */
357    final Item key2;
358
359    /**
360     * A reusable key used to look for items in the {@link #items} hash table.
361     */
362    final Item key3;
363
364    /**
365     * A reusable key used to look for items in the {@link #items} hash table.
366     */
367    final Item key4;
368
369    /**
370     * A type table used to temporarily store internal names that will not
371     * necessarily be stored in the constant pool. This type table is used by
372     * the control flow and data flow analysis algorithm used to compute stack
373     * map frames from scratch. This array associates to each index <tt>i</tt>
374     * the Item whose index is <tt>i</tt>. All Item objects stored in this array
375     * are also stored in the {@link #items} hash table. These two arrays allow
376     * to retrieve an Item from its index or, conversely, to get the index of an
377     * Item from its value. Each Item stores an internal name in its
378     * {@link Item#strVal1} field.
379     */
380    Item[] typeTable;
381
382    /**
383     * Number of elements in the {@link #typeTable} array.
384     */
385    private short typeCount;
386
387    /**
388     * The access flags of this class.
389     */
390    private int access;
391
392    /**
393     * The constant pool item that contains the internal name of this class.
394     */
395    private int name;
396
397    /**
398     * The internal name of this class.
399     */
400    String thisName;
401
402    /**
403     * The constant pool item that contains the signature of this class.
404     */
405    private int signature;
406
407    /**
408     * The constant pool item that contains the internal name of the super class
409     * of this class.
410     */
411    private int superName;
412
413    /**
414     * Number of interfaces implemented or extended by this class or interface.
415     */
416    private int interfaceCount;
417
418    /**
419     * The interfaces implemented or extended by this class or interface. More
420     * precisely, this array contains the indexes of the constant pool items
421     * that contain the internal names of these interfaces.
422     */
423    private int[] interfaces;
424
425    /**
426     * The index of the constant pool item that contains the name of the source
427     * file from which this class was compiled.
428     */
429    private int sourceFile;
430
431    /**
432     * The SourceDebug attribute of this class.
433     */
434    private ByteVector sourceDebug;
435
436    /**
437     * The constant pool item that contains the name of the enclosing class of
438     * this class.
439     */
440    private int enclosingMethodOwner;
441
442    /**
443     * The constant pool item that contains the name and descriptor of the
444     * enclosing method of this class.
445     */
446    private int enclosingMethod;
447
448    /**
449     * The runtime visible annotations of this class.
450     */
451    private AnnotationWriter anns;
452
453    /**
454     * The runtime invisible annotations of this class.
455     */
456    private AnnotationWriter ianns;
457
458    /**
459     * The runtime visible type annotations of this class.
460     */
461    private AnnotationWriter tanns;
462
463    /**
464     * The runtime invisible type annotations of this class.
465     */
466    private AnnotationWriter itanns;
467
468    /**
469     * The non standard attributes of this class.
470     */
471    private Attribute attrs;
472
473    /**
474     * The number of entries in the InnerClasses attribute.
475     */
476    private int innerClassesCount;
477
478    /**
479     * The InnerClasses attribute.
480     */
481    private ByteVector innerClasses;
482
483    /**
484     * The number of entries in the BootstrapMethods attribute.
485     */
486    int bootstrapMethodsCount;
487
488    /**
489     * The BootstrapMethods attribute.
490     */
491    ByteVector bootstrapMethods;
492
493    /**
494     * The fields of this class. These fields are stored in a linked list of
495     * {@link FieldWriter} objects, linked to each other by their
496     * {@link FieldWriter#fv} field. This field stores the first element of this
497     * list.
498     */
499    FieldWriter firstField;
500
501    /**
502     * The fields of this class. These fields are stored in a linked list of
503     * {@link FieldWriter} objects, linked to each other by their
504     * {@link FieldWriter#fv} field. This field stores the last element of this
505     * list.
506     */
507    FieldWriter lastField;
508
509    /**
510     * The methods of this class. These methods are stored in a linked list of
511     * {@link MethodWriter} objects, linked to each other by their
512     * {@link MethodWriter#mv} field. This field stores the first element of
513     * this list.
514     */
515    MethodWriter firstMethod;
516
517    /**
518     * The methods of this class. These methods are stored in a linked list of
519     * {@link MethodWriter} objects, linked to each other by their
520     * {@link MethodWriter#mv} field. This field stores the last element of this
521     * list.
522     */
523    MethodWriter lastMethod;
524
525    /**
526     * <tt>true</tt> if the maximum stack size and number of local variables
527     * must be automatically computed.
528     */
529    private boolean computeMaxs;
530
531    /**
532     * <tt>true</tt> if the stack map frames must be recomputed from scratch.
533     */
534    private boolean computeFrames;
535
536    /**
537     * <tt>true</tt> if the stack map tables of this class are invalid. The
538     * {@link MethodWriter#resizeInstructions} method cannot transform existing
539     * stack map tables, and so produces potentially invalid classes when it is
540     * executed. In this case the class is reread and rewritten with the
541     * {@link #COMPUTE_FRAMES} option (the resizeInstructions method can resize
542     * stack map tables when this option is used).
543     */
544    boolean invalidFrames;
545
546    // ------------------------------------------------------------------------
547    // Static initializer
548    // ------------------------------------------------------------------------
549
550    /**
551     * Computes the instruction types of JVM opcodes.
552     */
553    static {
554        int i;
555        byte[] b = new byte[220];
556        String s = "AAAAAAAAAAAAAAAABCLMMDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD"
557                + "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
558                + "AAAAAAAAAAAAAAAAANAAAAAAAAAAAAAAAAAAAAJJJJJJJJJJJJJJJJDOPAA"
559                + "AAAAGGGGGGGHIFBFAAFFAARQJJKKJJJJJJJJJJJJJJJJJJ";
560        for (i = 0; i < b.length; ++i) {
561            b[i] = (byte) (s.charAt(i) - 'A');
562        }
563        TYPE = b;
564
565        // code to generate the above string
566        //
567        // // SBYTE_INSN instructions
568        // b[Constants.NEWARRAY] = SBYTE_INSN;
569        // b[Constants.BIPUSH] = SBYTE_INSN;
570        //
571        // // SHORT_INSN instructions
572        // b[Constants.SIPUSH] = SHORT_INSN;
573        //
574        // // (IMPL)VAR_INSN instructions
575        // b[Constants.RET] = VAR_INSN;
576        // for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) {
577        // b[i] = VAR_INSN;
578        // }
579        // for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) {
580        // b[i] = VAR_INSN;
581        // }
582        // for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3
583        // b[i] = IMPLVAR_INSN;
584        // }
585        // for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3
586        // b[i] = IMPLVAR_INSN;
587        // }
588        //
589        // // TYPE_INSN instructions
590        // b[Constants.NEW] = TYPE_INSN;
591        // b[Constants.ANEWARRAY] = TYPE_INSN;
592        // b[Constants.CHECKCAST] = TYPE_INSN;
593        // b[Constants.INSTANCEOF] = TYPE_INSN;
594        //
595        // // (Set)FIELDORMETH_INSN instructions
596        // for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) {
597        // b[i] = FIELDORMETH_INSN;
598        // }
599        // b[Constants.INVOKEINTERFACE] = ITFMETH_INSN;
600        // b[Constants.INVOKEDYNAMIC] = INDYMETH_INSN;
601        //
602        // // LABEL(W)_INSN instructions
603        // for (i = Constants.IFEQ; i <= Constants.JSR; ++i) {
604        // b[i] = LABEL_INSN;
605        // }
606        // b[Constants.IFNULL] = LABEL_INSN;
607        // b[Constants.IFNONNULL] = LABEL_INSN;
608        // b[200] = LABELW_INSN; // GOTO_W
609        // b[201] = LABELW_INSN; // JSR_W
610        // // temporary opcodes used internally by ASM - see Label and
611        // MethodWriter
612        // for (i = 202; i < 220; ++i) {
613        // b[i] = LABEL_INSN;
614        // }
615        //
616        // // LDC(_W) instructions
617        // b[Constants.LDC] = LDC_INSN;
618        // b[19] = LDCW_INSN; // LDC_W
619        // b[20] = LDCW_INSN; // LDC2_W
620        //
621        // // special instructions
622        // b[Constants.IINC] = IINC_INSN;
623        // b[Constants.TABLESWITCH] = TABL_INSN;
624        // b[Constants.LOOKUPSWITCH] = LOOK_INSN;
625        // b[Constants.MULTIANEWARRAY] = MANA_INSN;
626        // b[196] = WIDE_INSN; // WIDE
627        //
628        // for (i = 0; i < b.length; ++i) {
629        // System.err.print((char)('A' + b[i]));
630        // }
631        // System.err.println();
632    }
633
634    // ------------------------------------------------------------------------
635    // Constructor
636    // ------------------------------------------------------------------------
637
638    /**
639     * Constructs a new {@link ClassWriter} object.
640     *
641     * @param flags
642     *            option flags that can be used to modify the default behavior
643     *            of this class. See {@link #COMPUTE_MAXS},
644     *            {@link #COMPUTE_FRAMES}.
645     */
646    public ClassWriter(final int flags) {
647        super(Opcodes.ASM5);
648        index = 1;
649        pool = new ByteVector();
650        items = new Item[256];
651        threshold = (int) (0.75d * items.length);
652        key = new Item();
653        key2 = new Item();
654        key3 = new Item();
655        key4 = new Item();
656        this.computeMaxs = (flags & COMPUTE_MAXS) != 0;
657        this.computeFrames = (flags & COMPUTE_FRAMES) != 0;
658    }
659
660    /**
661     * Constructs a new {@link ClassWriter} object and enables optimizations for
662     * "mostly add" bytecode transformations. These optimizations are the
663     * following:
664     *
665     * <ul>
666     * <li>The constant pool from the original class is copied as is in the new
667     * class, which saves time. New constant pool entries will be added at the
668     * end if necessary, but unused constant pool entries <i>won't be
669     * removed</i>.</li>
670     * <li>Methods that are not transformed are copied as is in the new class,
671     * directly from the original class bytecode (i.e. without emitting visit
672     * events for all the method instructions), which saves a <i>lot</i> of
673     * time. Untransformed methods are detected by the fact that the
674     * {@link ClassReader} receives {@link MethodVisitor} objects that come from
675     * a {@link ClassWriter} (and not from any other {@link ClassVisitor}
676     * instance).</li>
677     * </ul>
678     *
679     * @param classReader
680     *            the {@link ClassReader} used to read the original class. It
681     *            will be used to copy the entire constant pool from the
682     *            original class and also to copy other fragments of original
683     *            bytecode where applicable.
684     * @param flags
685     *            option flags that can be used to modify the default behavior
686     *            of this class. <i>These option flags do not affect methods
687     *            that are copied as is in the new class. This means that the
688     *            maximum stack size nor the stack frames will be computed for
689     *            these methods</i>. See {@link #COMPUTE_MAXS},
690     *            {@link #COMPUTE_FRAMES}.
691     */
692    public ClassWriter(final ClassReader classReader, final int flags) {
693        this(flags);
694        classReader.copyPool(this);
695        this.cr = classReader;
696    }
697
698    // ------------------------------------------------------------------------
699    // Implementation of the ClassVisitor abstract class
700    // ------------------------------------------------------------------------
701
702    @Override
703    public final void visit(final int version, final int access,
704            final String name, final String signature, final String superName,
705            final String[] interfaces) {
706        this.version = version;
707        this.access = access;
708        this.name = (name == null) ? 0 : newClass(name);
709        thisName = name;
710        if (ClassReader.SIGNATURES && signature != null) {
711            this.signature = newUTF8(signature);
712        }
713        this.superName = superName == null ? 0 : newClass(superName);
714        if (interfaces != null && interfaces.length > 0) {
715            interfaceCount = interfaces.length;
716            this.interfaces = new int[interfaceCount];
717            for (int i = 0; i < interfaceCount; ++i) {
718                this.interfaces[i] = newClass(interfaces[i]);
719            }
720        }
721    }
722
723    @Override
724    public final void visitSource(final String file, final String debug) {
725        if (file != null) {
726            sourceFile = newUTF8(file);
727        }
728        if (debug != null) {
729            sourceDebug = new ByteVector().encodeUTF8(debug, 0,
730                    Integer.MAX_VALUE);
731        }
732    }
733
734    @Override
735    public final void visitOuterClass(final String owner, final String name,
736            final String desc) {
737        enclosingMethodOwner = newClass(owner);
738        if (name != null && desc != null) {
739            enclosingMethod = newNameType(name, desc);
740        }
741    }
742
743    @Override
744    public final AnnotationVisitor visitAnnotation(final String desc,
745            final boolean visible) {
746        if (!ClassReader.ANNOTATIONS) {
747            return null;
748        }
749        ByteVector bv = new ByteVector();
750        // write type, and reserve space for values count
751        bv.putShort(newUTF8(desc)).putShort(0);
752        AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, 2);
753        if (visible) {
754            aw.next = anns;
755            anns = aw;
756        } else {
757            aw.next = ianns;
758            ianns = aw;
759        }
760        return aw;
761    }
762
763    @Override
764    public final AnnotationVisitor visitTypeAnnotation(int typeRef,
765            TypePath typePath, final String desc, final boolean visible) {
766        if (!ClassReader.ANNOTATIONS) {
767            return null;
768        }
769        ByteVector bv = new ByteVector();
770        // write target_type and target_info
771        AnnotationWriter.putTarget(typeRef, typePath, bv);
772        // write type, and reserve space for values count
773        bv.putShort(newUTF8(desc)).putShort(0);
774        AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv,
775                bv.length - 2);
776        if (visible) {
777            aw.next = tanns;
778            tanns = aw;
779        } else {
780            aw.next = itanns;
781            itanns = aw;
782        }
783        return aw;
784    }
785
786    @Override
787    public final void visitAttribute(final Attribute attr) {
788        attr.next = attrs;
789        attrs = attr;
790    }
791
792    @Override
793    public final void visitInnerClass(final String name,
794            final String outerName, final String innerName, final int access) {
795        if (innerClasses == null) {
796            innerClasses = new ByteVector();
797        }
798        // Sec. 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the
799        // constant_pool table which represents a class or interface C that is
800        // not a package member must have exactly one corresponding entry in the
801        // classes array". To avoid duplicates we keep track in the intVal field
802        // of the Item of each CONSTANT_Class_info entry C whether an inner
803        // class entry has already been added for C (this field is unused for
804        // class entries, and changing its value does not change the hashcode
805        // and equality tests). If so we store the index of this inner class
806        // entry (plus one) in intVal. This hack allows duplicate detection in
807        // O(1) time.
808        Item nameItem = newClassItem(name);
809        if (nameItem.intVal == 0) {
810            ++innerClassesCount;
811            innerClasses.putShort(nameItem.index);
812            innerClasses.putShort(outerName == null ? 0 : newClass(outerName));
813            innerClasses.putShort(innerName == null ? 0 : newUTF8(innerName));
814            innerClasses.putShort(access);
815            nameItem.intVal = innerClassesCount;
816        } else {
817            // Compare the inner classes entry nameItem.intVal - 1 with the
818            // arguments of this method and throw an exception if there is a
819            // difference?
820        }
821    }
822
823    @Override
824    public final FieldVisitor visitField(final int access, final String name,
825            final String desc, final String signature, final Object value) {
826        return new FieldWriter(this, access, name, desc, signature, value);
827    }
828
829    @Override
830    public final MethodVisitor visitMethod(final int access, final String name,
831            final String desc, final String signature, final String[] exceptions) {
832        return new MethodWriter(this, access, name, desc, signature,
833                exceptions, computeMaxs, computeFrames);
834    }
835
836    @Override
837    public final void visitEnd() {
838    }
839
840    // ------------------------------------------------------------------------
841    // Other public methods
842    // ------------------------------------------------------------------------
843
844    /**
845     * Returns the bytecode of the class that was build with this class writer.
846     *
847     * @return the bytecode of the class that was build with this class writer.
848     */
849    public byte[] toByteArray() {
850        if (index > 0xFFFF) {
851            throw new RuntimeException("Class file too large!");
852        }
853        // computes the real size of the bytecode of this class
854        int size = 24 + 2 * interfaceCount;
855        int nbFields = 0;
856        FieldWriter fb = firstField;
857        while (fb != null) {
858            ++nbFields;
859            size += fb.getSize();
860            fb = (FieldWriter) fb.fv;
861        }
862        int nbMethods = 0;
863        MethodWriter mb = firstMethod;
864        while (mb != null) {
865            ++nbMethods;
866            size += mb.getSize();
867            mb = (MethodWriter) mb.mv;
868        }
869        int attributeCount = 0;
870        if (bootstrapMethods != null) {
871            // we put it as first attribute in order to improve a bit
872            // ClassReader.copyBootstrapMethods
873            ++attributeCount;
874            size += 8 + bootstrapMethods.length;
875            newUTF8("BootstrapMethods");
876        }
877        if (ClassReader.SIGNATURES && signature != 0) {
878            ++attributeCount;
879            size += 8;
880            newUTF8("Signature");
881        }
882        if (sourceFile != 0) {
883            ++attributeCount;
884            size += 8;
885            newUTF8("SourceFile");
886        }
887        if (sourceDebug != null) {
888            ++attributeCount;
889            size += sourceDebug.length + 6;
890            newUTF8("SourceDebugExtension");
891        }
892        if (enclosingMethodOwner != 0) {
893            ++attributeCount;
894            size += 10;
895            newUTF8("EnclosingMethod");
896        }
897        if ((access & Opcodes.ACC_DEPRECATED) != 0) {
898            ++attributeCount;
899            size += 6;
900            newUTF8("Deprecated");
901        }
902        if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
903            if ((version & 0xFFFF) < Opcodes.V1_5
904                    || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) {
905                ++attributeCount;
906                size += 6;
907                newUTF8("Synthetic");
908            }
909        }
910        if (innerClasses != null) {
911            ++attributeCount;
912            size += 8 + innerClasses.length;
913            newUTF8("InnerClasses");
914        }
915        if (ClassReader.ANNOTATIONS && anns != null) {
916            ++attributeCount;
917            size += 8 + anns.getSize();
918            newUTF8("RuntimeVisibleAnnotations");
919        }
920        if (ClassReader.ANNOTATIONS && ianns != null) {
921            ++attributeCount;
922            size += 8 + ianns.getSize();
923            newUTF8("RuntimeInvisibleAnnotations");
924        }
925        if (ClassReader.ANNOTATIONS && tanns != null) {
926            ++attributeCount;
927            size += 8 + tanns.getSize();
928            newUTF8("RuntimeVisibleTypeAnnotations");
929        }
930        if (ClassReader.ANNOTATIONS && itanns != null) {
931            ++attributeCount;
932            size += 8 + itanns.getSize();
933            newUTF8("RuntimeInvisibleTypeAnnotations");
934        }
935        if (attrs != null) {
936            attributeCount += attrs.getCount();
937            size += attrs.getSize(this, null, 0, -1, -1);
938        }
939        size += pool.length;
940        // allocates a byte vector of this size, in order to avoid unnecessary
941        // arraycopy operations in the ByteVector.enlarge() method
942        ByteVector out = new ByteVector(size);
943        out.putInt(0xCAFEBABE).putInt(version);
944        out.putShort(index).putByteArray(pool.data, 0, pool.length);
945        int mask = Opcodes.ACC_DEPRECATED | ACC_SYNTHETIC_ATTRIBUTE
946                | ((access & ACC_SYNTHETIC_ATTRIBUTE) / TO_ACC_SYNTHETIC);
947        out.putShort(access & ~mask).putShort(name).putShort(superName);
948        out.putShort(interfaceCount);
949        for (int i = 0; i < interfaceCount; ++i) {
950            out.putShort(interfaces[i]);
951        }
952        out.putShort(nbFields);
953        fb = firstField;
954        while (fb != null) {
955            fb.put(out);
956            fb = (FieldWriter) fb.fv;
957        }
958        out.putShort(nbMethods);
959        mb = firstMethod;
960        while (mb != null) {
961            mb.put(out);
962            mb = (MethodWriter) mb.mv;
963        }
964        out.putShort(attributeCount);
965        if (bootstrapMethods != null) {
966            out.putShort(newUTF8("BootstrapMethods"));
967            out.putInt(bootstrapMethods.length + 2).putShort(
968                    bootstrapMethodsCount);
969            out.putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);
970        }
971        if (ClassReader.SIGNATURES && signature != 0) {
972            out.putShort(newUTF8("Signature")).putInt(2).putShort(signature);
973        }
974        if (sourceFile != 0) {
975            out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile);
976        }
977        if (sourceDebug != null) {
978            int len = sourceDebug.length;
979            out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
980            out.putByteArray(sourceDebug.data, 0, len);
981        }
982        if (enclosingMethodOwner != 0) {
983            out.putShort(newUTF8("EnclosingMethod")).putInt(4);
984            out.putShort(enclosingMethodOwner).putShort(enclosingMethod);
985        }
986        if ((access & Opcodes.ACC_DEPRECATED) != 0) {
987            out.putShort(newUTF8("Deprecated")).putInt(0);
988        }
989        if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
990            if ((version & 0xFFFF) < Opcodes.V1_5
991                    || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) {
992                out.putShort(newUTF8("Synthetic")).putInt(0);
993            }
994        }
995        if (innerClasses != null) {
996            out.putShort(newUTF8("InnerClasses"));
997            out.putInt(innerClasses.length + 2).putShort(innerClassesCount);
998            out.putByteArray(innerClasses.data, 0, innerClasses.length);
999        }
1000        if (ClassReader.ANNOTATIONS && anns != null) {
1001            out.putShort(newUTF8("RuntimeVisibleAnnotations"));
1002            anns.put(out);
1003        }
1004        if (ClassReader.ANNOTATIONS && ianns != null) {
1005            out.putShort(newUTF8("RuntimeInvisibleAnnotations"));
1006            ianns.put(out);
1007        }
1008        if (ClassReader.ANNOTATIONS && tanns != null) {
1009            out.putShort(newUTF8("RuntimeVisibleTypeAnnotations"));
1010            tanns.put(out);
1011        }
1012        if (ClassReader.ANNOTATIONS && itanns != null) {
1013            out.putShort(newUTF8("RuntimeInvisibleTypeAnnotations"));
1014            itanns.put(out);
1015        }
1016        if (attrs != null) {
1017            attrs.put(this, null, 0, -1, -1, out);
1018        }
1019        if (invalidFrames) {
1020            anns = null;
1021            ianns = null;
1022            attrs = null;
1023            innerClassesCount = 0;
1024            innerClasses = null;
1025            bootstrapMethodsCount = 0;
1026            bootstrapMethods = null;
1027            firstField = null;
1028            lastField = null;
1029            firstMethod = null;
1030            lastMethod = null;
1031            computeMaxs = false;
1032            computeFrames = true;
1033            invalidFrames = false;
1034            new ClassReader(out.data).accept(this, ClassReader.SKIP_FRAMES);
1035            return toByteArray();
1036        }
1037        return out.data;
1038    }
1039
1040    // ------------------------------------------------------------------------
1041    // Utility methods: constant pool management
1042    // ------------------------------------------------------------------------
1043
1044    /**
1045     * Adds a number or string constant to the constant pool of the class being
1046     * build. Does nothing if the constant pool already contains a similar item.
1047     *
1048     * @param cst
1049     *            the value of the constant to be added to the constant pool.
1050     *            This parameter must be an {@link Integer}, a {@link Float}, a
1051     *            {@link Long}, a {@link Double}, a {@link String} or a
1052     *            {@link Type}.
1053     * @return a new or already existing constant item with the given value.
1054     */
1055    Item newConstItem(final Object cst) {
1056        if (cst instanceof Integer) {
1057            int val = ((Integer) cst).intValue();
1058            return newInteger(val);
1059        } else if (cst instanceof Byte) {
1060            int val = ((Byte) cst).intValue();
1061            return newInteger(val);
1062        } else if (cst instanceof Character) {
1063            int val = ((Character) cst).charValue();
1064            return newInteger(val);
1065        } else if (cst instanceof Short) {
1066            int val = ((Short) cst).intValue();
1067            return newInteger(val);
1068        } else if (cst instanceof Boolean) {
1069            int val = ((Boolean) cst).booleanValue() ? 1 : 0;
1070            return newInteger(val);
1071        } else if (cst instanceof Float) {
1072            float val = ((Float) cst).floatValue();
1073            return newFloat(val);
1074        } else if (cst instanceof Long) {
1075            long val = ((Long) cst).longValue();
1076            return newLong(val);
1077        } else if (cst instanceof Double) {
1078            double val = ((Double) cst).doubleValue();
1079            return newDouble(val);
1080        } else if (cst instanceof String) {
1081            return newString((String) cst);
1082        } else if (cst instanceof Type) {
1083            Type t = (Type) cst;
1084            int s = t.getSort();
1085            if (s == Type.OBJECT) {
1086                return newClassItem(t.getInternalName());
1087            } else if (s == Type.METHOD) {
1088                return newMethodTypeItem(t.getDescriptor());
1089            } else { // s == primitive type or array
1090                return newClassItem(t.getDescriptor());
1091            }
1092        } else if (cst instanceof Handle) {
1093            Handle h = (Handle) cst;
1094            return newHandleItem(h.tag, h.owner, h.name, h.desc, h.itf);
1095        } else {
1096            throw new IllegalArgumentException("value " + cst);
1097        }
1098    }
1099
1100    /**
1101     * Adds a number or string constant to the constant pool of the class being
1102     * build. Does nothing if the constant pool already contains a similar item.
1103     * <i>This method is intended for {@link Attribute} sub classes, and is
1104     * normally not needed by class generators or adapters.</i>
1105     *
1106     * @param cst
1107     *            the value of the constant to be added to the constant pool.
1108     *            This parameter must be an {@link Integer}, a {@link Float}, a
1109     *            {@link Long}, a {@link Double} or a {@link String}.
1110     * @return the index of a new or already existing constant item with the
1111     *         given value.
1112     */
1113    public int newConst(final Object cst) {
1114        return newConstItem(cst).index;
1115    }
1116
1117    /**
1118     * Adds an UTF8 string to the constant pool of the class being build. Does
1119     * nothing if the constant pool already contains a similar item. <i>This
1120     * method is intended for {@link Attribute} sub classes, and is normally not
1121     * needed by class generators or adapters.</i>
1122     *
1123     * @param value
1124     *            the String value.
1125     * @return the index of a new or already existing UTF8 item.
1126     */
1127    public int newUTF8(final String value) {
1128        key.set(UTF8, value, null, null);
1129        Item result = get(key);
1130        if (result == null) {
1131            pool.putByte(UTF8).putUTF8(value);
1132            result = new Item(index++, key);
1133            put(result);
1134        }
1135        return result.index;
1136    }
1137
1138    /**
1139     * Adds a class reference to the constant pool of the class being build.
1140     * Does nothing if the constant pool already contains a similar item.
1141     * <i>This method is intended for {@link Attribute} sub classes, and is
1142     * normally not needed by class generators or adapters.</i>
1143     *
1144     * @param value
1145     *            the internal name of the class.
1146     * @return a new or already existing class reference item.
1147     */
1148    Item newClassItem(final String value) {
1149        key2.set(CLASS, value, null, null);
1150        Item result = get(key2);
1151        if (result == null) {
1152            pool.put12(CLASS, newUTF8(value));
1153            result = new Item(index++, key2);
1154            put(result);
1155        }
1156        return result;
1157    }
1158
1159    /**
1160     * Adds a class reference to the constant pool of the class being build.
1161     * Does nothing if the constant pool already contains a similar item.
1162     * <i>This method is intended for {@link Attribute} sub classes, and is
1163     * normally not needed by class generators or adapters.</i>
1164     *
1165     * @param value
1166     *            the internal name of the class.
1167     * @return the index of a new or already existing class reference item.
1168     */
1169    public int newClass(final String value) {
1170        return newClassItem(value).index;
1171    }
1172
1173    /**
1174     * Adds a module name to the constant pool.
1175     *
1176     * Does nothing if the constant pool already contains a similar item.
1177     * <i>This method is intended for {@link Attribute} sub classes, and is
1178     * normally not needed by class generators or adapters.</i>
1179     *
1180     * @param  value
1181     *         the module name
1182     * @return the index of a new or already existing module reference item.
1183     */
1184    public int newModule(String value) {
1185        key2.set(MODULE, value, null, null);
1186        Item result = get(key2);
1187        if (result == null) {
1188            pool.put12(MODULE, newUTF8(value));
1189            result = new Item(index++, key2);
1190            put(result);
1191        }
1192        return result.index;
1193    }
1194
1195    /**
1196     * Adds a package name to the constant pool.
1197     *
1198     * Does nothing if the constant pool already contains a similar item.
1199     * <i>This method is intended for {@link Attribute} sub classes, and is
1200     * normally not needed by class generators or adapters.</i>
1201     *
1202     * @param  value
1203     *         the internal name of the package.
1204     * @return the index of a new or already existing package reference item.
1205     */
1206    public int newPackage(String value) {
1207        key2.set(PACKAGE, value, null, null);
1208        Item result = get(key2);
1209        if (result == null) {
1210            pool.put12(PACKAGE, newUTF8(value));
1211            result = new Item(index++, key2);
1212            put(result);
1213        }
1214        return result.index;
1215    }
1216
1217    /**
1218     * Adds a method type reference to the constant pool of the class being
1219     * build. Does nothing if the constant pool already contains a similar item.
1220     * <i>This method is intended for {@link Attribute} sub classes, and is
1221     * normally not needed by class generators or adapters.</i>
1222     *
1223     * @param methodDesc
1224     *            method descriptor of the method type.
1225     * @return a new or already existing method type reference item.
1226     */
1227    Item newMethodTypeItem(final String methodDesc) {
1228        key2.set(MTYPE, methodDesc, null, null);
1229        Item result = get(key2);
1230        if (result == null) {
1231            pool.put12(MTYPE, newUTF8(methodDesc));
1232            result = new Item(index++, key2);
1233            put(result);
1234        }
1235        return result;
1236    }
1237
1238    /**
1239     * Adds a method type reference to the constant pool of the class being
1240     * build. Does nothing if the constant pool already contains a similar item.
1241     * <i>This method is intended for {@link Attribute} sub classes, and is
1242     * normally not needed by class generators or adapters.</i>
1243     *
1244     * @param methodDesc
1245     *            method descriptor of the method type.
1246     * @return the index of a new or already existing method type reference
1247     *         item.
1248     */
1249    public int newMethodType(final String methodDesc) {
1250        return newMethodTypeItem(methodDesc).index;
1251    }
1252
1253    /**
1254     * Adds a handle to the constant pool of the class being build. Does nothing
1255     * if the constant pool already contains a similar item. <i>This method is
1256     * intended for {@link Attribute} sub classes, and is normally not needed by
1257     * class generators or adapters.</i>
1258     *
1259     * @param tag
1260     *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
1261     *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
1262     *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
1263     *            {@link Opcodes#H_INVOKESTATIC},
1264     *            {@link Opcodes#H_INVOKESPECIAL},
1265     *            {@link Opcodes#H_NEWINVOKESPECIAL} or
1266     *            {@link Opcodes#H_INVOKEINTERFACE}.
1267     * @param owner
1268     *            the internal name of the field or method owner class.
1269     * @param name
1270     *            the name of the field or method.
1271     * @param desc
1272     *            the descriptor of the field or method.
1273     * @param itf
1274     *            true if the owner is an interface.
1275     * @return a new or an already existing method type reference item.
1276     */
1277    Item newHandleItem(final int tag, final String owner, final String name,
1278            final String desc, final boolean itf) {
1279        key4.set(HANDLE_BASE + tag, owner, name, desc);
1280        Item result = get(key4);
1281        if (result == null) {
1282            if (tag <= Opcodes.H_PUTSTATIC) {
1283                put112(HANDLE, tag, newField(owner, name, desc));
1284            } else {
1285                put112(HANDLE,
1286                        tag,
1287                        newMethod(owner, name, desc, itf));
1288            }
1289            result = new Item(index++, key4);
1290            put(result);
1291        }
1292        return result;
1293    }
1294
1295    /**
1296     * Adds a handle to the constant pool of the class being build. Does nothing
1297     * if the constant pool already contains a similar item. <i>This method is
1298     * intended for {@link Attribute} sub classes, and is normally not needed by
1299     * class generators or adapters.</i>
1300     *
1301     * @param tag
1302     *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
1303     *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
1304     *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
1305     *            {@link Opcodes#H_INVOKESTATIC},
1306     *            {@link Opcodes#H_INVOKESPECIAL},
1307     *            {@link Opcodes#H_NEWINVOKESPECIAL} or
1308     *            {@link Opcodes#H_INVOKEINTERFACE}.
1309     * @param owner
1310     *            the internal name of the field or method owner class.
1311     * @param name
1312     *            the name of the field or method.
1313     * @param desc
1314     *            the descriptor of the field or method.
1315     * @return the index of a new or already existing method type reference
1316     *         item.
1317     *
1318     * @deprecated this method is superseded by
1319     *             {@link #newHandle(int, String, String, String, boolean)}.
1320     */
1321    @Deprecated
1322    public int newHandle(final int tag, final String owner, final String name,
1323            final String desc) {
1324        return newHandle(tag, owner, name, desc, tag == Opcodes.H_INVOKEINTERFACE);
1325    }
1326
1327    /**
1328     * Adds a handle to the constant pool of the class being build. Does nothing
1329     * if the constant pool already contains a similar item. <i>This method is
1330     * intended for {@link Attribute} sub classes, and is normally not needed by
1331     * class generators or adapters.</i>
1332     *
1333     * @param tag
1334     *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
1335     *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
1336     *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
1337     *            {@link Opcodes#H_INVOKESTATIC},
1338     *            {@link Opcodes#H_INVOKESPECIAL},
1339     *            {@link Opcodes#H_NEWINVOKESPECIAL} or
1340     *            {@link Opcodes#H_INVOKEINTERFACE}.
1341     * @param owner
1342     *            the internal name of the field or method owner class.
1343     * @param name
1344     *            the name of the field or method.
1345     * @param desc
1346     *            the descriptor of the field or method.
1347     * @param itf
1348     *            true if the owner is an interface.
1349     * @return the index of a new or already existing method type reference
1350     *         item.
1351     */
1352    public int newHandle(final int tag, final String owner, final String name,
1353            final String desc, final boolean itf) {
1354        return newHandleItem(tag, owner, name, desc, itf).index;
1355    }
1356
1357    /**
1358     * Adds an invokedynamic reference to the constant pool of the class being
1359     * build. Does nothing if the constant pool already contains a similar item.
1360     * <i>This method is intended for {@link Attribute} sub classes, and is
1361     * normally not needed by class generators or adapters.</i>
1362     *
1363     * @param name
1364     *            name of the invoked method.
1365     * @param desc
1366     *            descriptor of the invoke method.
1367     * @param bsm
1368     *            the bootstrap method.
1369     * @param bsmArgs
1370     *            the bootstrap method constant arguments.
1371     *
1372     * @return a new or an already existing invokedynamic type reference item.
1373     */
1374    Item newInvokeDynamicItem(final String name, final String desc,
1375            final Handle bsm, final Object... bsmArgs) {
1376        // cache for performance
1377        ByteVector bootstrapMethods = this.bootstrapMethods;
1378        if (bootstrapMethods == null) {
1379            bootstrapMethods = this.bootstrapMethods = new ByteVector();
1380        }
1381
1382        int position = bootstrapMethods.length; // record current position
1383
1384        int hashCode = bsm.hashCode();
1385        bootstrapMethods.putShort(newHandle(bsm.tag, bsm.owner, bsm.name,
1386                bsm.desc, bsm.isInterface()));
1387
1388        int argsLength = bsmArgs.length;
1389        bootstrapMethods.putShort(argsLength);
1390
1391        for (int i = 0; i < argsLength; i++) {
1392            Object bsmArg = bsmArgs[i];
1393            hashCode ^= bsmArg.hashCode();
1394            bootstrapMethods.putShort(newConst(bsmArg));
1395        }
1396
1397        byte[] data = bootstrapMethods.data;
1398        int length = (1 + 1 + argsLength) << 1; // (bsm + argCount + arguments)
1399        hashCode &= 0x7FFFFFFF;
1400        Item result = items[hashCode % items.length];
1401        loop: while (result != null) {
1402            if (result.type != BSM || result.hashCode != hashCode) {
1403                result = result.next;
1404                continue;
1405            }
1406
1407            // because the data encode the size of the argument
1408            // we don't need to test if these size are equals
1409            int resultPosition = result.intVal;
1410            for (int p = 0; p < length; p++) {
1411                if (data[position + p] != data[resultPosition + p]) {
1412                    result = result.next;
1413                    continue loop;
1414                }
1415            }
1416            break;
1417        }
1418
1419        int bootstrapMethodIndex;
1420        if (result != null) {
1421            bootstrapMethodIndex = result.index;
1422            bootstrapMethods.length = position; // revert to old position
1423        } else {
1424            bootstrapMethodIndex = bootstrapMethodsCount++;
1425            result = new Item(bootstrapMethodIndex);
1426            result.set(position, hashCode);
1427            put(result);
1428        }
1429
1430        // now, create the InvokeDynamic constant
1431        key3.set(name, desc, bootstrapMethodIndex);
1432        result = get(key3);
1433        if (result == null) {
1434            put122(INDY, bootstrapMethodIndex, newNameType(name, desc));
1435            result = new Item(index++, key3);
1436            put(result);
1437        }
1438        return result;
1439    }
1440
1441    /**
1442     * Adds an invokedynamic reference to the constant pool of the class being
1443     * build. Does nothing if the constant pool already contains a similar item.
1444     * <i>This method is intended for {@link Attribute} sub classes, and is
1445     * normally not needed by class generators or adapters.</i>
1446     *
1447     * @param name
1448     *            name of the invoked method.
1449     * @param desc
1450     *            descriptor of the invoke method.
1451     * @param bsm
1452     *            the bootstrap method.
1453     * @param bsmArgs
1454     *            the bootstrap method constant arguments.
1455     *
1456     * @return the index of a new or already existing invokedynamic reference
1457     *         item.
1458     */
1459    public int newInvokeDynamic(final String name, final String desc,
1460            final Handle bsm, final Object... bsmArgs) {
1461        return newInvokeDynamicItem(name, desc, bsm, bsmArgs).index;
1462    }
1463
1464    /**
1465     * Adds a field reference to the constant pool of the class being build.
1466     * Does nothing if the constant pool already contains a similar item.
1467     *
1468     * @param owner
1469     *            the internal name of the field's owner class.
1470     * @param name
1471     *            the field's name.
1472     * @param desc
1473     *            the field's descriptor.
1474     * @return a new or already existing field reference item.
1475     */
1476    Item newFieldItem(final String owner, final String name, final String desc) {
1477        key3.set(FIELD, owner, name, desc);
1478        Item result = get(key3);
1479        if (result == null) {
1480            put122(FIELD, newClass(owner), newNameType(name, desc));
1481            result = new Item(index++, key3);
1482            put(result);
1483        }
1484        return result;
1485    }
1486
1487    /**
1488     * Adds a field reference to the constant pool of the class being build.
1489     * Does nothing if the constant pool already contains a similar item.
1490     * <i>This method is intended for {@link Attribute} sub classes, and is
1491     * normally not needed by class generators or adapters.</i>
1492     *
1493     * @param owner
1494     *            the internal name of the field's owner class.
1495     * @param name
1496     *            the field's name.
1497     * @param desc
1498     *            the field's descriptor.
1499     * @return the index of a new or already existing field reference item.
1500     */
1501    public int newField(final String owner, final String name, final String desc) {
1502        return newFieldItem(owner, name, desc).index;
1503    }
1504
1505    /**
1506     * Adds a method reference to the constant pool of the class being build.
1507     * Does nothing if the constant pool already contains a similar item.
1508     *
1509     * @param owner
1510     *            the internal name of the method's owner class.
1511     * @param name
1512     *            the method's name.
1513     * @param desc
1514     *            the method's descriptor.
1515     * @param itf
1516     *            <tt>true</tt> if <tt>owner</tt> is an interface.
1517     * @return a new or already existing method reference item.
1518     */
1519    Item newMethodItem(final String owner, final String name,
1520            final String desc, final boolean itf) {
1521        int type = itf ? IMETH : METH;
1522        key3.set(type, owner, name, desc);
1523        Item result = get(key3);
1524        if (result == null) {
1525            put122(type, newClass(owner), newNameType(name, desc));
1526            result = new Item(index++, key3);
1527            put(result);
1528        }
1529        return result;
1530    }
1531
1532    /**
1533     * Adds a method reference to the constant pool of the class being build.
1534     * Does nothing if the constant pool already contains a similar item.
1535     * <i>This method is intended for {@link Attribute} sub classes, and is
1536     * normally not needed by class generators or adapters.</i>
1537     *
1538     * @param owner
1539     *            the internal name of the method's owner class.
1540     * @param name
1541     *            the method's name.
1542     * @param desc
1543     *            the method's descriptor.
1544     * @param itf
1545     *            <tt>true</tt> if <tt>owner</tt> is an interface.
1546     * @return the index of a new or already existing method reference item.
1547     */
1548    public int newMethod(final String owner, final String name,
1549            final String desc, final boolean itf) {
1550        return newMethodItem(owner, name, desc, itf).index;
1551    }
1552
1553    /**
1554     * Adds an integer to the constant pool of the class being build. Does
1555     * nothing if the constant pool already contains a similar item.
1556     *
1557     * @param value
1558     *            the int value.
1559     * @return a new or already existing int item.
1560     */
1561    Item newInteger(final int value) {
1562        key.set(value);
1563        Item result = get(key);
1564        if (result == null) {
1565            pool.putByte(INT).putInt(value);
1566            result = new Item(index++, key);
1567            put(result);
1568        }
1569        return result;
1570    }
1571
1572    /**
1573     * Adds a float to the constant pool of the class being build. Does nothing
1574     * if the constant pool already contains a similar item.
1575     *
1576     * @param value
1577     *            the float value.
1578     * @return a new or already existing float item.
1579     */
1580    Item newFloat(final float value) {
1581        key.set(value);
1582        Item result = get(key);
1583        if (result == null) {
1584            pool.putByte(FLOAT).putInt(key.intVal);
1585            result = new Item(index++, key);
1586            put(result);
1587        }
1588        return result;
1589    }
1590
1591    /**
1592     * Adds a long to the constant pool of the class being build. Does nothing
1593     * if the constant pool already contains a similar item.
1594     *
1595     * @param value
1596     *            the long value.
1597     * @return a new or already existing long item.
1598     */
1599    Item newLong(final long value) {
1600        key.set(value);
1601        Item result = get(key);
1602        if (result == null) {
1603            pool.putByte(LONG).putLong(value);
1604            result = new Item(index, key);
1605            index += 2;
1606            put(result);
1607        }
1608        return result;
1609    }
1610
1611    /**
1612     * Adds a double to the constant pool of the class being build. Does nothing
1613     * if the constant pool already contains a similar item.
1614     *
1615     * @param value
1616     *            the double value.
1617     * @return a new or already existing double item.
1618     */
1619    Item newDouble(final double value) {
1620        key.set(value);
1621        Item result = get(key);
1622        if (result == null) {
1623            pool.putByte(DOUBLE).putLong(key.longVal);
1624            result = new Item(index, key);
1625            index += 2;
1626            put(result);
1627        }
1628        return result;
1629    }
1630
1631    /**
1632     * Adds a string to the constant pool of the class being build. Does nothing
1633     * if the constant pool already contains a similar item.
1634     *
1635     * @param value
1636     *            the String value.
1637     * @return a new or already existing string item.
1638     */
1639    private Item newString(final String value) {
1640        key2.set(STR, value, null, null);
1641        Item result = get(key2);
1642        if (result == null) {
1643            pool.put12(STR, newUTF8(value));
1644            result = new Item(index++, key2);
1645            put(result);
1646        }
1647        return result;
1648    }
1649
1650    /**
1651     * Adds a name and type to the constant pool of the class being build. Does
1652     * nothing if the constant pool already contains a similar item. <i>This
1653     * method is intended for {@link Attribute} sub classes, and is normally not
1654     * needed by class generators or adapters.</i>
1655     *
1656     * @param name
1657     *            a name.
1658     * @param desc
1659     *            a type descriptor.
1660     * @return the index of a new or already existing name and type item.
1661     */
1662    public int newNameType(final String name, final String desc) {
1663        return newNameTypeItem(name, desc).index;
1664    }
1665
1666    /**
1667     * Adds a name and type to the constant pool of the class being build. Does
1668     * nothing if the constant pool already contains a similar item.
1669     *
1670     * @param name
1671     *            a name.
1672     * @param desc
1673     *            a type descriptor.
1674     * @return a new or already existing name and type item.
1675     */
1676    Item newNameTypeItem(final String name, final String desc) {
1677        key2.set(NAME_TYPE, name, desc, null);
1678        Item result = get(key2);
1679        if (result == null) {
1680            put122(NAME_TYPE, newUTF8(name), newUTF8(desc));
1681            result = new Item(index++, key2);
1682            put(result);
1683        }
1684        return result;
1685    }
1686
1687    /**
1688     * Adds the given internal name to {@link #typeTable} and returns its index.
1689     * Does nothing if the type table already contains this internal name.
1690     *
1691     * @param type
1692     *            the internal name to be added to the type table.
1693     * @return the index of this internal name in the type table.
1694     */
1695    int addType(final String type) {
1696        key.set(TYPE_NORMAL, type, null, null);
1697        Item result = get(key);
1698        if (result == null) {
1699            result = addType(key);
1700        }
1701        return result.index;
1702    }
1703
1704    /**
1705     * Adds the given "uninitialized" type to {@link #typeTable} and returns its
1706     * index. This method is used for UNINITIALIZED types, made of an internal
1707     * name and a bytecode offset.
1708     *
1709     * @param type
1710     *            the internal name to be added to the type table.
1711     * @param offset
1712     *            the bytecode offset of the NEW instruction that created this
1713     *            UNINITIALIZED type value.
1714     * @return the index of this internal name in the type table.
1715     */
1716    int addUninitializedType(final String type, final int offset) {
1717        key.type = TYPE_UNINIT;
1718        key.intVal = offset;
1719        key.strVal1 = type;
1720        key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset);
1721        Item result = get(key);
1722        if (result == null) {
1723            result = addType(key);
1724        }
1725        return result.index;
1726    }
1727
1728    /**
1729     * Adds the given Item to {@link #typeTable}.
1730     *
1731     * @param item
1732     *            the value to be added to the type table.
1733     * @return the added Item, which a new Item instance with the same value as
1734     *         the given Item.
1735     */
1736    private Item addType(final Item item) {
1737        ++typeCount;
1738        Item result = new Item(typeCount, key);
1739        put(result);
1740        if (typeTable == null) {
1741            typeTable = new Item[16];
1742        }
1743        if (typeCount == typeTable.length) {
1744            Item[] newTable = new Item[2 * typeTable.length];
1745            System.arraycopy(typeTable, 0, newTable, 0, typeTable.length);
1746            typeTable = newTable;
1747        }
1748        typeTable[typeCount] = result;
1749        return result;
1750    }
1751
1752    /**
1753     * Returns the index of the common super type of the two given types. This
1754     * method calls {@link #getCommonSuperClass} and caches the result in the
1755     * {@link #items} hash table to speedup future calls with the same
1756     * parameters.
1757     *
1758     * @param type1
1759     *            index of an internal name in {@link #typeTable}.
1760     * @param type2
1761     *            index of an internal name in {@link #typeTable}.
1762     * @return the index of the common super type of the two given types.
1763     */
1764    int getMergedType(final int type1, final int type2) {
1765        key2.type = TYPE_MERGED;
1766        key2.longVal = type1 | (((long) type2) << 32);
1767        key2.hashCode = 0x7FFFFFFF & (TYPE_MERGED + type1 + type2);
1768        Item result = get(key2);
1769        if (result == null) {
1770            String t = typeTable[type1].strVal1;
1771            String u = typeTable[type2].strVal1;
1772            key2.intVal = addType(getCommonSuperClass(t, u));
1773            result = new Item((short) 0, key2);
1774            put(result);
1775        }
1776        return result.intVal;
1777    }
1778
1779    /**
1780     * Returns the common super type of the two given types. The default
1781     * implementation of this method <i>loads</i> the two given classes and uses
1782     * the java.lang.Class methods to find the common super class. It can be
1783     * overridden to compute this common super type in other ways, in particular
1784     * without actually loading any class, or to take into account the class
1785     * that is currently being generated by this ClassWriter, which can of
1786     * course not be loaded since it is under construction.
1787     *
1788     * @param type1
1789     *            the internal name of a class.
1790     * @param type2
1791     *            the internal name of another class.
1792     * @return the internal name of the common super class of the two given
1793     *         classes.
1794     */
1795    protected String getCommonSuperClass(final String type1, final String type2) {
1796        Class<?> c, d;
1797        ClassLoader classLoader = getClass().getClassLoader();
1798        try {
1799            c = Class.forName(type1.replace('/', '.'), false, classLoader);
1800            d = Class.forName(type2.replace('/', '.'), false, classLoader);
1801        } catch (Exception e) {
1802            throw new RuntimeException(e.toString());
1803        }
1804        if (c.isAssignableFrom(d)) {
1805            return type1;
1806        }
1807        if (d.isAssignableFrom(c)) {
1808            return type2;
1809        }
1810        if (c.isInterface() || d.isInterface()) {
1811            return "java/lang/Object";
1812        } else {
1813            do {
1814                c = c.getSuperclass();
1815            } while (!c.isAssignableFrom(d));
1816            return c.getName().replace('.', '/');
1817        }
1818    }
1819
1820    /**
1821     * Returns the constant pool's hash table item which is equal to the given
1822     * item.
1823     *
1824     * @param key
1825     *            a constant pool item.
1826     * @return the constant pool's hash table item which is equal to the given
1827     *         item, or <tt>null</tt> if there is no such item.
1828     */
1829    private Item get(final Item key) {
1830        Item i = items[key.hashCode % items.length];
1831        while (i != null && (i.type != key.type || !key.isEqualTo(i))) {
1832            i = i.next;
1833        }
1834        return i;
1835    }
1836
1837    /**
1838     * Puts the given item in the constant pool's hash table. The hash table
1839     * <i>must</i> not already contains this item.
1840     *
1841     * @param i
1842     *            the item to be added to the constant pool's hash table.
1843     */
1844    private void put(final Item i) {
1845        if (index + typeCount > threshold) {
1846            int ll = items.length;
1847            int nl = ll * 2 + 1;
1848            Item[] newItems = new Item[nl];
1849            for (int l = ll - 1; l >= 0; --l) {
1850                Item j = items[l];
1851                while (j != null) {
1852                    int index = j.hashCode % newItems.length;
1853                    Item k = j.next;
1854                    j.next = newItems[index];
1855                    newItems[index] = j;
1856                    j = k;
1857                }
1858            }
1859            items = newItems;
1860            threshold = (int) (nl * 0.75);
1861        }
1862        int index = i.hashCode % items.length;
1863        i.next = items[index];
1864        items[index] = i;
1865    }
1866
1867    /**
1868     * Puts one byte and two shorts into the constant pool.
1869     *
1870     * @param b
1871     *            a byte.
1872     * @param s1
1873     *            a short.
1874     * @param s2
1875     *            another short.
1876     */
1877    private void put122(final int b, final int s1, final int s2) {
1878        pool.put12(b, s1).putShort(s2);
1879    }
1880
1881    /**
1882     * Puts two bytes and one short into the constant pool.
1883     *
1884     * @param b1
1885     *            a byte.
1886     * @param b2
1887     *            another byte.
1888     * @param s
1889     *            a short.
1890     */
1891    private void put112(final int b1, final int b2, final int s) {
1892        pool.put11(b1, b2).putShort(s);
1893    }
1894}
1895