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  */
  59 package 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  */
  70 public 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 base value for all CONSTANT_MethodHandle constant pool items.
 276      * Internally, ASM store the 9 variations of CONSTANT_MethodHandle into 9
 277      * different items.
 278      */
 279     static final int HANDLE_BASE = 20;
 280 
 281     /**
 282      * Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable},
 283      * instead of the constant pool, in order to avoid clashes with normal
 284      * constant pool items in the ClassWriter constant pool's hash table.
 285      */
 286     static final int TYPE_NORMAL = 30;
 287 
 288     /**
 289      * Uninitialized type Item stored in the ClassWriter
 290      * {@link ClassWriter#typeTable}, instead of the constant pool, in order to
 291      * avoid clashes with normal constant pool items in the ClassWriter constant
 292      * pool's hash table.
 293      */
 294     static final int TYPE_UNINIT = 31;
 295 
 296     /**
 297      * Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable},
 298      * instead of the constant pool, in order to avoid clashes with normal
 299      * constant pool items in the ClassWriter constant pool's hash table.
 300      */
 301     static final int TYPE_MERGED = 32;
 302 
 303     /**
 304      * The type of BootstrapMethods items. These items are stored in a special
 305      * class attribute named BootstrapMethods and not in the constant pool.
 306      */
 307     static final int BSM = 33;
 308 
 309     /**
 310      * The class reader from which this class writer was constructed, if any.
 311      */
 312     ClassReader cr;
 313 
 314     /**
 315      * Minor and major version numbers of the class to be generated.
 316      */
 317     int version;
 318 
 319     /**
 320      * Index of the next item to be added in the constant pool.
 321      */
 322     int index;
 323 
 324     /**
 325      * The constant pool of this class.
 326      */
 327     final ByteVector pool;
 328 
 329     /**
 330      * The constant pool's hash table data.
 331      */
 332     Item[] items;
 333 
 334     /**
 335      * The threshold of the constant pool's hash table.
 336      */
 337     int threshold;
 338 
 339     /**
 340      * A reusable key used to look for items in the {@link #items} hash table.
 341      */
 342     final Item key;
 343 
 344     /**
 345      * A reusable key used to look for items in the {@link #items} hash table.
 346      */
 347     final Item key2;
 348 
 349     /**
 350      * A reusable key used to look for items in the {@link #items} hash table.
 351      */
 352     final Item key3;
 353 
 354     /**
 355      * A reusable key used to look for items in the {@link #items} hash table.
 356      */
 357     final Item key4;
 358 
 359     /**
 360      * A type table used to temporarily store internal names that will not
 361      * necessarily be stored in the constant pool. This type table is used by
 362      * the control flow and data flow analysis algorithm used to compute stack
 363      * map frames from scratch. This array associates to each index <tt>i</tt>
 364      * the Item whose index is <tt>i</tt>. All Item objects stored in this array
 365      * are also stored in the {@link #items} hash table. These two arrays allow
 366      * to retrieve an Item from its index or, conversely, to get the index of an
 367      * Item from its value. Each Item stores an internal name in its
 368      * {@link Item#strVal1} field.
 369      */
 370     Item[] typeTable;
 371 
 372     /**
 373      * Number of elements in the {@link #typeTable} array.
 374      */
 375     private short typeCount;
 376 
 377     /**
 378      * The access flags of this class.
 379      */
 380     private int access;
 381 
 382     /**
 383      * The constant pool item that contains the internal name of this class.
 384      */
 385     private int name;
 386 
 387     /**
 388      * The internal name of this class.
 389      */
 390     String thisName;
 391 
 392     /**
 393      * The constant pool item that contains the signature of this class.
 394      */
 395     private int signature;
 396 
 397     /**
 398      * The constant pool item that contains the internal name of the super class
 399      * of this class.
 400      */
 401     private int superName;
 402 
 403     /**
 404      * Number of interfaces implemented or extended by this class or interface.
 405      */
 406     private int interfaceCount;
 407 
 408     /**
 409      * The interfaces implemented or extended by this class or interface. More
 410      * precisely, this array contains the indexes of the constant pool items
 411      * that contain the internal names of these interfaces.
 412      */
 413     private int[] interfaces;
 414 
 415     /**
 416      * The index of the constant pool item that contains the name of the source
 417      * file from which this class was compiled.
 418      */
 419     private int sourceFile;
 420 
 421     /**
 422      * The SourceDebug attribute of this class.
 423      */
 424     private ByteVector sourceDebug;
 425 
 426     /**
 427      * The constant pool item that contains the name of the enclosing class of
 428      * this class.
 429      */
 430     private int enclosingMethodOwner;
 431 
 432     /**
 433      * The constant pool item that contains the name and descriptor of the
 434      * enclosing method of this class.
 435      */
 436     private int enclosingMethod;
 437 
 438     /**
 439      * The runtime visible annotations of this class.
 440      */
 441     private AnnotationWriter anns;
 442 
 443     /**
 444      * The runtime invisible annotations of this class.
 445      */
 446     private AnnotationWriter ianns;
 447 
 448     /**
 449      * The runtime visible type annotations of this class.
 450      */
 451     private AnnotationWriter tanns;
 452 
 453     /**
 454      * The runtime invisible type annotations of this class.
 455      */
 456     private AnnotationWriter itanns;
 457 
 458     /**
 459      * The non standard attributes of this class.
 460      */
 461     private Attribute attrs;
 462 
 463     /**
 464      * The number of entries in the InnerClasses attribute.
 465      */
 466     private int innerClassesCount;
 467 
 468     /**
 469      * The InnerClasses attribute.
 470      */
 471     private ByteVector innerClasses;
 472 
 473     /**
 474      * The number of entries in the BootstrapMethods attribute.
 475      */
 476     int bootstrapMethodsCount;
 477 
 478     /**
 479      * The BootstrapMethods attribute.
 480      */
 481     ByteVector bootstrapMethods;
 482 
 483     /**
 484      * The fields of this class. These fields are stored in a linked list of
 485      * {@link FieldWriter} objects, linked to each other by their
 486      * {@link FieldWriter#fv} field. This field stores the first element of this
 487      * list.
 488      */
 489     FieldWriter firstField;
 490 
 491     /**
 492      * The fields of this class. These fields are stored in a linked list of
 493      * {@link FieldWriter} objects, linked to each other by their
 494      * {@link FieldWriter#fv} field. This field stores the last element of this
 495      * list.
 496      */
 497     FieldWriter lastField;
 498 
 499     /**
 500      * The methods of this class. These methods are stored in a linked list of
 501      * {@link MethodWriter} objects, linked to each other by their
 502      * {@link MethodWriter#mv} field. This field stores the first element of
 503      * this list.
 504      */
 505     MethodWriter firstMethod;
 506 
 507     /**
 508      * The methods of this class. These methods are stored in a linked list of
 509      * {@link MethodWriter} objects, linked to each other by their
 510      * {@link MethodWriter#mv} field. This field stores the last element of this
 511      * list.
 512      */
 513     MethodWriter lastMethod;
 514 
 515     /**
 516      * <tt>true</tt> if the maximum stack size and number of local variables
 517      * must be automatically computed.
 518      */
 519     private boolean computeMaxs;
 520 
 521     /**
 522      * <tt>true</tt> if the stack map frames must be recomputed from scratch.
 523      */
 524     private boolean computeFrames;
 525 
 526     /**
 527      * <tt>true</tt> if the stack map tables of this class are invalid. The
 528      * {@link MethodWriter#resizeInstructions} method cannot transform existing
 529      * stack map tables, and so produces potentially invalid classes when it is
 530      * executed. In this case the class is reread and rewritten with the
 531      * {@link #COMPUTE_FRAMES} option (the resizeInstructions method can resize
 532      * stack map tables when this option is used).
 533      */
 534     boolean invalidFrames;
 535 
 536     // ------------------------------------------------------------------------
 537     // Static initializer
 538     // ------------------------------------------------------------------------
 539 
 540     /**
 541      * Computes the instruction types of JVM opcodes.
 542      */
 543     static {
 544         int i;
 545         byte[] b = new byte[220];
 546         String s = "AAAAAAAAAAAAAAAABCLMMDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD"
 547                 + "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
 548                 + "AAAAAAAAAAAAAAAAANAAAAAAAAAAAAAAAAAAAAJJJJJJJJJJJJJJJJDOPAA"
 549                 + "AAAAGGGGGGGHIFBFAAFFAARQJJKKJJJJJJJJJJJJJJJJJJ";
 550         for (i = 0; i < b.length; ++i) {
 551             b[i] = (byte) (s.charAt(i) - 'A');
 552         }
 553         TYPE = b;
 554 
 555         // code to generate the above string
 556         //
 557         // // SBYTE_INSN instructions
 558         // b[Constants.NEWARRAY] = SBYTE_INSN;
 559         // b[Constants.BIPUSH] = SBYTE_INSN;
 560         //
 561         // // SHORT_INSN instructions
 562         // b[Constants.SIPUSH] = SHORT_INSN;
 563         //
 564         // // (IMPL)VAR_INSN instructions
 565         // b[Constants.RET] = VAR_INSN;
 566         // for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) {
 567         // b[i] = VAR_INSN;
 568         // }
 569         // for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) {
 570         // b[i] = VAR_INSN;
 571         // }
 572         // for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3
 573         // b[i] = IMPLVAR_INSN;
 574         // }
 575         // for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3
 576         // b[i] = IMPLVAR_INSN;
 577         // }
 578         //
 579         // // TYPE_INSN instructions
 580         // b[Constants.NEW] = TYPE_INSN;
 581         // b[Constants.ANEWARRAY] = TYPE_INSN;
 582         // b[Constants.CHECKCAST] = TYPE_INSN;
 583         // b[Constants.INSTANCEOF] = TYPE_INSN;
 584         //
 585         // // (Set)FIELDORMETH_INSN instructions
 586         // for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) {
 587         // b[i] = FIELDORMETH_INSN;
 588         // }
 589         // b[Constants.INVOKEINTERFACE] = ITFMETH_INSN;
 590         // b[Constants.INVOKEDYNAMIC] = INDYMETH_INSN;
 591         //
 592         // // LABEL(W)_INSN instructions
 593         // for (i = Constants.IFEQ; i <= Constants.JSR; ++i) {
 594         // b[i] = LABEL_INSN;
 595         // }
 596         // b[Constants.IFNULL] = LABEL_INSN;
 597         // b[Constants.IFNONNULL] = LABEL_INSN;
 598         // b[200] = LABELW_INSN; // GOTO_W
 599         // b[201] = LABELW_INSN; // JSR_W
 600         // // temporary opcodes used internally by ASM - see Label and
 601         // MethodWriter
 602         // for (i = 202; i < 220; ++i) {
 603         // b[i] = LABEL_INSN;
 604         // }
 605         //
 606         // // LDC(_W) instructions
 607         // b[Constants.LDC] = LDC_INSN;
 608         // b[19] = LDCW_INSN; // LDC_W
 609         // b[20] = LDCW_INSN; // LDC2_W
 610         //
 611         // // special instructions
 612         // b[Constants.IINC] = IINC_INSN;
 613         // b[Constants.TABLESWITCH] = TABL_INSN;
 614         // b[Constants.LOOKUPSWITCH] = LOOK_INSN;
 615         // b[Constants.MULTIANEWARRAY] = MANA_INSN;
 616         // b[196] = WIDE_INSN; // WIDE
 617         //
 618         // for (i = 0; i < b.length; ++i) {
 619         // System.err.print((char)('A' + b[i]));
 620         // }
 621         // System.err.println();
 622     }
 623 
 624     // ------------------------------------------------------------------------
 625     // Constructor
 626     // ------------------------------------------------------------------------
 627 
 628     /**
 629      * Constructs a new {@link ClassWriter} object.
 630      *
 631      * @param flags
 632      *            option flags that can be used to modify the default behavior
 633      *            of this class. See {@link #COMPUTE_MAXS},
 634      *            {@link #COMPUTE_FRAMES}.
 635      */
 636     public ClassWriter(final int flags) {
 637         super(Opcodes.ASM5);
 638         index = 1;
 639         pool = new ByteVector();
 640         items = new Item[256];
 641         threshold = (int) (0.75d * items.length);
 642         key = new Item();
 643         key2 = new Item();
 644         key3 = new Item();
 645         key4 = new Item();
 646         this.computeMaxs = (flags & COMPUTE_MAXS) != 0;
 647         this.computeFrames = (flags & COMPUTE_FRAMES) != 0;
 648     }
 649 
 650     /**
 651      * Constructs a new {@link ClassWriter} object and enables optimizations for
 652      * "mostly add" bytecode transformations. These optimizations are the
 653      * following:
 654      *
 655      * <ul>
 656      * <li>The constant pool from the original class is copied as is in the new
 657      * class, which saves time. New constant pool entries will be added at the
 658      * end if necessary, but unused constant pool entries <i>won't be
 659      * removed</i>.</li>
 660      * <li>Methods that are not transformed are copied as is in the new class,
 661      * directly from the original class bytecode (i.e. without emitting visit
 662      * events for all the method instructions), which saves a <i>lot</i> of
 663      * time. Untransformed methods are detected by the fact that the
 664      * {@link ClassReader} receives {@link MethodVisitor} objects that come from
 665      * a {@link ClassWriter} (and not from any other {@link ClassVisitor}
 666      * instance).</li>
 667      * </ul>
 668      *
 669      * @param classReader
 670      *            the {@link ClassReader} used to read the original class. It
 671      *            will be used to copy the entire constant pool from the
 672      *            original class and also to copy other fragments of original
 673      *            bytecode where applicable.
 674      * @param flags
 675      *            option flags that can be used to modify the default behavior
 676      *            of this class. <i>These option flags do not affect methods
 677      *            that are copied as is in the new class. This means that the
 678      *            maximum stack size nor the stack frames will be computed for
 679      *            these methods</i>. See {@link #COMPUTE_MAXS},
 680      *            {@link #COMPUTE_FRAMES}.
 681      */
 682     public ClassWriter(final ClassReader classReader, final int flags) {
 683         this(flags);
 684         classReader.copyPool(this);
 685         this.cr = classReader;
 686     }
 687 
 688     // ------------------------------------------------------------------------
 689     // Implementation of the ClassVisitor abstract class
 690     // ------------------------------------------------------------------------
 691 
 692     @Override
 693     public final void visit(final int version, final int access,
 694             final String name, final String signature, final String superName,
 695             final String[] interfaces) {
 696         this.version = version;
 697         this.access = access;
 698         this.name = newClass(name);
 699         thisName = name;
 700         if (ClassReader.SIGNATURES && signature != null) {
 701             this.signature = newUTF8(signature);
 702         }
 703         this.superName = superName == null ? 0 : newClass(superName);
 704         if (interfaces != null && interfaces.length > 0) {
 705             interfaceCount = interfaces.length;
 706             this.interfaces = new int[interfaceCount];
 707             for (int i = 0; i < interfaceCount; ++i) {
 708                 this.interfaces[i] = newClass(interfaces[i]);
 709             }
 710         }
 711     }
 712 
 713     @Override
 714     public final void visitSource(final String file, final String debug) {
 715         if (file != null) {
 716             sourceFile = newUTF8(file);
 717         }
 718         if (debug != null) {
 719             sourceDebug = new ByteVector().encodeUTF8(debug, 0,
 720                     Integer.MAX_VALUE);
 721         }
 722     }
 723 
 724     @Override
 725     public final void visitOuterClass(final String owner, final String name,
 726             final String desc) {
 727         enclosingMethodOwner = newClass(owner);
 728         if (name != null && desc != null) {
 729             enclosingMethod = newNameType(name, desc);
 730         }
 731     }
 732 
 733     @Override
 734     public final AnnotationVisitor visitAnnotation(final String desc,
 735             final boolean visible) {
 736         if (!ClassReader.ANNOTATIONS) {
 737             return null;
 738         }
 739         ByteVector bv = new ByteVector();
 740         // write type, and reserve space for values count
 741         bv.putShort(newUTF8(desc)).putShort(0);
 742         AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, 2);
 743         if (visible) {
 744             aw.next = anns;
 745             anns = aw;
 746         } else {
 747             aw.next = ianns;
 748             ianns = aw;
 749         }
 750         return aw;
 751     }
 752 
 753     @Override
 754     public final AnnotationVisitor visitTypeAnnotation(int typeRef,
 755             TypePath typePath, final String desc, final boolean visible) {
 756         if (!ClassReader.ANNOTATIONS) {
 757             return null;
 758         }
 759         ByteVector bv = new ByteVector();
 760         // write target_type and target_info
 761         AnnotationWriter.putTarget(typeRef, typePath, bv);
 762         // write type, and reserve space for values count
 763         bv.putShort(newUTF8(desc)).putShort(0);
 764         AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv,
 765                 bv.length - 2);
 766         if (visible) {
 767             aw.next = tanns;
 768             tanns = aw;
 769         } else {
 770             aw.next = itanns;
 771             itanns = aw;
 772         }
 773         return aw;
 774     }
 775 
 776     @Override
 777     public final void visitAttribute(final Attribute attr) {
 778         attr.next = attrs;
 779         attrs = attr;
 780     }
 781 
 782     @Override
 783     public final void visitInnerClass(final String name,
 784             final String outerName, final String innerName, final int access) {
 785         if (innerClasses == null) {
 786             innerClasses = new ByteVector();
 787         }
 788         ++innerClassesCount;
 789         innerClasses.putShort(name == null ? 0 : newClass(name));
 790         innerClasses.putShort(outerName == null ? 0 : newClass(outerName));
 791         innerClasses.putShort(innerName == null ? 0 : newUTF8(innerName));
 792         innerClasses.putShort(access);
 793     }
 794 
 795     @Override
 796     public final FieldVisitor visitField(final int access, final String name,
 797             final String desc, final String signature, final Object value) {
 798         return new FieldWriter(this, access, name, desc, signature, value);
 799     }
 800 
 801     @Override
 802     public final MethodVisitor visitMethod(final int access, final String name,
 803             final String desc, final String signature, final String[] exceptions) {
 804         return new MethodWriter(this, access, name, desc, signature,
 805                 exceptions, computeMaxs, computeFrames);
 806     }
 807 
 808     @Override
 809     public final void visitEnd() {
 810     }
 811 
 812     // ------------------------------------------------------------------------
 813     // Other public methods
 814     // ------------------------------------------------------------------------
 815 
 816     /**
 817      * Returns the bytecode of the class that was build with this class writer.
 818      *
 819      * @return the bytecode of the class that was build with this class writer.
 820      */
 821     public byte[] toByteArray() {
 822         if (index > 0xFFFF) {
 823             throw new RuntimeException("Class file too large!");
 824         }
 825         // computes the real size of the bytecode of this class
 826         int size = 24 + 2 * interfaceCount;
 827         int nbFields = 0;
 828         FieldWriter fb = firstField;
 829         while (fb != null) {
 830             ++nbFields;
 831             size += fb.getSize();
 832             fb = (FieldWriter) fb.fv;
 833         }
 834         int nbMethods = 0;
 835         MethodWriter mb = firstMethod;
 836         while (mb != null) {
 837             ++nbMethods;
 838             size += mb.getSize();
 839             mb = (MethodWriter) mb.mv;
 840         }
 841         int attributeCount = 0;
 842         if (bootstrapMethods != null) {
 843             // we put it as first attribute in order to improve a bit
 844             // ClassReader.copyBootstrapMethods
 845             ++attributeCount;
 846             size += 8 + bootstrapMethods.length;
 847             newUTF8("BootstrapMethods");
 848         }
 849         if (ClassReader.SIGNATURES && signature != 0) {
 850             ++attributeCount;
 851             size += 8;
 852             newUTF8("Signature");
 853         }
 854         if (sourceFile != 0) {
 855             ++attributeCount;
 856             size += 8;
 857             newUTF8("SourceFile");
 858         }
 859         if (sourceDebug != null) {
 860             ++attributeCount;
 861             size += sourceDebug.length + 6;
 862             newUTF8("SourceDebugExtension");
 863         }
 864         if (enclosingMethodOwner != 0) {
 865             ++attributeCount;
 866             size += 10;
 867             newUTF8("EnclosingMethod");
 868         }
 869         if ((access & Opcodes.ACC_DEPRECATED) != 0) {
 870             ++attributeCount;
 871             size += 6;
 872             newUTF8("Deprecated");
 873         }
 874         if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
 875             if ((version & 0xFFFF) < Opcodes.V1_5
 876                     || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) {
 877                 ++attributeCount;
 878                 size += 6;
 879                 newUTF8("Synthetic");
 880             }
 881         }
 882         if (innerClasses != null) {
 883             ++attributeCount;
 884             size += 8 + innerClasses.length;
 885             newUTF8("InnerClasses");
 886         }
 887         if (ClassReader.ANNOTATIONS && anns != null) {
 888             ++attributeCount;
 889             size += 8 + anns.getSize();
 890             newUTF8("RuntimeVisibleAnnotations");
 891         }
 892         if (ClassReader.ANNOTATIONS && ianns != null) {
 893             ++attributeCount;
 894             size += 8 + ianns.getSize();
 895             newUTF8("RuntimeInvisibleAnnotations");
 896         }
 897         if (ClassReader.ANNOTATIONS && tanns != null) {
 898             ++attributeCount;
 899             size += 8 + tanns.getSize();
 900             newUTF8("RuntimeVisibleTypeAnnotations");
 901         }
 902         if (ClassReader.ANNOTATIONS && itanns != null) {
 903             ++attributeCount;
 904             size += 8 + itanns.getSize();
 905             newUTF8("RuntimeInvisibleTypeAnnotations");
 906         }
 907         if (attrs != null) {
 908             attributeCount += attrs.getCount();
 909             size += attrs.getSize(this, null, 0, -1, -1);
 910         }
 911         size += pool.length;
 912         // allocates a byte vector of this size, in order to avoid unnecessary
 913         // arraycopy operations in the ByteVector.enlarge() method
 914         ByteVector out = new ByteVector(size);
 915         out.putInt(0xCAFEBABE).putInt(version);
 916         out.putShort(index).putByteArray(pool.data, 0, pool.length);
 917         int mask = Opcodes.ACC_DEPRECATED | ACC_SYNTHETIC_ATTRIBUTE
 918                 | ((access & ACC_SYNTHETIC_ATTRIBUTE) / TO_ACC_SYNTHETIC);
 919         out.putShort(access & ~mask).putShort(name).putShort(superName);
 920         out.putShort(interfaceCount);
 921         for (int i = 0; i < interfaceCount; ++i) {
 922             out.putShort(interfaces[i]);
 923         }
 924         out.putShort(nbFields);
 925         fb = firstField;
 926         while (fb != null) {
 927             fb.put(out);
 928             fb = (FieldWriter) fb.fv;
 929         }
 930         out.putShort(nbMethods);
 931         mb = firstMethod;
 932         while (mb != null) {
 933             mb.put(out);
 934             mb = (MethodWriter) mb.mv;
 935         }
 936         out.putShort(attributeCount);
 937         if (bootstrapMethods != null) {
 938             out.putShort(newUTF8("BootstrapMethods"));
 939             out.putInt(bootstrapMethods.length + 2).putShort(
 940                     bootstrapMethodsCount);
 941             out.putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);
 942         }
 943         if (ClassReader.SIGNATURES && signature != 0) {
 944             out.putShort(newUTF8("Signature")).putInt(2).putShort(signature);
 945         }
 946         if (sourceFile != 0) {
 947             out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile);
 948         }
 949         if (sourceDebug != null) {
 950             int len = sourceDebug.length;
 951             out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
 952             out.putByteArray(sourceDebug.data, 0, len);
 953         }
 954         if (enclosingMethodOwner != 0) {
 955             out.putShort(newUTF8("EnclosingMethod")).putInt(4);
 956             out.putShort(enclosingMethodOwner).putShort(enclosingMethod);
 957         }
 958         if ((access & Opcodes.ACC_DEPRECATED) != 0) {
 959             out.putShort(newUTF8("Deprecated")).putInt(0);
 960         }
 961         if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
 962             if ((version & 0xFFFF) < Opcodes.V1_5
 963                     || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) {
 964                 out.putShort(newUTF8("Synthetic")).putInt(0);
 965             }
 966         }
 967         if (innerClasses != null) {
 968             out.putShort(newUTF8("InnerClasses"));
 969             out.putInt(innerClasses.length + 2).putShort(innerClassesCount);
 970             out.putByteArray(innerClasses.data, 0, innerClasses.length);
 971         }
 972         if (ClassReader.ANNOTATIONS && anns != null) {
 973             out.putShort(newUTF8("RuntimeVisibleAnnotations"));
 974             anns.put(out);
 975         }
 976         if (ClassReader.ANNOTATIONS && ianns != null) {
 977             out.putShort(newUTF8("RuntimeInvisibleAnnotations"));
 978             ianns.put(out);
 979         }
 980         if (ClassReader.ANNOTATIONS && tanns != null) {
 981             out.putShort(newUTF8("RuntimeVisibleTypeAnnotations"));
 982             tanns.put(out);
 983         }
 984         if (ClassReader.ANNOTATIONS && itanns != null) {
 985             out.putShort(newUTF8("RuntimeInvisibleTypeAnnotations"));
 986             itanns.put(out);
 987         }
 988         if (attrs != null) {
 989             attrs.put(this, null, 0, -1, -1, out);
 990         }
 991         if (invalidFrames) {
 992             anns = null;
 993             ianns = null;
 994             attrs = null;
 995             innerClassesCount = 0;
 996             innerClasses = null;
 997             bootstrapMethodsCount = 0;
 998             bootstrapMethods = null;
 999             firstField = null;
1000             lastField = null;
1001             firstMethod = null;
1002             lastMethod = null;
1003             computeMaxs = false;
1004             computeFrames = true;
1005             invalidFrames = false;
1006             new ClassReader(out.data).accept(this, ClassReader.SKIP_FRAMES);
1007             return toByteArray();
1008         }
1009         return out.data;
1010     }
1011 
1012     // ------------------------------------------------------------------------
1013     // Utility methods: constant pool management
1014     // ------------------------------------------------------------------------
1015 
1016     /**
1017      * Adds a number or string constant to the constant pool of the class being
1018      * build. Does nothing if the constant pool already contains a similar item.
1019      *
1020      * @param cst
1021      *            the value of the constant to be added to the constant pool.
1022      *            This parameter must be an {@link Integer}, a {@link Float}, a
1023      *            {@link Long}, a {@link Double}, a {@link String} or a
1024      *            {@link Type}.
1025      * @return a new or already existing constant item with the given value.
1026      */
1027     Item newConstItem(final Object cst) {
1028         if (cst instanceof Integer) {
1029             int val = ((Integer) cst).intValue();
1030             return newInteger(val);
1031         } else if (cst instanceof Byte) {
1032             int val = ((Byte) cst).intValue();
1033             return newInteger(val);
1034         } else if (cst instanceof Character) {
1035             int val = ((Character) cst).charValue();
1036             return newInteger(val);
1037         } else if (cst instanceof Short) {
1038             int val = ((Short) cst).intValue();
1039             return newInteger(val);
1040         } else if (cst instanceof Boolean) {
1041             int val = ((Boolean) cst).booleanValue() ? 1 : 0;
1042             return newInteger(val);
1043         } else if (cst instanceof Float) {
1044             float val = ((Float) cst).floatValue();
1045             return newFloat(val);
1046         } else if (cst instanceof Long) {
1047             long val = ((Long) cst).longValue();
1048             return newLong(val);
1049         } else if (cst instanceof Double) {
1050             double val = ((Double) cst).doubleValue();
1051             return newDouble(val);
1052         } else if (cst instanceof String) {
1053             return newString((String) cst);
1054         } else if (cst instanceof Type) {
1055             Type t = (Type) cst;
1056             int s = t.getSort();
1057             if (s == Type.OBJECT) {
1058                 return newClassItem(t.getInternalName());
1059             } else if (s == Type.METHOD) {
1060                 return newMethodTypeItem(t.getDescriptor());
1061             } else { // s == primitive type or array
1062                 return newClassItem(t.getDescriptor());
1063             }
1064         } else if (cst instanceof Handle) {
1065             Handle h = (Handle) cst;
1066             return newHandleItem(h.tag, h.owner, h.name, h.desc);
1067         } else {
1068             throw new IllegalArgumentException("value " + cst);
1069         }
1070     }
1071 
1072     /**
1073      * Adds a number or string constant to the constant pool of the class being
1074      * build. Does nothing if the constant pool already contains a similar item.
1075      * <i>This method is intended for {@link Attribute} sub classes, and is
1076      * normally not needed by class generators or adapters.</i>
1077      *
1078      * @param cst
1079      *            the value of the constant to be added to the constant pool.
1080      *            This parameter must be an {@link Integer}, a {@link Float}, a
1081      *            {@link Long}, a {@link Double} or a {@link String}.
1082      * @return the index of a new or already existing constant item with the
1083      *         given value.
1084      */
1085     public int newConst(final Object cst) {
1086         return newConstItem(cst).index;
1087     }
1088 
1089     /**
1090      * Adds an UTF8 string to the constant pool of the class being build. Does
1091      * nothing if the constant pool already contains a similar item. <i>This
1092      * method is intended for {@link Attribute} sub classes, and is normally not
1093      * needed by class generators or adapters.</i>
1094      *
1095      * @param value
1096      *            the String value.
1097      * @return the index of a new or already existing UTF8 item.
1098      */
1099     public int newUTF8(final String value) {
1100         key.set(UTF8, value, null, null);
1101         Item result = get(key);
1102         if (result == null) {
1103             pool.putByte(UTF8).putUTF8(value);
1104             result = new Item(index++, key);
1105             put(result);
1106         }
1107         return result.index;
1108     }
1109 
1110     /**
1111      * Adds a class reference to the constant pool of the class being build.
1112      * Does nothing if the constant pool already contains a similar item.
1113      * <i>This method is intended for {@link Attribute} sub classes, and is
1114      * normally not needed by class generators or adapters.</i>
1115      *
1116      * @param value
1117      *            the internal name of the class.
1118      * @return a new or already existing class reference item.
1119      */
1120     Item newClassItem(final String value) {
1121         key2.set(CLASS, value, null, null);
1122         Item result = get(key2);
1123         if (result == null) {
1124             pool.put12(CLASS, newUTF8(value));
1125             result = new Item(index++, key2);
1126             put(result);
1127         }
1128         return result;
1129     }
1130 
1131     /**
1132      * Adds a class reference to the constant pool of the class being build.
1133      * Does nothing if the constant pool already contains a similar item.
1134      * <i>This method is intended for {@link Attribute} sub classes, and is
1135      * normally not needed by class generators or adapters.</i>
1136      *
1137      * @param value
1138      *            the internal name of the class.
1139      * @return the index of a new or already existing class reference item.
1140      */
1141     public int newClass(final String value) {
1142         return newClassItem(value).index;
1143     }
1144 
1145     /**
1146      * Adds a method type reference to the constant pool of the class being
1147      * build. Does nothing if the constant pool already contains a similar item.
1148      * <i>This method is intended for {@link Attribute} sub classes, and is
1149      * normally not needed by class generators or adapters.</i>
1150      *
1151      * @param methodDesc
1152      *            method descriptor of the method type.
1153      * @return a new or already existing method type reference item.
1154      */
1155     Item newMethodTypeItem(final String methodDesc) {
1156         key2.set(MTYPE, methodDesc, null, null);
1157         Item result = get(key2);
1158         if (result == null) {
1159             pool.put12(MTYPE, newUTF8(methodDesc));
1160             result = new Item(index++, key2);
1161             put(result);
1162         }
1163         return result;
1164     }
1165 
1166     /**
1167      * Adds a method type reference to the constant pool of the class being
1168      * build. Does nothing if the constant pool already contains a similar item.
1169      * <i>This method is intended for {@link Attribute} sub classes, and is
1170      * normally not needed by class generators or adapters.</i>
1171      *
1172      * @param methodDesc
1173      *            method descriptor of the method type.
1174      * @return the index of a new or already existing method type reference
1175      *         item.
1176      */
1177     public int newMethodType(final String methodDesc) {
1178         return newMethodTypeItem(methodDesc).index;
1179     }
1180 
1181     /**
1182      * Adds a handle to the constant pool of the class being build. Does nothing
1183      * if the constant pool already contains a similar item. <i>This method is
1184      * intended for {@link Attribute} sub classes, and is normally not needed by
1185      * class generators or adapters.</i>
1186      *
1187      * @param tag
1188      *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
1189      *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
1190      *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
1191      *            {@link Opcodes#H_INVOKESTATIC},
1192      *            {@link Opcodes#H_INVOKESPECIAL},
1193      *            {@link Opcodes#H_NEWINVOKESPECIAL} or
1194      *            {@link Opcodes#H_INVOKEINTERFACE}.
1195      * @param owner
1196      *            the internal name of the field or method owner class.
1197      * @param name
1198      *            the name of the field or method.
1199      * @param desc
1200      *            the descriptor of the field or method.
1201      * @return a new or an already existing method type reference item.
1202      */
1203     Item newHandleItem(final int tag, final String owner, final String name,
1204             final String desc) {
1205         key4.set(HANDLE_BASE + tag, owner, name, desc);
1206         Item result = get(key4);
1207         if (result == null) {
1208             if (tag <= Opcodes.H_PUTSTATIC) {
1209                 put112(HANDLE, tag, newField(owner, name, desc));
1210             } else {
1211                 put112(HANDLE,
1212                         tag,
1213                         newMethod(owner, name, desc,
1214                                 tag == Opcodes.H_INVOKEINTERFACE));
1215             }
1216             result = new Item(index++, key4);
1217             put(result);
1218         }
1219         return result;
1220     }
1221 
1222     /**
1223      * Adds a handle to the constant pool of the class being build. Does nothing
1224      * if the constant pool already contains a similar item. <i>This method is
1225      * intended for {@link Attribute} sub classes, and is normally not needed by
1226      * class generators or adapters.</i>
1227      *
1228      * @param tag
1229      *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
1230      *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
1231      *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
1232      *            {@link Opcodes#H_INVOKESTATIC},
1233      *            {@link Opcodes#H_INVOKESPECIAL},
1234      *            {@link Opcodes#H_NEWINVOKESPECIAL} or
1235      *            {@link Opcodes#H_INVOKEINTERFACE}.
1236      * @param owner
1237      *            the internal name of the field or method owner class.
1238      * @param name
1239      *            the name of the field or method.
1240      * @param desc
1241      *            the descriptor of the field or method.
1242      * @return the index of a new or already existing method type reference
1243      *         item.
1244      */
1245     public int newHandle(final int tag, final String owner, final String name,
1246             final String desc) {
1247         return newHandleItem(tag, owner, name, desc).index;
1248     }
1249 
1250     /**
1251      * Adds an invokedynamic reference to the constant pool of the class being
1252      * build. Does nothing if the constant pool already contains a similar item.
1253      * <i>This method is intended for {@link Attribute} sub classes, and is
1254      * normally not needed by class generators or adapters.</i>
1255      *
1256      * @param name
1257      *            name of the invoked method.
1258      * @param desc
1259      *            descriptor of the invoke method.
1260      * @param bsm
1261      *            the bootstrap method.
1262      * @param bsmArgs
1263      *            the bootstrap method constant arguments.
1264      *
1265      * @return a new or an already existing invokedynamic type reference item.
1266      */
1267     Item newInvokeDynamicItem(final String name, final String desc,
1268             final Handle bsm, final Object... bsmArgs) {
1269         // cache for performance
1270         ByteVector bootstrapMethods = this.bootstrapMethods;
1271         if (bootstrapMethods == null) {
1272             bootstrapMethods = this.bootstrapMethods = new ByteVector();
1273         }
1274 
1275         int position = bootstrapMethods.length; // record current position
1276 
1277         int hashCode = bsm.hashCode();
1278         bootstrapMethods.putShort(newHandle(bsm.tag, bsm.owner, bsm.name,
1279                 bsm.desc));
1280 
1281         int argsLength = bsmArgs.length;
1282         bootstrapMethods.putShort(argsLength);
1283 
1284         for (int i = 0; i < argsLength; i++) {
1285             Object bsmArg = bsmArgs[i];
1286             hashCode ^= bsmArg.hashCode();
1287             bootstrapMethods.putShort(newConst(bsmArg));
1288         }
1289 
1290         byte[] data = bootstrapMethods.data;
1291         int length = (1 + 1 + argsLength) << 1; // (bsm + argCount + arguments)
1292         hashCode &= 0x7FFFFFFF;
1293         Item result = items[hashCode % items.length];
1294         loop: while (result != null) {
1295             if (result.type != BSM || result.hashCode != hashCode) {
1296                 result = result.next;
1297                 continue;
1298             }
1299 
1300             // because the data encode the size of the argument
1301             // we don't need to test if these size are equals
1302             int resultPosition = result.intVal;
1303             for (int p = 0; p < length; p++) {
1304                 if (data[position + p] != data[resultPosition + p]) {
1305                     result = result.next;
1306                     continue loop;
1307                 }
1308             }
1309             break;
1310         }
1311 
1312         int bootstrapMethodIndex;
1313         if (result != null) {
1314             bootstrapMethodIndex = result.index;
1315             bootstrapMethods.length = position; // revert to old position
1316         } else {
1317             bootstrapMethodIndex = bootstrapMethodsCount++;
1318             result = new Item(bootstrapMethodIndex);
1319             result.set(position, hashCode);
1320             put(result);
1321         }
1322 
1323         // now, create the InvokeDynamic constant
1324         key3.set(name, desc, bootstrapMethodIndex);
1325         result = get(key3);
1326         if (result == null) {
1327             put122(INDY, bootstrapMethodIndex, newNameType(name, desc));
1328             result = new Item(index++, key3);
1329             put(result);
1330         }
1331         return result;
1332     }
1333 
1334     /**
1335      * Adds an invokedynamic reference to the constant pool of the class being
1336      * build. Does nothing if the constant pool already contains a similar item.
1337      * <i>This method is intended for {@link Attribute} sub classes, and is
1338      * normally not needed by class generators or adapters.</i>
1339      *
1340      * @param name
1341      *            name of the invoked method.
1342      * @param desc
1343      *            descriptor of the invoke method.
1344      * @param bsm
1345      *            the bootstrap method.
1346      * @param bsmArgs
1347      *            the bootstrap method constant arguments.
1348      *
1349      * @return the index of a new or already existing invokedynamic reference
1350      *         item.
1351      */
1352     public int newInvokeDynamic(final String name, final String desc,
1353             final Handle bsm, final Object... bsmArgs) {
1354         return newInvokeDynamicItem(name, desc, bsm, bsmArgs).index;
1355     }
1356 
1357     /**
1358      * Adds a field reference to the constant pool of the class being build.
1359      * Does nothing if the constant pool already contains a similar item.
1360      *
1361      * @param owner
1362      *            the internal name of the field's owner class.
1363      * @param name
1364      *            the field's name.
1365      * @param desc
1366      *            the field's descriptor.
1367      * @return a new or already existing field reference item.
1368      */
1369     Item newFieldItem(final String owner, final String name, final String desc) {
1370         key3.set(FIELD, owner, name, desc);
1371         Item result = get(key3);
1372         if (result == null) {
1373             put122(FIELD, newClass(owner), newNameType(name, desc));
1374             result = new Item(index++, key3);
1375             put(result);
1376         }
1377         return result;
1378     }
1379 
1380     /**
1381      * Adds a field reference to the constant pool of the class being build.
1382      * Does nothing if the constant pool already contains a similar item.
1383      * <i>This method is intended for {@link Attribute} sub classes, and is
1384      * normally not needed by class generators or adapters.</i>
1385      *
1386      * @param owner
1387      *            the internal name of the field's owner class.
1388      * @param name
1389      *            the field's name.
1390      * @param desc
1391      *            the field's descriptor.
1392      * @return the index of a new or already existing field reference item.
1393      */
1394     public int newField(final String owner, final String name, final String desc) {
1395         return newFieldItem(owner, name, desc).index;
1396     }
1397 
1398     /**
1399      * Adds a method reference to the constant pool of the class being build.
1400      * Does nothing if the constant pool already contains a similar item.
1401      *
1402      * @param owner
1403      *            the internal name of the method's owner class.
1404      * @param name
1405      *            the method's name.
1406      * @param desc
1407      *            the method's descriptor.
1408      * @param itf
1409      *            <tt>true</tt> if <tt>owner</tt> is an interface.
1410      * @return a new or already existing method reference item.
1411      */
1412     Item newMethodItem(final String owner, final String name,
1413             final String desc, final boolean itf) {
1414         int type = itf ? IMETH : METH;
1415         key3.set(type, owner, name, desc);
1416         Item result = get(key3);
1417         if (result == null) {
1418             put122(type, newClass(owner), newNameType(name, desc));
1419             result = new Item(index++, key3);
1420             put(result);
1421         }
1422         return result;
1423     }
1424 
1425     /**
1426      * Adds a method reference to the constant pool of the class being build.
1427      * Does nothing if the constant pool already contains a similar item.
1428      * <i>This method is intended for {@link Attribute} sub classes, and is
1429      * normally not needed by class generators or adapters.</i>
1430      *
1431      * @param owner
1432      *            the internal name of the method's owner class.
1433      * @param name
1434      *            the method's name.
1435      * @param desc
1436      *            the method's descriptor.
1437      * @param itf
1438      *            <tt>true</tt> if <tt>owner</tt> is an interface.
1439      * @return the index of a new or already existing method reference item.
1440      */
1441     public int newMethod(final String owner, final String name,
1442             final String desc, final boolean itf) {
1443         return newMethodItem(owner, name, desc, itf).index;
1444     }
1445 
1446     /**
1447      * Adds an integer to the constant pool of the class being build. Does
1448      * nothing if the constant pool already contains a similar item.
1449      *
1450      * @param value
1451      *            the int value.
1452      * @return a new or already existing int item.
1453      */
1454     Item newInteger(final int value) {
1455         key.set(value);
1456         Item result = get(key);
1457         if (result == null) {
1458             pool.putByte(INT).putInt(value);
1459             result = new Item(index++, key);
1460             put(result);
1461         }
1462         return result;
1463     }
1464 
1465     /**
1466      * Adds a float to the constant pool of the class being build. Does nothing
1467      * if the constant pool already contains a similar item.
1468      *
1469      * @param value
1470      *            the float value.
1471      * @return a new or already existing float item.
1472      */
1473     Item newFloat(final float value) {
1474         key.set(value);
1475         Item result = get(key);
1476         if (result == null) {
1477             pool.putByte(FLOAT).putInt(key.intVal);
1478             result = new Item(index++, key);
1479             put(result);
1480         }
1481         return result;
1482     }
1483 
1484     /**
1485      * Adds a long to the constant pool of the class being build. Does nothing
1486      * if the constant pool already contains a similar item.
1487      *
1488      * @param value
1489      *            the long value.
1490      * @return a new or already existing long item.
1491      */
1492     Item newLong(final long value) {
1493         key.set(value);
1494         Item result = get(key);
1495         if (result == null) {
1496             pool.putByte(LONG).putLong(value);
1497             result = new Item(index, key);
1498             index += 2;
1499             put(result);
1500         }
1501         return result;
1502     }
1503 
1504     /**
1505      * Adds a double to the constant pool of the class being build. Does nothing
1506      * if the constant pool already contains a similar item.
1507      *
1508      * @param value
1509      *            the double value.
1510      * @return a new or already existing double item.
1511      */
1512     Item newDouble(final double value) {
1513         key.set(value);
1514         Item result = get(key);
1515         if (result == null) {
1516             pool.putByte(DOUBLE).putLong(key.longVal);
1517             result = new Item(index, key);
1518             index += 2;
1519             put(result);
1520         }
1521         return result;
1522     }
1523 
1524     /**
1525      * Adds a string to the constant pool of the class being build. Does nothing
1526      * if the constant pool already contains a similar item.
1527      *
1528      * @param value
1529      *            the String value.
1530      * @return a new or already existing string item.
1531      */
1532     private Item newString(final String value) {
1533         key2.set(STR, value, null, null);
1534         Item result = get(key2);
1535         if (result == null) {
1536             pool.put12(STR, newUTF8(value));
1537             result = new Item(index++, key2);
1538             put(result);
1539         }
1540         return result;
1541     }
1542 
1543     /**
1544      * Adds a name and type to the constant pool of the class being build. Does
1545      * nothing if the constant pool already contains a similar item. <i>This
1546      * method is intended for {@link Attribute} sub classes, and is normally not
1547      * needed by class generators or adapters.</i>
1548      *
1549      * @param name
1550      *            a name.
1551      * @param desc
1552      *            a type descriptor.
1553      * @return the index of a new or already existing name and type item.
1554      */
1555     public int newNameType(final String name, final String desc) {
1556         return newNameTypeItem(name, desc).index;
1557     }
1558 
1559     /**
1560      * Adds a name and type to the constant pool of the class being build. Does
1561      * nothing if the constant pool already contains a similar item.
1562      *
1563      * @param name
1564      *            a name.
1565      * @param desc
1566      *            a type descriptor.
1567      * @return a new or already existing name and type item.
1568      */
1569     Item newNameTypeItem(final String name, final String desc) {
1570         key2.set(NAME_TYPE, name, desc, null);
1571         Item result = get(key2);
1572         if (result == null) {
1573             put122(NAME_TYPE, newUTF8(name), newUTF8(desc));
1574             result = new Item(index++, key2);
1575             put(result);
1576         }
1577         return result;
1578     }
1579 
1580     /**
1581      * Adds the given internal name to {@link #typeTable} and returns its index.
1582      * Does nothing if the type table already contains this internal name.
1583      *
1584      * @param type
1585      *            the internal name to be added to the type table.
1586      * @return the index of this internal name in the type table.
1587      */
1588     int addType(final String type) {
1589         key.set(TYPE_NORMAL, type, null, null);
1590         Item result = get(key);
1591         if (result == null) {
1592             result = addType(key);
1593         }
1594         return result.index;
1595     }
1596 
1597     /**
1598      * Adds the given "uninitialized" type to {@link #typeTable} and returns its
1599      * index. This method is used for UNINITIALIZED types, made of an internal
1600      * name and a bytecode offset.
1601      *
1602      * @param type
1603      *            the internal name to be added to the type table.
1604      * @param offset
1605      *            the bytecode offset of the NEW instruction that created this
1606      *            UNINITIALIZED type value.
1607      * @return the index of this internal name in the type table.
1608      */
1609     int addUninitializedType(final String type, final int offset) {
1610         key.type = TYPE_UNINIT;
1611         key.intVal = offset;
1612         key.strVal1 = type;
1613         key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset);
1614         Item result = get(key);
1615         if (result == null) {
1616             result = addType(key);
1617         }
1618         return result.index;
1619     }
1620 
1621     /**
1622      * Adds the given Item to {@link #typeTable}.
1623      *
1624      * @param item
1625      *            the value to be added to the type table.
1626      * @return the added Item, which a new Item instance with the same value as
1627      *         the given Item.
1628      */
1629     private Item addType(final Item item) {
1630         ++typeCount;
1631         Item result = new Item(typeCount, key);
1632         put(result);
1633         if (typeTable == null) {
1634             typeTable = new Item[16];
1635         }
1636         if (typeCount == typeTable.length) {
1637             Item[] newTable = new Item[2 * typeTable.length];
1638             System.arraycopy(typeTable, 0, newTable, 0, typeTable.length);
1639             typeTable = newTable;
1640         }
1641         typeTable[typeCount] = result;
1642         return result;
1643     }
1644 
1645     /**
1646      * Returns the index of the common super type of the two given types. This
1647      * method calls {@link #getCommonSuperClass} and caches the result in the
1648      * {@link #items} hash table to speedup future calls with the same
1649      * parameters.
1650      *
1651      * @param type1
1652      *            index of an internal name in {@link #typeTable}.
1653      * @param type2
1654      *            index of an internal name in {@link #typeTable}.
1655      * @return the index of the common super type of the two given types.
1656      */
1657     int getMergedType(final int type1, final int type2) {
1658         key2.type = TYPE_MERGED;
1659         key2.longVal = type1 | (((long) type2) << 32);
1660         key2.hashCode = 0x7FFFFFFF & (TYPE_MERGED + type1 + type2);
1661         Item result = get(key2);
1662         if (result == null) {
1663             String t = typeTable[type1].strVal1;
1664             String u = typeTable[type2].strVal1;
1665             key2.intVal = addType(getCommonSuperClass(t, u));
1666             result = new Item((short) 0, key2);
1667             put(result);
1668         }
1669         return result.intVal;
1670     }
1671 
1672     /**
1673      * Returns the common super type of the two given types. The default
1674      * implementation of this method <i>loads</i> the two given classes and uses
1675      * the java.lang.Class methods to find the common super class. It can be
1676      * overridden to compute this common super type in other ways, in particular
1677      * without actually loading any class, or to take into account the class
1678      * that is currently being generated by this ClassWriter, which can of
1679      * course not be loaded since it is under construction.
1680      *
1681      * @param type1
1682      *            the internal name of a class.
1683      * @param type2
1684      *            the internal name of another class.
1685      * @return the internal name of the common super class of the two given
1686      *         classes.
1687      */
1688     protected String getCommonSuperClass(final String type1, final String type2) {
1689         Class<?> c, d;
1690         ClassLoader classLoader = getClass().getClassLoader();
1691         try {
1692             c = Class.forName(type1.replace('/', '.'), false, classLoader);
1693             d = Class.forName(type2.replace('/', '.'), false, classLoader);
1694         } catch (Exception e) {
1695             throw new RuntimeException(e.toString());
1696         }
1697         if (c.isAssignableFrom(d)) {
1698             return type1;
1699         }
1700         if (d.isAssignableFrom(c)) {
1701             return type2;
1702         }
1703         if (c.isInterface() || d.isInterface()) {
1704             return "java/lang/Object";
1705         } else {
1706             do {
1707                 c = c.getSuperclass();
1708             } while (!c.isAssignableFrom(d));
1709             return c.getName().replace('.', '/');
1710         }
1711     }
1712 
1713     /**
1714      * Returns the constant pool's hash table item which is equal to the given
1715      * item.
1716      *
1717      * @param key
1718      *            a constant pool item.
1719      * @return the constant pool's hash table item which is equal to the given
1720      *         item, or <tt>null</tt> if there is no such item.
1721      */
1722     private Item get(final Item key) {
1723         Item i = items[key.hashCode % items.length];
1724         while (i != null && (i.type != key.type || !key.isEqualTo(i))) {
1725             i = i.next;
1726         }
1727         return i;
1728     }
1729 
1730     /**
1731      * Puts the given item in the constant pool's hash table. The hash table
1732      * <i>must</i> not already contains this item.
1733      *
1734      * @param i
1735      *            the item to be added to the constant pool's hash table.
1736      */
1737     private void put(final Item i) {
1738         if (index + typeCount > threshold) {
1739             int ll = items.length;
1740             int nl = ll * 2 + 1;
1741             Item[] newItems = new Item[nl];
1742             for (int l = ll - 1; l >= 0; --l) {
1743                 Item j = items[l];
1744                 while (j != null) {
1745                     int index = j.hashCode % newItems.length;
1746                     Item k = j.next;
1747                     j.next = newItems[index];
1748                     newItems[index] = j;
1749                     j = k;
1750                 }
1751             }
1752             items = newItems;
1753             threshold = (int) (nl * 0.75);
1754         }
1755         int index = i.hashCode % items.length;
1756         i.next = items[index];
1757         items[index] = i;
1758     }
1759 
1760     /**
1761      * Puts one byte and two shorts into the constant pool.
1762      *
1763      * @param b
1764      *            a byte.
1765      * @param s1
1766      *            a short.
1767      * @param s2
1768      *            another short.
1769      */
1770     private void put122(final int b, final int s1, final int s2) {
1771         pool.put12(b, s1).putShort(s2);
1772     }
1773 
1774     /**
1775      * Puts two bytes and one short into the constant pool.
1776      *
1777      * @param b1
1778      *            a byte.
1779      * @param b2
1780      *            another byte.
1781      * @param s
1782      *            a short.
1783      */
1784     private void put112(final int b1, final int b2, final int s) {
1785         pool.put11(b1, b2).putShort(s);
1786     }
1787 }