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 
  60 package jdk.internal.org.objectweb.asm;
  61 
  62 /**
  63  * A {@link MethodVisitor} that generates a corresponding 'method_info' structure, as defined in the
  64  * Java Virtual Machine Specification (JVMS).
  65  *
  66  * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.6">JVMS
  67  *     4.6</a>
  68  * @author Eric Bruneton
  69  * @author Eugene Kuleshov
  70  */
  71 final class MethodWriter extends MethodVisitor {
  72 
  73     /** Indicates that nothing must be computed. */
  74     static final int COMPUTE_NOTHING = 0;
  75 
  76     /**
  77       * Indicates that the maximum stack size and the maximum number of local variables must be
  78       * computed, from scratch.
  79       */
  80     static final int COMPUTE_MAX_STACK_AND_LOCAL = 1;
  81 
  82     /**
  83       * Indicates that the maximum stack size and the maximum number of local variables must be
  84       * computed, from the existing stack map frames. This can be done more efficiently than with the
  85       * control flow graph algorithm used for {@link #COMPUTE_MAX_STACK_AND_LOCAL}, by using a linear
  86       * scan of the bytecode instructions.
  87       */
  88     static final int COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES = 2;
  89 
  90     /**
  91       * Indicates that the stack map frames of type F_INSERT must be computed. The other frames are not
  92       * computed. They should all be of type F_NEW and should be sufficient to compute the content of
  93       * the F_INSERT frames, together with the bytecode instructions between a F_NEW and a F_INSERT
  94       * frame - and without any knowledge of the type hierarchy (by definition of F_INSERT).
  95       */
  96     static final int COMPUTE_INSERTED_FRAMES = 3;
  97 
  98     /**
  99       * Indicates that all the stack map frames must be computed. In this case the maximum stack size
 100       * and the maximum number of local variables is also computed.
 101       */
 102     static final int COMPUTE_ALL_FRAMES = 4;
 103 
 104     /** Indicates that {@link #STACK_SIZE_DELTA} is not applicable (not constant or never used). */
 105     private static final int NA = 0;
 106 
 107     /**
 108       * The stack size variation corresponding to each JVM opcode. The stack size variation for opcode
 109       * 'o' is given by the array element at index 'o'.
 110       *
 111       * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-6.html">JVMS 6</a>
 112       */
 113     private static final int[] STACK_SIZE_DELTA = {
 114         0, // nop = 0 (0x0)
 115         1, // aconst_null = 1 (0x1)
 116         1, // iconst_m1 = 2 (0x2)
 117         1, // iconst_0 = 3 (0x3)
 118         1, // iconst_1 = 4 (0x4)
 119         1, // iconst_2 = 5 (0x5)
 120         1, // iconst_3 = 6 (0x6)
 121         1, // iconst_4 = 7 (0x7)
 122         1, // iconst_5 = 8 (0x8)
 123         2, // lconst_0 = 9 (0x9)
 124         2, // lconst_1 = 10 (0xa)
 125         1, // fconst_0 = 11 (0xb)
 126         1, // fconst_1 = 12 (0xc)
 127         1, // fconst_2 = 13 (0xd)
 128         2, // dconst_0 = 14 (0xe)
 129         2, // dconst_1 = 15 (0xf)
 130         1, // bipush = 16 (0x10)
 131         1, // sipush = 17 (0x11)
 132         1, // ldc = 18 (0x12)
 133         NA, // ldc_w = 19 (0x13)
 134         NA, // ldc2_w = 20 (0x14)
 135         1, // iload = 21 (0x15)
 136         2, // lload = 22 (0x16)
 137         1, // fload = 23 (0x17)
 138         2, // dload = 24 (0x18)
 139         1, // aload = 25 (0x19)
 140         NA, // iload_0 = 26 (0x1a)
 141         NA, // iload_1 = 27 (0x1b)
 142         NA, // iload_2 = 28 (0x1c)
 143         NA, // iload_3 = 29 (0x1d)
 144         NA, // lload_0 = 30 (0x1e)
 145         NA, // lload_1 = 31 (0x1f)
 146         NA, // lload_2 = 32 (0x20)
 147         NA, // lload_3 = 33 (0x21)
 148         NA, // fload_0 = 34 (0x22)
 149         NA, // fload_1 = 35 (0x23)
 150         NA, // fload_2 = 36 (0x24)
 151         NA, // fload_3 = 37 (0x25)
 152         NA, // dload_0 = 38 (0x26)
 153         NA, // dload_1 = 39 (0x27)
 154         NA, // dload_2 = 40 (0x28)
 155         NA, // dload_3 = 41 (0x29)
 156         NA, // aload_0 = 42 (0x2a)
 157         NA, // aload_1 = 43 (0x2b)
 158         NA, // aload_2 = 44 (0x2c)
 159         NA, // aload_3 = 45 (0x2d)
 160         -1, // iaload = 46 (0x2e)
 161         0, // laload = 47 (0x2f)
 162         -1, // faload = 48 (0x30)
 163         0, // daload = 49 (0x31)
 164         -1, // aaload = 50 (0x32)
 165         -1, // baload = 51 (0x33)
 166         -1, // caload = 52 (0x34)
 167         -1, // saload = 53 (0x35)
 168         -1, // istore = 54 (0x36)
 169         -2, // lstore = 55 (0x37)
 170         -1, // fstore = 56 (0x38)
 171         -2, // dstore = 57 (0x39)
 172         -1, // astore = 58 (0x3a)
 173         NA, // istore_0 = 59 (0x3b)
 174         NA, // istore_1 = 60 (0x3c)
 175         NA, // istore_2 = 61 (0x3d)
 176         NA, // istore_3 = 62 (0x3e)
 177         NA, // lstore_0 = 63 (0x3f)
 178         NA, // lstore_1 = 64 (0x40)
 179         NA, // lstore_2 = 65 (0x41)
 180         NA, // lstore_3 = 66 (0x42)
 181         NA, // fstore_0 = 67 (0x43)
 182         NA, // fstore_1 = 68 (0x44)
 183         NA, // fstore_2 = 69 (0x45)
 184         NA, // fstore_3 = 70 (0x46)
 185         NA, // dstore_0 = 71 (0x47)
 186         NA, // dstore_1 = 72 (0x48)
 187         NA, // dstore_2 = 73 (0x49)
 188         NA, // dstore_3 = 74 (0x4a)
 189         NA, // astore_0 = 75 (0x4b)
 190         NA, // astore_1 = 76 (0x4c)
 191         NA, // astore_2 = 77 (0x4d)
 192         NA, // astore_3 = 78 (0x4e)
 193         -3, // iastore = 79 (0x4f)
 194         -4, // lastore = 80 (0x50)
 195         -3, // fastore = 81 (0x51)
 196         -4, // dastore = 82 (0x52)
 197         -3, // aastore = 83 (0x53)
 198         -3, // bastore = 84 (0x54)
 199         -3, // castore = 85 (0x55)
 200         -3, // sastore = 86 (0x56)
 201         -1, // pop = 87 (0x57)
 202         -2, // pop2 = 88 (0x58)
 203         1, // dup = 89 (0x59)
 204         1, // dup_x1 = 90 (0x5a)
 205         1, // dup_x2 = 91 (0x5b)
 206         2, // dup2 = 92 (0x5c)
 207         2, // dup2_x1 = 93 (0x5d)
 208         2, // dup2_x2 = 94 (0x5e)
 209         0, // swap = 95 (0x5f)
 210         -1, // iadd = 96 (0x60)
 211         -2, // ladd = 97 (0x61)
 212         -1, // fadd = 98 (0x62)
 213         -2, // dadd = 99 (0x63)
 214         -1, // isub = 100 (0x64)
 215         -2, // lsub = 101 (0x65)
 216         -1, // fsub = 102 (0x66)
 217         -2, // dsub = 103 (0x67)
 218         -1, // imul = 104 (0x68)
 219         -2, // lmul = 105 (0x69)
 220         -1, // fmul = 106 (0x6a)
 221         -2, // dmul = 107 (0x6b)
 222         -1, // idiv = 108 (0x6c)
 223         -2, // ldiv = 109 (0x6d)
 224         -1, // fdiv = 110 (0x6e)
 225         -2, // ddiv = 111 (0x6f)
 226         -1, // irem = 112 (0x70)
 227         -2, // lrem = 113 (0x71)
 228         -1, // frem = 114 (0x72)
 229         -2, // drem = 115 (0x73)
 230         0, // ineg = 116 (0x74)
 231         0, // lneg = 117 (0x75)
 232         0, // fneg = 118 (0x76)
 233         0, // dneg = 119 (0x77)
 234         -1, // ishl = 120 (0x78)
 235         -1, // lshl = 121 (0x79)
 236         -1, // ishr = 122 (0x7a)
 237         -1, // lshr = 123 (0x7b)
 238         -1, // iushr = 124 (0x7c)
 239         -1, // lushr = 125 (0x7d)
 240         -1, // iand = 126 (0x7e)
 241         -2, // land = 127 (0x7f)
 242         -1, // ior = 128 (0x80)
 243         -2, // lor = 129 (0x81)
 244         -1, // ixor = 130 (0x82)
 245         -2, // lxor = 131 (0x83)
 246         0, // iinc = 132 (0x84)
 247         1, // i2l = 133 (0x85)
 248         0, // i2f = 134 (0x86)
 249         1, // i2d = 135 (0x87)
 250         -1, // l2i = 136 (0x88)
 251         -1, // l2f = 137 (0x89)
 252         0, // l2d = 138 (0x8a)
 253         0, // f2i = 139 (0x8b)
 254         1, // f2l = 140 (0x8c)
 255         1, // f2d = 141 (0x8d)
 256         -1, // d2i = 142 (0x8e)
 257         0, // d2l = 143 (0x8f)
 258         -1, // d2f = 144 (0x90)
 259         0, // i2b = 145 (0x91)
 260         0, // i2c = 146 (0x92)
 261         0, // i2s = 147 (0x93)
 262         -3, // lcmp = 148 (0x94)
 263         -1, // fcmpl = 149 (0x95)
 264         -1, // fcmpg = 150 (0x96)
 265         -3, // dcmpl = 151 (0x97)
 266         -3, // dcmpg = 152 (0x98)
 267         -1, // ifeq = 153 (0x99)
 268         -1, // ifne = 154 (0x9a)
 269         -1, // iflt = 155 (0x9b)
 270         -1, // ifge = 156 (0x9c)
 271         -1, // ifgt = 157 (0x9d)
 272         -1, // ifle = 158 (0x9e)
 273         -2, // if_icmpeq = 159 (0x9f)
 274         -2, // if_icmpne = 160 (0xa0)
 275         -2, // if_icmplt = 161 (0xa1)
 276         -2, // if_icmpge = 162 (0xa2)
 277         -2, // if_icmpgt = 163 (0xa3)
 278         -2, // if_icmple = 164 (0xa4)
 279         -2, // if_acmpeq = 165 (0xa5)
 280         -2, // if_acmpne = 166 (0xa6)
 281         0, // goto = 167 (0xa7)
 282         1, // jsr = 168 (0xa8)
 283         0, // ret = 169 (0xa9)
 284         -1, // tableswitch = 170 (0xaa)
 285         -1, // lookupswitch = 171 (0xab)
 286         -1, // ireturn = 172 (0xac)
 287         -2, // lreturn = 173 (0xad)
 288         -1, // freturn = 174 (0xae)
 289         -2, // dreturn = 175 (0xaf)
 290         -1, // areturn = 176 (0xb0)
 291         0, // return = 177 (0xb1)
 292         NA, // getstatic = 178 (0xb2)
 293         NA, // putstatic = 179 (0xb3)
 294         NA, // getfield = 180 (0xb4)
 295         NA, // putfield = 181 (0xb5)
 296         NA, // invokevirtual = 182 (0xb6)
 297         NA, // invokespecial = 183 (0xb7)
 298         NA, // invokestatic = 184 (0xb8)
 299         NA, // invokeinterface = 185 (0xb9)
 300         NA, // invokedynamic = 186 (0xba)
 301         1, // new = 187 (0xbb)
 302         0, // newarray = 188 (0xbc)
 303         0, // anewarray = 189 (0xbd)
 304         0, // arraylength = 190 (0xbe)
 305         NA, // athrow = 191 (0xbf)
 306         0, // checkcast = 192 (0xc0)
 307         0, // instanceof = 193 (0xc1)
 308         -1, // monitorenter = 194 (0xc2)
 309         -1, // monitorexit = 195 (0xc3)
 310         NA, // wide = 196 (0xc4)
 311         NA, // multianewarray = 197 (0xc5)
 312         -1, // ifnull = 198 (0xc6)
 313         -1, // ifnonnull = 199 (0xc7)
 314         NA, // goto_w = 200 (0xc8)
 315         NA // jsr_w = 201 (0xc9)



 316     };
 317 
 318     /** Where the constants used in this MethodWriter must be stored. */
 319     private final SymbolTable symbolTable;
 320 
 321     // Note: fields are ordered as in the method_info structure, and those related to attributes are
 322     // ordered as in Section 4.7 of the JVMS.
 323 
 324     /**
 325       * The access_flags field of the method_info JVMS structure. This field can contain ASM specific
 326       * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the
 327       * ClassFile structure.
 328       */
 329     private final int accessFlags;
 330 
 331     /** The name_index field of the method_info JVMS structure. */
 332     private final int nameIndex;
 333 
 334     /** The name of this method. */
 335     private final String name;
 336 
 337     /** The descriptor_index field of the method_info JVMS structure. */
 338     private final int descriptorIndex;
 339 
 340     /** The descriptor of this method. */
 341     private final String descriptor;
 342 
 343     // Code attribute fields and sub attributes:
 344 
 345     /** The max_stack field of the Code attribute. */
 346     private int maxStack;
 347 
 348     /** The max_locals field of the Code attribute. */
 349     private int maxLocals;
 350 
 351     /** The 'code' field of the Code attribute. */
 352     private final ByteVector code = new ByteVector();
 353 
 354     /**
 355       * The first element in the exception handler list (used to generate the exception_table of the
 356       * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May
 357       * be {@literal null}.
 358       */
 359     private Handler firstHandler;
 360 
 361     /**
 362       * The last element in the exception handler list (used to generate the exception_table of the
 363       * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May
 364       * be {@literal null}.
 365       */
 366     private Handler lastHandler;
 367 
 368     /** The line_number_table_length field of the LineNumberTable code attribute. */
 369     private int lineNumberTableLength;
 370 
 371     /** The line_number_table array of the LineNumberTable code attribute, or {@literal null}. */
 372     private ByteVector lineNumberTable;
 373 
 374     /** The local_variable_table_length field of the LocalVariableTable code attribute. */
 375     private int localVariableTableLength;
 376 
 377     /**
 378       * The local_variable_table array of the LocalVariableTable code attribute, or {@literal null}.
 379       */
 380     private ByteVector localVariableTable;
 381 
 382     /** The local_variable_type_table_length field of the LocalVariableTypeTable code attribute. */
 383     private int localVariableTypeTableLength;
 384 
 385     /**
 386       * The local_variable_type_table array of the LocalVariableTypeTable code attribute, or {@literal
 387       * null}.
 388       */
 389     private ByteVector localVariableTypeTable;
 390 
 391     /** The number_of_entries field of the StackMapTable code attribute. */
 392     private int stackMapTableNumberOfEntries;
 393 
 394     /** The 'entries' array of the StackMapTable code attribute. */
 395     private ByteVector stackMapTableEntries;
 396 
 397     /**
 398       * The last runtime visible type annotation of the Code attribute. The previous ones can be
 399       * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 400       */
 401     private AnnotationWriter lastCodeRuntimeVisibleTypeAnnotation;
 402 
 403     /**
 404       * The last runtime invisible type annotation of the Code attribute. The previous ones can be
 405       * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 406       */
 407     private AnnotationWriter lastCodeRuntimeInvisibleTypeAnnotation;
 408 
 409     /**
 410       * The first non standard attribute of the Code attribute. The next ones can be accessed with the
 411       * {@link Attribute#nextAttribute} field. May be {@literal null}.
 412       *
 413       * <p><b>WARNING</b>: this list stores the attributes in the <i>reverse</i> order of their visit.
 414       * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link
 415       * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the
 416       * reverse order specified by the user.
 417       */
 418     private Attribute firstCodeAttribute;
 419 
 420     // Other method_info attributes:
 421 
 422     /** The number_of_exceptions field of the Exceptions attribute. */
 423     private final int numberOfExceptions;
 424 
 425     /** The exception_index_table array of the Exceptions attribute, or {@literal null}. */
 426     private final int[] exceptionIndexTable;
 427 
 428     /** The signature_index field of the Signature attribute. */
 429     private final int signatureIndex;
 430 
 431     /**
 432       * The last runtime visible annotation of this method. The previous ones can be accessed with the
 433       * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 434       */
 435     private AnnotationWriter lastRuntimeVisibleAnnotation;
 436 
 437     /**
 438       * The last runtime invisible annotation of this method. The previous ones can be accessed with
 439       * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 440       */
 441     private AnnotationWriter lastRuntimeInvisibleAnnotation;
 442 
 443     /** The number of method parameters that can have runtime visible annotations, or 0. */
 444     private int visibleAnnotableParameterCount;
 445 
 446     /**
 447       * The runtime visible parameter annotations of this method. Each array element contains the last
 448       * annotation of a parameter (which can be {@literal null} - the previous ones can be accessed
 449       * with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.
 450       */
 451     private AnnotationWriter[] lastRuntimeVisibleParameterAnnotations;
 452 
 453     /** The number of method parameters that can have runtime visible annotations, or 0. */
 454     private int invisibleAnnotableParameterCount;
 455 
 456     /**
 457       * The runtime invisible parameter annotations of this method. Each array element contains the
 458       * last annotation of a parameter (which can be {@literal null} - the previous ones can be
 459       * accessed with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.
 460       */
 461     private AnnotationWriter[] lastRuntimeInvisibleParameterAnnotations;
 462 
 463     /**
 464       * The last runtime visible type annotation of this method. The previous ones can be accessed with
 465       * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 466       */
 467     private AnnotationWriter lastRuntimeVisibleTypeAnnotation;
 468 
 469     /**
 470       * The last runtime invisible type annotation of this method. The previous ones can be accessed
 471       * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 472       */
 473     private AnnotationWriter lastRuntimeInvisibleTypeAnnotation;
 474 
 475     /** The default_value field of the AnnotationDefault attribute, or {@literal null}. */
 476     private ByteVector defaultValue;
 477 
 478     /** The parameters_count field of the MethodParameters attribute. */
 479     private int parametersCount;
 480 
 481     /** The 'parameters' array of the MethodParameters attribute, or {@literal null}. */
 482     private ByteVector parameters;
 483 
 484     /**
 485       * The first non standard attribute of this method. The next ones can be accessed with the {@link
 486       * Attribute#nextAttribute} field. May be {@literal null}.
 487       *
 488       * <p><b>WARNING</b>: this list stores the attributes in the <i>reverse</i> order of their visit.
 489       * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link
 490       * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the
 491       * reverse order specified by the user.
 492       */
 493     private Attribute firstAttribute;
 494 
 495     // -----------------------------------------------------------------------------------------------
 496     // Fields used to compute the maximum stack size and number of locals, and the stack map frames
 497     // -----------------------------------------------------------------------------------------------
 498 
 499     /**
 500       * Indicates what must be computed. Must be one of {@link #COMPUTE_ALL_FRAMES}, {@link
 501       * #COMPUTE_INSERTED_FRAMES}, {@link COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link
 502       * #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_NOTHING}.
 503       */
 504     private final int compute;
 505 
 506     /**
 507       * The first basic block of the method. The next ones (in bytecode offset order) can be accessed
 508       * with the {@link Label#nextBasicBlock} field.
 509       */
 510     private Label firstBasicBlock;
 511 
 512     /**
 513       * The last basic block of the method (in bytecode offset order). This field is updated each time
 514       * a basic block is encountered, and is used to append it at the end of the basic block list.
 515       */
 516     private Label lastBasicBlock;
 517 
 518     /**
 519       * The current basic block, i.e. the basic block of the last visited instruction. When {@link
 520       * #compute} is equal to {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_ALL_FRAMES}, this
 521       * field is {@literal null} for unreachable code. When {@link #compute} is equal to {@link
 522       * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES} or {@link #COMPUTE_INSERTED_FRAMES}, this field stays
 523       * unchanged throughout the whole method (i.e. the whole code is seen as a single basic block;
 524       * indeed, the existing frames are sufficient by hypothesis to compute any intermediate frame -
 525       * and the maximum stack size as well - without using any control flow graph).
 526       */
 527     private Label currentBasicBlock;
 528 
 529     /**
 530       * The relative stack size after the last visited instruction. This size is relative to the
 531       * beginning of {@link #currentBasicBlock}, i.e. the true stack size after the last visited
 532       * instruction is equal to the {@link Label#inputStackSize} of the current basic block plus {@link
 533       * #relativeStackSize}. When {@link #compute} is equal to {@link
 534       * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of
 535       * the method, so this relative size is also equal to the absolute stack size after the last
 536       * visited instruction.
 537       */
 538     private int relativeStackSize;
 539 
 540     /**
 541       * The maximum relative stack size after the last visited instruction. This size is relative to
 542       * the beginning of {@link #currentBasicBlock}, i.e. the true maximum stack size after the last
 543       * visited instruction is equal to the {@link Label#inputStackSize} of the current basic block
 544       * plus {@link #maxRelativeStackSize}.When {@link #compute} is equal to {@link
 545       * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of
 546       * the method, so this relative size is also equal to the absolute maximum stack size after the
 547       * last visited instruction.
 548       */
 549     private int maxRelativeStackSize;
 550 
 551     /** The number of local variables in the last visited stack map frame. */
 552     private int currentLocals;
 553 
 554     /** The bytecode offset of the last frame that was written in {@link #stackMapTableEntries}. */
 555     private int previousFrameOffset;
 556 
 557     /**
 558       * The last frame that was written in {@link #stackMapTableEntries}. This field has the same
 559       * format as {@link #currentFrame}.
 560       */
 561     private int[] previousFrame;
 562 
 563     /**
 564       * The current stack map frame. The first element contains the bytecode offset of the instruction
 565       * to which the frame corresponds, the second element is the number of locals and the third one is
 566       * the number of stack elements. The local variables start at index 3 and are followed by the
 567       * operand stack elements. In summary frame[0] = offset, frame[1] = numLocal, frame[2] = numStack.
 568       * Local variables and operand stack entries contain abstract types, as defined in {@link Frame},
 569       * but restricted to {@link Frame#CONSTANT_KIND}, {@link Frame#REFERENCE_KIND} or {@link
 570       * Frame#UNINITIALIZED_KIND} abstract types. Long and double types use only one array entry.
 571       */
 572     private int[] currentFrame;
 573 
 574     /** Whether this method contains subroutines. */
 575     private boolean hasSubroutines;
 576 
 577     // -----------------------------------------------------------------------------------------------
 578     // Other miscellaneous status fields
 579     // -----------------------------------------------------------------------------------------------
 580 
 581     /** Whether the bytecode of this method contains ASM specific instructions. */
 582     private boolean hasAsmInstructions;
 583 
 584     /**
 585       * The start offset of the last visited instruction. Used to set the offset field of type
 586       * annotations of type 'offset_target' (see <a
 587       * href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.1">JVMS
 588       * 4.7.20.1</a>).
 589       */
 590     private int lastBytecodeOffset;
 591 
 592     /**
 593       * The offset in bytes in {@link SymbolTable#getSource} from which the method_info for this method
 594       * (excluding its first 6 bytes) must be copied, or 0.
 595       */
 596     private int sourceOffset;
 597 
 598     /**
 599       * The length in bytes in {@link SymbolTable#getSource} which must be copied to get the
 600       * method_info for this method (excluding its first 6 bytes for access_flags, name_index and
 601       * descriptor_index).
 602       */
 603     private int sourceLength;
 604 
 605     // -----------------------------------------------------------------------------------------------
 606     // Constructor and accessors
 607     // -----------------------------------------------------------------------------------------------
 608 
 609     /**
 610       * Constructs a new {@link MethodWriter}.
 611       *
 612       * @param symbolTable where the constants used in this AnnotationWriter must be stored.
 613       * @param access the method's access flags (see {@link Opcodes}).
 614       * @param name the method's name.
 615       * @param descriptor the method's descriptor (see {@link Type}).
 616       * @param signature the method's signature. May be {@literal null}.
 617       * @param exceptions the internal names of the method's exceptions. May be {@literal null}.
 618       * @param compute indicates what must be computed (see #compute).
 619       */
 620     MethodWriter(
 621             final SymbolTable symbolTable,
 622             final int access,
 623             final String name,
 624             final String descriptor,
 625             final String signature,
 626             final String[] exceptions,
 627             final int compute) {
 628         super(/* latest api = */ Opcodes.ASM9);
 629         this.symbolTable = symbolTable;
 630         this.accessFlags = "<init>".equals(name) ? access | Constants.ACC_CONSTRUCTOR : access;
 631         this.nameIndex = symbolTable.addConstantUtf8(name);
 632         this.name = name;
 633         this.descriptorIndex = symbolTable.addConstantUtf8(descriptor);
 634         this.descriptor = descriptor;
 635         this.signatureIndex = signature == null ? 0 : symbolTable.addConstantUtf8(signature);
 636         if (exceptions != null && exceptions.length > 0) {
 637             numberOfExceptions = exceptions.length;
 638             this.exceptionIndexTable = new int[numberOfExceptions];
 639             for (int i = 0; i < numberOfExceptions; ++i) {
 640                 this.exceptionIndexTable[i] = symbolTable.addConstantClass(exceptions[i]).index;
 641             }
 642         } else {
 643             numberOfExceptions = 0;
 644             this.exceptionIndexTable = null;
 645         }
 646         this.compute = compute;
 647         if (compute != COMPUTE_NOTHING) {
 648             // Update maxLocals and currentLocals.
 649             int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;
 650             if ((access & Opcodes.ACC_STATIC) != 0) {
 651                 --argumentsSize;
 652             }
 653             maxLocals = argumentsSize;
 654             currentLocals = argumentsSize;
 655             // Create and visit the label for the first basic block.
 656             firstBasicBlock = new Label();
 657             visitLabel(firstBasicBlock);
 658         }
 659     }
 660 
 661     boolean hasFrames() {
 662         return stackMapTableNumberOfEntries > 0;
 663     }
 664 
 665     boolean hasAsmInstructions() {
 666         return hasAsmInstructions;
 667     }
 668 
 669     // -----------------------------------------------------------------------------------------------
 670     // Implementation of the MethodVisitor abstract class
 671     // -----------------------------------------------------------------------------------------------
 672 
 673     @Override
 674     public void visitParameter(final String name, final int access) {
 675         if (parameters == null) {
 676             parameters = new ByteVector();
 677         }
 678         ++parametersCount;
 679         parameters.putShort((name == null) ? 0 : symbolTable.addConstantUtf8(name)).putShort(access);
 680     }
 681 
 682     @Override
 683     public AnnotationVisitor visitAnnotationDefault() {
 684         defaultValue = new ByteVector();
 685         return new AnnotationWriter(symbolTable, /* useNamedValues = */ false, defaultValue, null);
 686     }
 687 
 688     @Override
 689     public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
 690         if (visible) {
 691             return lastRuntimeVisibleAnnotation =
 692                     AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation);
 693         } else {
 694             return lastRuntimeInvisibleAnnotation =
 695                     AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation);
 696         }
 697     }
 698 
 699     @Override
 700     public AnnotationVisitor visitTypeAnnotation(
 701             final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
 702         if (visible) {
 703             return lastRuntimeVisibleTypeAnnotation =
 704                     AnnotationWriter.create(
 705                             symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation);
 706         } else {
 707             return lastRuntimeInvisibleTypeAnnotation =
 708                     AnnotationWriter.create(
 709                             symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation);
 710         }
 711     }
 712 
 713     @Override
 714     public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) {
 715         if (visible) {
 716             visibleAnnotableParameterCount = parameterCount;
 717         } else {
 718             invisibleAnnotableParameterCount = parameterCount;
 719         }
 720     }
 721 
 722     @Override
 723     public AnnotationVisitor visitParameterAnnotation(
 724             final int parameter, final String annotationDescriptor, final boolean visible) {
 725         if (visible) {
 726             if (lastRuntimeVisibleParameterAnnotations == null) {
 727                 lastRuntimeVisibleParameterAnnotations =
 728                         new AnnotationWriter[Type.getArgumentTypes(descriptor).length];
 729             }
 730             return lastRuntimeVisibleParameterAnnotations[parameter] =
 731                     AnnotationWriter.create(
 732                             symbolTable, annotationDescriptor, lastRuntimeVisibleParameterAnnotations[parameter]);
 733         } else {
 734             if (lastRuntimeInvisibleParameterAnnotations == null) {
 735                 lastRuntimeInvisibleParameterAnnotations =
 736                         new AnnotationWriter[Type.getArgumentTypes(descriptor).length];
 737             }
 738             return lastRuntimeInvisibleParameterAnnotations[parameter] =
 739                     AnnotationWriter.create(
 740                             symbolTable,
 741                             annotationDescriptor,
 742                             lastRuntimeInvisibleParameterAnnotations[parameter]);
 743         }
 744     }
 745 
 746     @Override
 747     public void visitAttribute(final Attribute attribute) {
 748         // Store the attributes in the <i>reverse</i> order of their visit by this method.
 749         if (attribute.isCodeAttribute()) {
 750             attribute.nextAttribute = firstCodeAttribute;
 751             firstCodeAttribute = attribute;
 752         } else {
 753             attribute.nextAttribute = firstAttribute;
 754             firstAttribute = attribute;
 755         }
 756     }
 757 
 758     @Override
 759     public void visitCode() {
 760         // Nothing to do.
 761     }
 762 
 763     @Override
 764     public void visitFrame(
 765             final int type,
 766             final int numLocal,
 767             final Object[] local,
 768             final int numStack,
 769             final Object[] stack) {
 770         if (compute == COMPUTE_ALL_FRAMES) {
 771             return;
 772         }
 773 
 774         if (compute == COMPUTE_INSERTED_FRAMES) {
 775             if (currentBasicBlock.frame == null) {
 776                 // This should happen only once, for the implicit first frame (which is explicitly visited
 777                 // in ClassReader if the EXPAND_ASM_INSNS option is used - and COMPUTE_INSERTED_FRAMES
 778                 // can't be set if EXPAND_ASM_INSNS is not used).
 779                 currentBasicBlock.frame = new CurrentFrame(currentBasicBlock);
 780                 currentBasicBlock.frame.setInputFrameFromDescriptor(
 781                         symbolTable, accessFlags, descriptor, numLocal);
 782                 currentBasicBlock.frame.accept(this);
 783             } else {
 784                 if (type == Opcodes.F_NEW) {
 785                     currentBasicBlock.frame.setInputFrameFromApiFormat(
 786                             symbolTable, numLocal, local, numStack, stack);
 787                 }
 788                 // If type is not F_NEW then it is F_INSERT by hypothesis, and currentBlock.frame contains
 789                 // the stack map frame at the current instruction, computed from the last F_NEW frame and
 790                 // the bytecode instructions in between (via calls to CurrentFrame#execute).
 791                 currentBasicBlock.frame.accept(this);
 792             }
 793         } else if (type == Opcodes.F_NEW) {
 794             if (previousFrame == null) {
 795                 int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;
 796                 Frame implicitFirstFrame = new Frame(new Label());
 797                 implicitFirstFrame.setInputFrameFromDescriptor(
 798                         symbolTable, accessFlags, descriptor, argumentsSize);
 799                 implicitFirstFrame.accept(this);
 800             }
 801             currentLocals = numLocal;
 802             int frameIndex = visitFrameStart(code.length, numLocal, numStack);
 803             for (int i = 0; i < numLocal; ++i) {
 804                 currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, local[i]);
 805             }
 806             for (int i = 0; i < numStack; ++i) {
 807                 currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, stack[i]);
 808             }
 809             visitFrameEnd();
 810         } else {
 811             if (symbolTable.getMajorVersion() < Opcodes.V1_6) {
 812                 throw new IllegalArgumentException("Class versions V1_5 or less must use F_NEW frames.");
 813             }
 814             int offsetDelta;
 815             if (stackMapTableEntries == null) {
 816                 stackMapTableEntries = new ByteVector();
 817                 offsetDelta = code.length;
 818             } else {
 819                 offsetDelta = code.length - previousFrameOffset - 1;
 820                 if (offsetDelta < 0) {
 821                     if (type == Opcodes.F_SAME) {
 822                         return;
 823                     } else {
 824                         throw new IllegalStateException();
 825                     }
 826                 }
 827             }
 828 
 829             switch (type) {
 830                 case Opcodes.F_FULL:
 831                     currentLocals = numLocal;
 832                     stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);
 833                     for (int i = 0; i < numLocal; ++i) {
 834                         putFrameType(local[i]);
 835                     }
 836                     stackMapTableEntries.putShort(numStack);
 837                     for (int i = 0; i < numStack; ++i) {
 838                         putFrameType(stack[i]);
 839                     }
 840                     break;
 841                 case Opcodes.F_APPEND:
 842                     currentLocals += numLocal;
 843                     stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED + numLocal).putShort(offsetDelta);
 844                     for (int i = 0; i < numLocal; ++i) {
 845                         putFrameType(local[i]);
 846                     }
 847                     break;
 848                 case Opcodes.F_CHOP:
 849                     currentLocals -= numLocal;
 850                     stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED - numLocal).putShort(offsetDelta);
 851                     break;
 852                 case Opcodes.F_SAME:
 853                     if (offsetDelta < 64) {
 854                         stackMapTableEntries.putByte(offsetDelta);
 855                     } else {
 856                         stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);
 857                     }
 858                     break;
 859                 case Opcodes.F_SAME1:
 860                     if (offsetDelta < 64) {
 861                         stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);
 862                     } else {
 863                         stackMapTableEntries
 864                                 .putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
 865                                 .putShort(offsetDelta);
 866                     }
 867                     putFrameType(stack[0]);
 868                     break;
 869                 default:
 870                     throw new IllegalArgumentException();
 871             }
 872 
 873             previousFrameOffset = code.length;
 874             ++stackMapTableNumberOfEntries;
 875         }
 876 
 877         if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
 878             relativeStackSize = numStack;
 879             for (int i = 0; i < numStack; ++i) {
 880                 if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {
 881                     relativeStackSize++;
 882                 }
 883             }
 884             if (relativeStackSize > maxRelativeStackSize) {
 885                 maxRelativeStackSize = relativeStackSize;
 886             }
 887         }
 888 
 889         maxStack = Math.max(maxStack, numStack);
 890         maxLocals = Math.max(maxLocals, currentLocals);
 891     }
 892 
 893     @Override
 894     public void visitInsn(final int opcode) {
 895         lastBytecodeOffset = code.length;
 896         // Add the instruction to the bytecode of the method.
 897         code.putByte(opcode);
 898         // If needed, update the maximum stack size and number of locals, and stack map frames.
 899         if (currentBasicBlock != null) {
 900             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
 901                 currentBasicBlock.frame.execute(opcode, 0, null, null);
 902             } else {
 903                 int size = relativeStackSize + STACK_SIZE_DELTA[opcode];
 904                 if (size > maxRelativeStackSize) {
 905                     maxRelativeStackSize = size;
 906                 }
 907                 relativeStackSize = size;
 908             }
 909             if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) {
 910                 endCurrentBasicBlockWithNoSuccessor();
 911             }
 912         }
 913     }
 914 
 915     @Override
 916     public void visitIntInsn(final int opcode, final int operand) {
 917         lastBytecodeOffset = code.length;
 918         // Add the instruction to the bytecode of the method.
 919         if (opcode == Opcodes.SIPUSH) {
 920             code.put12(opcode, operand);
 921         } else { // BIPUSH or NEWARRAY
 922             code.put11(opcode, operand);
 923         }
 924         // If needed, update the maximum stack size and number of locals, and stack map frames.
 925         if (currentBasicBlock != null) {
 926             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
 927                 currentBasicBlock.frame.execute(opcode, operand, null, null);
 928             } else if (opcode != Opcodes.NEWARRAY) {
 929                 // The stack size delta is 1 for BIPUSH or SIPUSH, and 0 for NEWARRAY.
 930                 int size = relativeStackSize + 1;
 931                 if (size > maxRelativeStackSize) {
 932                     maxRelativeStackSize = size;
 933                 }
 934                 relativeStackSize = size;
 935             }
 936         }
 937     }
 938 
 939     @Override
 940     public void visitVarInsn(final int opcode, final int varIndex) {
 941         lastBytecodeOffset = code.length;
 942         // Add the instruction to the bytecode of the method.
 943         if (varIndex < 4 && opcode != Opcodes.RET) {
 944             int optimizedOpcode;
 945             if (opcode < Opcodes.ISTORE) {
 946                 optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + varIndex;
 947             } else {
 948                 optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + varIndex;
 949             }
 950             code.putByte(optimizedOpcode);
 951         } else if (varIndex >= 256) {
 952             code.putByte(Constants.WIDE).put12(opcode, varIndex);
 953         } else {
 954             code.put11(opcode, varIndex);
 955         }
 956         // If needed, update the maximum stack size and number of locals, and stack map frames.
 957         if (currentBasicBlock != null) {
 958             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
 959                 currentBasicBlock.frame.execute(opcode, varIndex, null, null);
 960             } else {
 961                 if (opcode == Opcodes.RET) {
 962                     // No stack size delta.
 963                     currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_END;
 964                     currentBasicBlock.outputStackSize = (short) relativeStackSize;
 965                     endCurrentBasicBlockWithNoSuccessor();
 966                 } else { // xLOAD or xSTORE
 967                     int size = relativeStackSize + STACK_SIZE_DELTA[opcode];
 968                     if (size > maxRelativeStackSize) {
 969                         maxRelativeStackSize = size;
 970                     }
 971                     relativeStackSize = size;
 972                 }
 973             }
 974         }
 975         if (compute != COMPUTE_NOTHING) {
 976             int currentMaxLocals;
 977             if (opcode == Opcodes.LLOAD
 978                     || opcode == Opcodes.DLOAD
 979                     || opcode == Opcodes.LSTORE
 980                     || opcode == Opcodes.DSTORE) {
 981                 currentMaxLocals = varIndex + 2;
 982             } else {
 983                 currentMaxLocals = varIndex + 1;
 984             }
 985             if (currentMaxLocals > maxLocals) {
 986                 maxLocals = currentMaxLocals;
 987             }
 988         }
 989         if (opcode >= Opcodes.ISTORE && compute == COMPUTE_ALL_FRAMES && firstHandler != null) {
 990             // If there are exception handler blocks, each instruction within a handler range is, in
 991             // theory, a basic block (since execution can jump from this instruction to the exception
 992             // handler). As a consequence, the local variable types at the beginning of the handler
 993             // block should be the merge of the local variable types at all the instructions within the
 994             // handler range. However, instead of creating a basic block for each instruction, we can
 995             // get the same result in a more efficient way. Namely, by starting a new basic block after
 996             // each xSTORE instruction, which is what we do here.
 997             visitLabel(new Label());
 998         }
 999     }
1000 
1001     @Override
1002     public void visitTypeInsn(final int opcode, final String type) {
1003         lastBytecodeOffset = code.length;
1004         // Add the instruction to the bytecode of the method.
1005         Symbol typeSymbol = symbolTable.addConstantClass(type);
1006         code.put12(opcode, typeSymbol.index);
1007         // If needed, update the maximum stack size and number of locals, and stack map frames.
1008         if (currentBasicBlock != null) {
1009             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1010                 currentBasicBlock.frame.execute(opcode, lastBytecodeOffset, typeSymbol, symbolTable);
1011             } else if (opcode == Opcodes.NEW) {
1012                 // The stack size delta is 1 for NEW, and 0 for ANEWARRAY, CHECKCAST, or INSTANCEOF.
1013                 int size = relativeStackSize + 1;
1014                 if (size > maxRelativeStackSize) {
1015                     maxRelativeStackSize = size;
1016                 }
1017                 relativeStackSize = size;
1018             }
1019         }
1020     }
1021 
1022     @Override
1023     public void visitFieldInsn(
1024             final int opcode, final String owner, final String name, final String descriptor) {
1025         lastBytecodeOffset = code.length;
1026         // Add the instruction to the bytecode of the method.
1027         Symbol fieldrefSymbol = symbolTable.addConstantFieldref(owner, name, descriptor);
1028         code.put12(opcode, fieldrefSymbol.index);
1029         // If needed, update the maximum stack size and number of locals, and stack map frames.
1030         if (currentBasicBlock != null) {
1031             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1032                 currentBasicBlock.frame.execute(opcode, 0, fieldrefSymbol, symbolTable);
1033             } else {
1034                 int size;
1035                 char firstDescChar = descriptor.charAt(0);
1036                 switch (opcode) {



1037                     case Opcodes.GETSTATIC:
1038                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 2 : 1);
1039                         break;
1040                     case Opcodes.PUTSTATIC:
1041                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -2 : -1);
1042                         break;
1043                     case Opcodes.GETFIELD:
1044                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 1 : 0);
1045                         break;
1046                     case Opcodes.PUTFIELD:
1047                     default:
1048                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -3 : -2);
1049                         break;
1050                 }
1051                 if (size > maxRelativeStackSize) {
1052                     maxRelativeStackSize = size;
1053                 }
1054                 relativeStackSize = size;
1055             }
1056         }
1057     }
1058 
1059     @Override
1060     public void visitMethodInsn(
1061             final int opcode,
1062             final String owner,
1063             final String name,
1064             final String descriptor,
1065             final boolean isInterface) {
1066         lastBytecodeOffset = code.length;
1067         // Add the instruction to the bytecode of the method.
1068         Symbol methodrefSymbol = symbolTable.addConstantMethodref(owner, name, descriptor, isInterface);
1069         if (opcode == Opcodes.INVOKEINTERFACE) {
1070             code.put12(Opcodes.INVOKEINTERFACE, methodrefSymbol.index)
1071                     .put11(methodrefSymbol.getArgumentsAndReturnSizes() >> 2, 0);
1072         } else {
1073             code.put12(opcode, methodrefSymbol.index);
1074         }
1075         // If needed, update the maximum stack size and number of locals, and stack map frames.
1076         if (currentBasicBlock != null) {
1077             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1078                 currentBasicBlock.frame.execute(opcode, 0, methodrefSymbol, symbolTable);
1079             } else {
1080                 int argumentsAndReturnSize = methodrefSymbol.getArgumentsAndReturnSizes();
1081                 int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2);
1082                 int size;
1083                 if (opcode == Opcodes.INVOKESTATIC) {
1084                     size = relativeStackSize + stackSizeDelta + 1;
1085                 } else {
1086                     size = relativeStackSize + stackSizeDelta;
1087                 }
1088                 if (size > maxRelativeStackSize) {
1089                     maxRelativeStackSize = size;
1090                 }
1091                 relativeStackSize = size;
1092             }
1093         }
1094     }
1095 
1096     @Override
1097     public void visitInvokeDynamicInsn(
1098             final String name,
1099             final String descriptor,
1100             final Handle bootstrapMethodHandle,
1101             final Object... bootstrapMethodArguments) {
1102         lastBytecodeOffset = code.length;
1103         // Add the instruction to the bytecode of the method.
1104         Symbol invokeDynamicSymbol =
1105                 symbolTable.addConstantInvokeDynamic(
1106                         name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
1107         code.put12(Opcodes.INVOKEDYNAMIC, invokeDynamicSymbol.index);
1108         code.putShort(0);
1109         // If needed, update the maximum stack size and number of locals, and stack map frames.
1110         if (currentBasicBlock != null) {
1111             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1112                 currentBasicBlock.frame.execute(Opcodes.INVOKEDYNAMIC, 0, invokeDynamicSymbol, symbolTable);
1113             } else {
1114                 int argumentsAndReturnSize = invokeDynamicSymbol.getArgumentsAndReturnSizes();
1115                 int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2) + 1;
1116                 int size = relativeStackSize + stackSizeDelta;
1117                 if (size > maxRelativeStackSize) {
1118                     maxRelativeStackSize = size;
1119                 }
1120                 relativeStackSize = size;
1121             }
1122         }
1123     }
1124 
1125     @Override
1126     public void visitJumpInsn(final int opcode, final Label label) {
1127         lastBytecodeOffset = code.length;
1128         // Add the instruction to the bytecode of the method.
1129         // Compute the 'base' opcode, i.e. GOTO or JSR if opcode is GOTO_W or JSR_W, otherwise opcode.
1130         int baseOpcode =
1131                 opcode >= Constants.GOTO_W ? opcode - Constants.WIDE_JUMP_OPCODE_DELTA : opcode;
1132         boolean nextInsnIsJumpTarget = false;
1133         if ((label.flags & Label.FLAG_RESOLVED) != 0
1134                 && label.bytecodeOffset - code.length < Short.MIN_VALUE) {
1135             // Case of a backward jump with an offset < -32768. In this case we automatically replace GOTO
1136             // with GOTO_W, JSR with JSR_W and IFxxx <l> with IFNOTxxx <L> GOTO_W <l> L:..., where
1137             // IFNOTxxx is the "opposite" opcode of IFxxx (e.g. IFNE for IFEQ) and where <L> designates
1138             // the instruction just after the GOTO_W.
1139             if (baseOpcode == Opcodes.GOTO) {
1140                 code.putByte(Constants.GOTO_W);
1141             } else if (baseOpcode == Opcodes.JSR) {
1142                 code.putByte(Constants.JSR_W);
1143             } else {
1144                 // Put the "opposite" opcode of baseOpcode. This can be done by flipping the least
1145                 // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ (with a
1146                 // pre and post offset by 1). The jump offset is 8 bytes (3 for IFNOTxxx, 5 for GOTO_W).
1147                 code.putByte(baseOpcode >= Opcodes.IFNULL ? baseOpcode ^ 1 : ((baseOpcode + 1) ^ 1) - 1);
1148                 code.putShort(8);
1149                 // Here we could put a GOTO_W in theory, but if ASM specific instructions are used in this
1150                 // method or another one, and if the class has frames, we will need to insert a frame after
1151                 // this GOTO_W during the additional ClassReader -> ClassWriter round trip to remove the ASM
1152                 // specific instructions. To not miss this additional frame, we need to use an ASM_GOTO_W
1153                 // here, which has the unfortunate effect of forcing this additional round trip (which in
1154                 // some case would not have been really necessary, but we can't know this at this point).
1155                 code.putByte(Constants.ASM_GOTO_W);
1156                 hasAsmInstructions = true;
1157                 // The instruction after the GOTO_W becomes the target of the IFNOT instruction.
1158                 nextInsnIsJumpTarget = true;
1159             }
1160             label.put(code, code.length - 1, true);
1161         } else if (baseOpcode != opcode) {
1162             // Case of a GOTO_W or JSR_W specified by the user (normally ClassReader when used to remove
1163             // ASM specific instructions). In this case we keep the original instruction.
1164             code.putByte(opcode);
1165             label.put(code, code.length - 1, true);
1166         } else {
1167             // Case of a jump with an offset >= -32768, or of a jump with an unknown offset. In these
1168             // cases we store the offset in 2 bytes (which will be increased via a ClassReader ->
1169             // ClassWriter round trip if it turns out that 2 bytes are not sufficient).
1170             code.putByte(baseOpcode);
1171             label.put(code, code.length - 1, false);
1172         }
1173 
1174         // If needed, update the maximum stack size and number of locals, and stack map frames.
1175         if (currentBasicBlock != null) {
1176             Label nextBasicBlock = null;
1177             if (compute == COMPUTE_ALL_FRAMES) {
1178                 currentBasicBlock.frame.execute(baseOpcode, 0, null, null);
1179                 // Record the fact that 'label' is the target of a jump instruction.
1180                 label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
1181                 // Add 'label' as a successor of the current basic block.
1182                 addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
1183                 if (baseOpcode != Opcodes.GOTO) {
1184                     // The next instruction starts a new basic block (except for GOTO: by default the code
1185                     // following a goto is unreachable - unless there is an explicit label for it - and we
1186                     // should not compute stack frame types for its instructions).
1187                     nextBasicBlock = new Label();
1188                 }
1189             } else if (compute == COMPUTE_INSERTED_FRAMES) {
1190                 currentBasicBlock.frame.execute(baseOpcode, 0, null, null);
1191             } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
1192                 // No need to update maxRelativeStackSize (the stack size delta is always negative).
1193                 relativeStackSize += STACK_SIZE_DELTA[baseOpcode];
1194             } else {
1195                 if (baseOpcode == Opcodes.JSR) {
1196                     // Record the fact that 'label' designates a subroutine, if not already done.
1197                     if ((label.flags & Label.FLAG_SUBROUTINE_START) == 0) {
1198                         label.flags |= Label.FLAG_SUBROUTINE_START;
1199                         hasSubroutines = true;
1200                     }
1201                     currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_CALLER;
1202                     // Note that, by construction in this method, a block which calls a subroutine has at
1203                     // least two successors in the control flow graph: the first one (added below) leads to
1204                     // the instruction after the JSR, while the second one (added here) leads to the JSR
1205                     // target. Note that the first successor is virtual (it does not correspond to a possible
1206                     // execution path): it is only used to compute the successors of the basic blocks ending
1207                     // with a ret, in {@link Label#addSubroutineRetSuccessors}.
1208                     addSuccessorToCurrentBasicBlock(relativeStackSize + 1, label);
1209                     // The instruction after the JSR starts a new basic block.
1210                     nextBasicBlock = new Label();
1211                 } else {
1212                     // No need to update maxRelativeStackSize (the stack size delta is always negative).
1213                     relativeStackSize += STACK_SIZE_DELTA[baseOpcode];
1214                     addSuccessorToCurrentBasicBlock(relativeStackSize, label);
1215                 }
1216             }
1217             // If the next instruction starts a new basic block, call visitLabel to add the label of this
1218             // instruction as a successor of the current block, and to start a new basic block.
1219             if (nextBasicBlock != null) {
1220                 if (nextInsnIsJumpTarget) {
1221                     nextBasicBlock.flags |= Label.FLAG_JUMP_TARGET;
1222                 }
1223                 visitLabel(nextBasicBlock);
1224             }
1225             if (baseOpcode == Opcodes.GOTO) {
1226                 endCurrentBasicBlockWithNoSuccessor();
1227             }
1228         }
1229     }
1230 
1231     @Override
1232     public void visitLabel(final Label label) {
1233         // Resolve the forward references to this label, if any.
1234         hasAsmInstructions |= label.resolve(code.data, code.length);
1235         // visitLabel starts a new basic block (except for debug only labels), so we need to update the
1236         // previous and current block references and list of successors.
1237         if ((label.flags & Label.FLAG_DEBUG_ONLY) != 0) {
1238             return;
1239         }
1240         if (compute == COMPUTE_ALL_FRAMES) {
1241             if (currentBasicBlock != null) {
1242                 if (label.bytecodeOffset == currentBasicBlock.bytecodeOffset) {
1243                     // We use {@link Label#getCanonicalInstance} to store the state of a basic block in only
1244                     // one place, but this does not work for labels which have not been visited yet.
1245                     // Therefore, when we detect here two labels having the same bytecode offset, we need to
1246                     // - consolidate the state scattered in these two instances into the canonical instance:
1247                     currentBasicBlock.flags |= (short) (label.flags & Label.FLAG_JUMP_TARGET);
1248                     // - make sure the two instances share the same Frame instance (the implementation of
1249                     // {@link Label#getCanonicalInstance} relies on this property; here label.frame should be
1250                     // null):
1251                     label.frame = currentBasicBlock.frame;
1252                     // - and make sure to NOT assign 'label' into 'currentBasicBlock' or 'lastBasicBlock', so
1253                     // that they still refer to the canonical instance for this bytecode offset.
1254                     return;
1255                 }
1256                 // End the current basic block (with one new successor).
1257                 addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
1258             }
1259             // Append 'label' at the end of the basic block list.
1260             if (lastBasicBlock != null) {
1261                 if (label.bytecodeOffset == lastBasicBlock.bytecodeOffset) {
1262                     // Same comment as above.
1263                     lastBasicBlock.flags |= (short) (label.flags & Label.FLAG_JUMP_TARGET);
1264                     // Here label.frame should be null.
1265                     label.frame = lastBasicBlock.frame;
1266                     currentBasicBlock = lastBasicBlock;
1267                     return;
1268                 }
1269                 lastBasicBlock.nextBasicBlock = label;
1270             }
1271             lastBasicBlock = label;
1272             // Make it the new current basic block.
1273             currentBasicBlock = label;
1274             // Here label.frame should be null.
1275             label.frame = new Frame(label);
1276         } else if (compute == COMPUTE_INSERTED_FRAMES) {
1277             if (currentBasicBlock == null) {
1278                 // This case should happen only once, for the visitLabel call in the constructor. Indeed, if
1279                 // compute is equal to COMPUTE_INSERTED_FRAMES, currentBasicBlock stays unchanged.
1280                 currentBasicBlock = label;
1281             } else {
1282                 // Update the frame owner so that a correct frame offset is computed in Frame.accept().
1283                 currentBasicBlock.frame.owner = label;
1284             }
1285         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1286             if (currentBasicBlock != null) {
1287                 // End the current basic block (with one new successor).
1288                 currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;
1289                 addSuccessorToCurrentBasicBlock(relativeStackSize, label);
1290             }
1291             // Start a new current basic block, and reset the current and maximum relative stack sizes.
1292             currentBasicBlock = label;
1293             relativeStackSize = 0;
1294             maxRelativeStackSize = 0;
1295             // Append the new basic block at the end of the basic block list.
1296             if (lastBasicBlock != null) {
1297                 lastBasicBlock.nextBasicBlock = label;
1298             }
1299             lastBasicBlock = label;
1300         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES && currentBasicBlock == null) {
1301             // This case should happen only once, for the visitLabel call in the constructor. Indeed, if
1302             // compute is equal to COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES, currentBasicBlock stays
1303             // unchanged.
1304             currentBasicBlock = label;
1305         }
1306     }
1307 
1308     @Override
1309     public void visitLdcInsn(final Object value) {
1310         lastBytecodeOffset = code.length;
1311         // Add the instruction to the bytecode of the method.
1312         Symbol constantSymbol = symbolTable.addConstant(value);
1313         int constantIndex = constantSymbol.index;
1314         char firstDescriptorChar;
1315         boolean isLongOrDouble =
1316                 constantSymbol.tag == Symbol.CONSTANT_LONG_TAG
1317                         || constantSymbol.tag == Symbol.CONSTANT_DOUBLE_TAG
1318                         || (constantSymbol.tag == Symbol.CONSTANT_DYNAMIC_TAG
1319                                 && ((firstDescriptorChar = constantSymbol.value.charAt(0)) == 'J'
1320                                         || firstDescriptorChar == 'D'));
1321         if (isLongOrDouble) {
1322             code.put12(Constants.LDC2_W, constantIndex);
1323         } else if (constantIndex >= 256) {
1324             code.put12(Constants.LDC_W, constantIndex);
1325         } else {
1326             code.put11(Opcodes.LDC, constantIndex);
1327         }
1328         // If needed, update the maximum stack size and number of locals, and stack map frames.
1329         if (currentBasicBlock != null) {
1330             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1331                 currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);
1332             } else {
1333                 int size = relativeStackSize + (isLongOrDouble ? 2 : 1);
1334                 if (size > maxRelativeStackSize) {
1335                     maxRelativeStackSize = size;
1336                 }
1337                 relativeStackSize = size;
1338             }
1339         }
1340     }
1341 
1342     @Override
1343     public void visitIincInsn(final int varIndex, final int increment) {
1344         lastBytecodeOffset = code.length;
1345         // Add the instruction to the bytecode of the method.
1346         if ((varIndex > 255) || (increment > 127) || (increment < -128)) {
1347             code.putByte(Constants.WIDE).put12(Opcodes.IINC, varIndex).putShort(increment);
1348         } else {
1349             code.putByte(Opcodes.IINC).put11(varIndex, increment);
1350         }
1351         // If needed, update the maximum stack size and number of locals, and stack map frames.
1352         if (currentBasicBlock != null
1353                 && (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES)) {
1354             currentBasicBlock.frame.execute(Opcodes.IINC, varIndex, null, null);
1355         }
1356         if (compute != COMPUTE_NOTHING) {
1357             int currentMaxLocals = varIndex + 1;
1358             if (currentMaxLocals > maxLocals) {
1359                 maxLocals = currentMaxLocals;
1360             }
1361         }
1362     }
1363 
1364     @Override
1365     public void visitTableSwitchInsn(
1366             final int min, final int max, final Label dflt, final Label... labels) {
1367         lastBytecodeOffset = code.length;
1368         // Add the instruction to the bytecode of the method.
1369         code.putByte(Opcodes.TABLESWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);
1370         dflt.put(code, lastBytecodeOffset, true);
1371         code.putInt(min).putInt(max);
1372         for (Label label : labels) {
1373             label.put(code, lastBytecodeOffset, true);
1374         }
1375         // If needed, update the maximum stack size and number of locals, and stack map frames.
1376         visitSwitchInsn(dflt, labels);
1377     }
1378 
1379     @Override
1380     public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {
1381         lastBytecodeOffset = code.length;
1382         // Add the instruction to the bytecode of the method.
1383         code.putByte(Opcodes.LOOKUPSWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);
1384         dflt.put(code, lastBytecodeOffset, true);
1385         code.putInt(labels.length);
1386         for (int i = 0; i < labels.length; ++i) {
1387             code.putInt(keys[i]);
1388             labels[i].put(code, lastBytecodeOffset, true);
1389         }
1390         // If needed, update the maximum stack size and number of locals, and stack map frames.
1391         visitSwitchInsn(dflt, labels);
1392     }
1393 
1394     private void visitSwitchInsn(final Label dflt, final Label[] labels) {
1395         if (currentBasicBlock != null) {
1396             if (compute == COMPUTE_ALL_FRAMES) {
1397                 currentBasicBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null);
1398                 // Add all the labels as successors of the current basic block.
1399                 addSuccessorToCurrentBasicBlock(Edge.JUMP, dflt);
1400                 dflt.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
1401                 for (Label label : labels) {
1402                     addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
1403                     label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
1404                 }
1405             } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1406                 // No need to update maxRelativeStackSize (the stack size delta is always negative).
1407                 --relativeStackSize;
1408                 // Add all the labels as successors of the current basic block.
1409                 addSuccessorToCurrentBasicBlock(relativeStackSize, dflt);
1410                 for (Label label : labels) {
1411                     addSuccessorToCurrentBasicBlock(relativeStackSize, label);
1412                 }
1413             }
1414             // End the current basic block.
1415             endCurrentBasicBlockWithNoSuccessor();
1416         }
1417     }
1418 
1419     @Override
1420     public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {
1421         lastBytecodeOffset = code.length;
1422         // Add the instruction to the bytecode of the method.
1423         Symbol descSymbol = symbolTable.addConstantClass(descriptor);
1424         code.put12(Opcodes.MULTIANEWARRAY, descSymbol.index).putByte(numDimensions);
1425         // If needed, update the maximum stack size and number of locals, and stack map frames.
1426         if (currentBasicBlock != null) {
1427             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1428                 currentBasicBlock.frame.execute(
1429                         Opcodes.MULTIANEWARRAY, numDimensions, descSymbol, symbolTable);
1430             } else {
1431                 // No need to update maxRelativeStackSize (the stack size delta is always negative).
1432                 relativeStackSize += 1 - numDimensions;
1433             }
1434         }
1435     }
1436 
1437     @Override
1438     public AnnotationVisitor visitInsnAnnotation(
1439             final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
1440         if (visible) {
1441             return lastCodeRuntimeVisibleTypeAnnotation =
1442                     AnnotationWriter.create(
1443                             symbolTable,
1444                             (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8),
1445                             typePath,
1446                             descriptor,
1447                             lastCodeRuntimeVisibleTypeAnnotation);
1448         } else {
1449             return lastCodeRuntimeInvisibleTypeAnnotation =
1450                     AnnotationWriter.create(
1451                             symbolTable,
1452                             (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8),
1453                             typePath,
1454                             descriptor,
1455                             lastCodeRuntimeInvisibleTypeAnnotation);
1456         }
1457     }
1458 
1459     @Override
1460     public void visitTryCatchBlock(
1461             final Label start, final Label end, final Label handler, final String type) {
1462         Handler newHandler =
1463                 new Handler(
1464                         start, end, handler, type != null ? symbolTable.addConstantClass(type).index : 0, type);
1465         if (firstHandler == null) {
1466             firstHandler = newHandler;
1467         } else {
1468             lastHandler.nextHandler = newHandler;
1469         }
1470         lastHandler = newHandler;
1471     }
1472 
1473     @Override
1474     public AnnotationVisitor visitTryCatchAnnotation(
1475             final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
1476         if (visible) {
1477             return lastCodeRuntimeVisibleTypeAnnotation =
1478                     AnnotationWriter.create(
1479                             symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeVisibleTypeAnnotation);
1480         } else {
1481             return lastCodeRuntimeInvisibleTypeAnnotation =
1482                     AnnotationWriter.create(
1483                             symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeInvisibleTypeAnnotation);
1484         }
1485     }
1486 
1487     @Override
1488     public void visitLocalVariable(
1489             final String name,
1490             final String descriptor,
1491             final String signature,
1492             final Label start,
1493             final Label end,
1494             final int index) {
1495         if (signature != null) {
1496             if (localVariableTypeTable == null) {
1497                 localVariableTypeTable = new ByteVector();
1498             }
1499             ++localVariableTypeTableLength;
1500             localVariableTypeTable
1501                     .putShort(start.bytecodeOffset)
1502                     .putShort(end.bytecodeOffset - start.bytecodeOffset)
1503                     .putShort(symbolTable.addConstantUtf8(name))
1504                     .putShort(symbolTable.addConstantUtf8(signature))
1505                     .putShort(index);
1506         }
1507         if (localVariableTable == null) {
1508             localVariableTable = new ByteVector();
1509         }
1510         ++localVariableTableLength;
1511         localVariableTable
1512                 .putShort(start.bytecodeOffset)
1513                 .putShort(end.bytecodeOffset - start.bytecodeOffset)
1514                 .putShort(symbolTable.addConstantUtf8(name))
1515                 .putShort(symbolTable.addConstantUtf8(descriptor))
1516                 .putShort(index);
1517         if (compute != COMPUTE_NOTHING) {
1518             char firstDescChar = descriptor.charAt(0);
1519             int currentMaxLocals = index + (firstDescChar == 'J' || firstDescChar == 'D' ? 2 : 1);
1520             if (currentMaxLocals > maxLocals) {
1521                 maxLocals = currentMaxLocals;
1522             }
1523         }
1524     }
1525 
1526     @Override
1527     public AnnotationVisitor visitLocalVariableAnnotation(
1528             final int typeRef,
1529             final TypePath typePath,
1530             final Label[] start,
1531             final Label[] end,
1532             final int[] index,
1533             final String descriptor,
1534             final boolean visible) {
1535         // Create a ByteVector to hold a 'type_annotation' JVMS structure.
1536         // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.
1537         ByteVector typeAnnotation = new ByteVector();
1538         // Write target_type, target_info, and target_path.
1539         typeAnnotation.putByte(typeRef >>> 24).putShort(start.length);
1540         for (int i = 0; i < start.length; ++i) {
1541             typeAnnotation
1542                     .putShort(start[i].bytecodeOffset)
1543                     .putShort(end[i].bytecodeOffset - start[i].bytecodeOffset)
1544                     .putShort(index[i]);
1545         }
1546         TypePath.put(typePath, typeAnnotation);
1547         // Write type_index and reserve space for num_element_value_pairs.
1548         typeAnnotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0);
1549         if (visible) {
1550             return lastCodeRuntimeVisibleTypeAnnotation =
1551                     new AnnotationWriter(
1552                             symbolTable,
1553                             /* useNamedValues = */ true,
1554                             typeAnnotation,
1555                             lastCodeRuntimeVisibleTypeAnnotation);
1556         } else {
1557             return lastCodeRuntimeInvisibleTypeAnnotation =
1558                     new AnnotationWriter(
1559                             symbolTable,
1560                             /* useNamedValues = */ true,
1561                             typeAnnotation,
1562                             lastCodeRuntimeInvisibleTypeAnnotation);
1563         }
1564     }
1565 
1566     @Override
1567     public void visitLineNumber(final int line, final Label start) {
1568         if (lineNumberTable == null) {
1569             lineNumberTable = new ByteVector();
1570         }
1571         ++lineNumberTableLength;
1572         lineNumberTable.putShort(start.bytecodeOffset);
1573         lineNumberTable.putShort(line);
1574     }
1575 
1576     @Override
1577     public void visitMaxs(final int maxStack, final int maxLocals) {
1578         if (compute == COMPUTE_ALL_FRAMES) {
1579             computeAllFrames();
1580         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1581             computeMaxStackAndLocal();
1582         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
1583             this.maxStack = maxRelativeStackSize;
1584         } else {
1585             this.maxStack = maxStack;
1586             this.maxLocals = maxLocals;
1587         }
1588     }
1589 
1590     /** Computes all the stack map frames of the method, from scratch. */
1591     private void computeAllFrames() {
1592         // Complete the control flow graph with exception handler blocks.
1593         Handler handler = firstHandler;
1594         while (handler != null) {
1595             String catchTypeDescriptor =
1596                     handler.catchTypeDescriptor == null ? "java/lang/Throwable" : handler.catchTypeDescriptor;
1597             int catchType = Frame.getAbstractTypeFromInternalName(symbolTable, catchTypeDescriptor);
1598             // Mark handlerBlock as an exception handler.
1599             Label handlerBlock = handler.handlerPc.getCanonicalInstance();
1600             handlerBlock.flags |= Label.FLAG_JUMP_TARGET;
1601             // Add handlerBlock as a successor of all the basic blocks in the exception handler range.
1602             Label handlerRangeBlock = handler.startPc.getCanonicalInstance();
1603             Label handlerRangeEnd = handler.endPc.getCanonicalInstance();
1604             while (handlerRangeBlock != handlerRangeEnd) {
1605                 handlerRangeBlock.outgoingEdges =
1606                         new Edge(catchType, handlerBlock, handlerRangeBlock.outgoingEdges);
1607                 handlerRangeBlock = handlerRangeBlock.nextBasicBlock;
1608             }
1609             handler = handler.nextHandler;
1610         }
1611 
1612         // Create and visit the first (implicit) frame.
1613         Frame firstFrame = firstBasicBlock.frame;
1614         firstFrame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, this.maxLocals);
1615         firstFrame.accept(this);
1616 
1617         // Fix point algorithm: add the first basic block to a list of blocks to process (i.e. blocks
1618         // whose stack map frame has changed) and, while there are blocks to process, remove one from
1619         // the list and update the stack map frames of its successor blocks in the control flow graph
1620         // (which might change them, in which case these blocks must be processed too, and are thus
1621         // added to the list of blocks to process). Also compute the maximum stack size of the method,
1622         // as a by-product.
1623         Label listOfBlocksToProcess = firstBasicBlock;
1624         listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;
1625         int maxStackSize = 0;
1626         while (listOfBlocksToProcess != Label.EMPTY_LIST) {
1627             // Remove a basic block from the list of blocks to process.
1628             Label basicBlock = listOfBlocksToProcess;
1629             listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;
1630             basicBlock.nextListElement = null;
1631             // By definition, basicBlock is reachable.
1632             basicBlock.flags |= Label.FLAG_REACHABLE;
1633             // Update the (absolute) maximum stack size.
1634             int maxBlockStackSize = basicBlock.frame.getInputStackSize() + basicBlock.outputStackMax;
1635             if (maxBlockStackSize > maxStackSize) {
1636                 maxStackSize = maxBlockStackSize;
1637             }
1638             // Update the successor blocks of basicBlock in the control flow graph.
1639             Edge outgoingEdge = basicBlock.outgoingEdges;
1640             while (outgoingEdge != null) {
1641                 Label successorBlock = outgoingEdge.successor.getCanonicalInstance();
1642                 boolean successorBlockChanged =
1643                         basicBlock.frame.merge(symbolTable, successorBlock.frame, outgoingEdge.info);
1644                 if (successorBlockChanged && successorBlock.nextListElement == null) {
1645                     // If successorBlock has changed it must be processed. Thus, if it is not already in the
1646                     // list of blocks to process, add it to this list.
1647                     successorBlock.nextListElement = listOfBlocksToProcess;
1648                     listOfBlocksToProcess = successorBlock;
1649                 }
1650                 outgoingEdge = outgoingEdge.nextEdge;
1651             }
1652         }
1653 
1654         // Loop over all the basic blocks and visit the stack map frames that must be stored in the
1655         // StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from
1656         // exception handler ranges.
1657         Label basicBlock = firstBasicBlock;
1658         while (basicBlock != null) {
1659             if ((basicBlock.flags & (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE))
1660                     == (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) {
1661                 basicBlock.frame.accept(this);
1662             }
1663             if ((basicBlock.flags & Label.FLAG_REACHABLE) == 0) {
1664                 // Find the start and end bytecode offsets of this unreachable block.
1665                 Label nextBasicBlock = basicBlock.nextBasicBlock;
1666                 int startOffset = basicBlock.bytecodeOffset;
1667                 int endOffset = (nextBasicBlock == null ? code.length : nextBasicBlock.bytecodeOffset) - 1;
1668                 if (endOffset >= startOffset) {
1669                     // Replace its instructions with NOP ... NOP ATHROW.
1670                     for (int i = startOffset; i < endOffset; ++i) {
1671                         code.data[i] = Opcodes.NOP;
1672                     }
1673                     code.data[endOffset] = (byte) Opcodes.ATHROW;
1674                     // Emit a frame for this unreachable block, with no local and a Throwable on the stack
1675                     // (so that the ATHROW could consume this Throwable if it were reachable).
1676                     int frameIndex = visitFrameStart(startOffset, /* numLocal = */ 0, /* numStack = */ 1);
1677                     currentFrame[frameIndex] =
1678                             Frame.getAbstractTypeFromInternalName(symbolTable, "java/lang/Throwable");
1679                     visitFrameEnd();
1680                     // Remove this unreachable basic block from the exception handler ranges.
1681                     firstHandler = Handler.removeRange(firstHandler, basicBlock, nextBasicBlock);
1682                     // The maximum stack size is now at least one, because of the Throwable declared above.
1683                     maxStackSize = Math.max(maxStackSize, 1);
1684                 }
1685             }
1686             basicBlock = basicBlock.nextBasicBlock;
1687         }
1688 
1689         this.maxStack = maxStackSize;
1690     }
1691 
1692     /** Computes the maximum stack size of the method. */
1693     private void computeMaxStackAndLocal() {
1694         // Complete the control flow graph with exception handler blocks.
1695         Handler handler = firstHandler;
1696         while (handler != null) {
1697             Label handlerBlock = handler.handlerPc;
1698             Label handlerRangeBlock = handler.startPc;
1699             Label handlerRangeEnd = handler.endPc;
1700             // Add handlerBlock as a successor of all the basic blocks in the exception handler range.
1701             while (handlerRangeBlock != handlerRangeEnd) {
1702                 if ((handlerRangeBlock.flags & Label.FLAG_SUBROUTINE_CALLER) == 0) {
1703                     handlerRangeBlock.outgoingEdges =
1704                             new Edge(Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges);
1705                 } else {
1706                     // If handlerRangeBlock is a JSR block, add handlerBlock after the first two outgoing
1707                     // edges to preserve the hypothesis about JSR block successors order (see
1708                     // {@link #visitJumpInsn}).
1709                     handlerRangeBlock.outgoingEdges.nextEdge.nextEdge =
1710                             new Edge(
1711                                     Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges.nextEdge.nextEdge);
1712                 }
1713                 handlerRangeBlock = handlerRangeBlock.nextBasicBlock;
1714             }
1715             handler = handler.nextHandler;
1716         }
1717 
1718         // Complete the control flow graph with the successor blocks of subroutines, if needed.
1719         if (hasSubroutines) {
1720             // First step: find the subroutines. This step determines, for each basic block, to which
1721             // subroutine(s) it belongs. Start with the main "subroutine":
1722             short numSubroutines = 1;
1723             firstBasicBlock.markSubroutine(numSubroutines);
1724             // Then, mark the subroutines called by the main subroutine, then the subroutines called by
1725             // those called by the main subroutine, etc.
1726             for (short currentSubroutine = 1; currentSubroutine <= numSubroutines; ++currentSubroutine) {
1727                 Label basicBlock = firstBasicBlock;
1728                 while (basicBlock != null) {
1729                     if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0
1730                             && basicBlock.subroutineId == currentSubroutine) {
1731                         Label jsrTarget = basicBlock.outgoingEdges.nextEdge.successor;
1732                         if (jsrTarget.subroutineId == 0) {
1733                             // If this subroutine has not been marked yet, find its basic blocks.
1734                             jsrTarget.markSubroutine(++numSubroutines);
1735                         }
1736                     }
1737                     basicBlock = basicBlock.nextBasicBlock;
1738                 }
1739             }
1740             // Second step: find the successors in the control flow graph of each subroutine basic block
1741             // 'r' ending with a RET instruction. These successors are the virtual successors of the basic
1742             // blocks ending with JSR instructions (see {@link #visitJumpInsn)} that can reach 'r'.
1743             Label basicBlock = firstBasicBlock;
1744             while (basicBlock != null) {
1745                 if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {
1746                     // By construction, jsr targets are stored in the second outgoing edge of basic blocks
1747                     // that ends with a jsr instruction (see {@link #FLAG_SUBROUTINE_CALLER}).
1748                     Label subroutine = basicBlock.outgoingEdges.nextEdge.successor;
1749                     subroutine.addSubroutineRetSuccessors(basicBlock);
1750                 }
1751                 basicBlock = basicBlock.nextBasicBlock;
1752             }
1753         }
1754 
1755         // Data flow algorithm: put the first basic block in a list of blocks to process (i.e. blocks
1756         // whose input stack size has changed) and, while there are blocks to process, remove one
1757         // from the list, update the input stack size of its successor blocks in the control flow
1758         // graph, and add these blocks to the list of blocks to process (if not already done).
1759         Label listOfBlocksToProcess = firstBasicBlock;
1760         listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;
1761         int maxStackSize = maxStack;
1762         while (listOfBlocksToProcess != Label.EMPTY_LIST) {
1763             // Remove a basic block from the list of blocks to process. Note that we don't reset
1764             // basicBlock.nextListElement to null on purpose, to make sure we don't reprocess already
1765             // processed basic blocks.
1766             Label basicBlock = listOfBlocksToProcess;
1767             listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;
1768             // Compute the (absolute) input stack size and maximum stack size of this block.
1769             int inputStackTop = basicBlock.inputStackSize;
1770             int maxBlockStackSize = inputStackTop + basicBlock.outputStackMax;
1771             // Update the absolute maximum stack size of the method.
1772             if (maxBlockStackSize > maxStackSize) {
1773                 maxStackSize = maxBlockStackSize;
1774             }
1775             // Update the input stack size of the successor blocks of basicBlock in the control flow
1776             // graph, and add these blocks to the list of blocks to process, if not already done.
1777             Edge outgoingEdge = basicBlock.outgoingEdges;
1778             if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {
1779                 // Ignore the first outgoing edge of the basic blocks ending with a jsr: these are virtual
1780                 // edges which lead to the instruction just after the jsr, and do not correspond to a
1781                 // possible execution path (see {@link #visitJumpInsn} and
1782                 // {@link Label#FLAG_SUBROUTINE_CALLER}).
1783                 outgoingEdge = outgoingEdge.nextEdge;
1784             }
1785             while (outgoingEdge != null) {
1786                 Label successorBlock = outgoingEdge.successor;
1787                 if (successorBlock.nextListElement == null) {
1788                     successorBlock.inputStackSize =
1789                             (short) (outgoingEdge.info == Edge.EXCEPTION ? 1 : inputStackTop + outgoingEdge.info);
1790                     successorBlock.nextListElement = listOfBlocksToProcess;
1791                     listOfBlocksToProcess = successorBlock;
1792                 }
1793                 outgoingEdge = outgoingEdge.nextEdge;
1794             }
1795         }
1796         this.maxStack = maxStackSize;
1797     }
1798 
1799     @Override
1800     public void visitEnd() {
1801         // Nothing to do.
1802     }
1803 
1804     // -----------------------------------------------------------------------------------------------
1805     // Utility methods: control flow analysis algorithm
1806     // -----------------------------------------------------------------------------------------------
1807 
1808     /**
1809       * Adds a successor to {@link #currentBasicBlock} in the control flow graph.
1810       *
1811       * @param info information about the control flow edge to be added.
1812       * @param successor the successor block to be added to the current basic block.
1813       */
1814     private void addSuccessorToCurrentBasicBlock(final int info, final Label successor) {
1815         currentBasicBlock.outgoingEdges = new Edge(info, successor, currentBasicBlock.outgoingEdges);
1816     }
1817 
1818     /**
1819       * Ends the current basic block. This method must be used in the case where the current basic
1820       * block does not have any successor.
1821       *
1822       * <p>WARNING: this method must be called after the currently visited instruction has been put in
1823       * {@link #code} (if frames are computed, this method inserts a new Label to start a new basic
1824       * block after the current instruction).
1825       */
1826     private void endCurrentBasicBlockWithNoSuccessor() {
1827         if (compute == COMPUTE_ALL_FRAMES) {
1828             Label nextBasicBlock = new Label();
1829             nextBasicBlock.frame = new Frame(nextBasicBlock);
1830             nextBasicBlock.resolve(code.data, code.length);
1831             lastBasicBlock.nextBasicBlock = nextBasicBlock;
1832             lastBasicBlock = nextBasicBlock;
1833             currentBasicBlock = null;
1834         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1835             currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;
1836             currentBasicBlock = null;
1837         }
1838     }
1839 
1840     // -----------------------------------------------------------------------------------------------
1841     // Utility methods: stack map frames
1842     // -----------------------------------------------------------------------------------------------
1843 
1844     /**
1845       * Starts the visit of a new stack map frame, stored in {@link #currentFrame}.
1846       *
1847       * @param offset the bytecode offset of the instruction to which the frame corresponds.
1848       * @param numLocal the number of local variables in the frame.
1849       * @param numStack the number of stack elements in the frame.
1850       * @return the index of the next element to be written in this frame.
1851       */
1852     int visitFrameStart(final int offset, final int numLocal, final int numStack) {
1853         int frameLength = 3 + numLocal + numStack;
1854         if (currentFrame == null || currentFrame.length < frameLength) {
1855             currentFrame = new int[frameLength];
1856         }
1857         currentFrame[0] = offset;
1858         currentFrame[1] = numLocal;
1859         currentFrame[2] = numStack;
1860         return 3;
1861     }
1862 
1863     /**
1864       * Sets an abstract type in {@link #currentFrame}.
1865       *
1866       * @param frameIndex the index of the element to be set in {@link #currentFrame}.
1867       * @param abstractType an abstract type.
1868       */
1869     void visitAbstractType(final int frameIndex, final int abstractType) {
1870         currentFrame[frameIndex] = abstractType;
1871     }
1872 
1873     /**
1874       * Ends the visit of {@link #currentFrame} by writing it in the StackMapTable entries and by
1875       * updating the StackMapTable number_of_entries (except if the current frame is the first one,
1876       * which is implicit in StackMapTable). Then resets {@link #currentFrame} to {@literal null}.
1877       */
1878     void visitFrameEnd() {
1879         if (previousFrame != null) {
1880             if (stackMapTableEntries == null) {
1881                 stackMapTableEntries = new ByteVector();
1882             }
1883             putFrame();
1884             ++stackMapTableNumberOfEntries;
1885         }
1886         previousFrame = currentFrame;
1887         currentFrame = null;
1888     }
1889 
1890     /** Compresses and writes {@link #currentFrame} in a new StackMapTable entry. */
1891     private void putFrame() {
1892         final int numLocal = currentFrame[1];
1893         final int numStack = currentFrame[2];
1894         if (symbolTable.getMajorVersion() < Opcodes.V1_6) {
1895             // Generate a StackMap attribute entry, which are always uncompressed.
1896             stackMapTableEntries.putShort(currentFrame[0]).putShort(numLocal);
1897             putAbstractTypes(3, 3 + numLocal);
1898             stackMapTableEntries.putShort(numStack);
1899             putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);
1900             return;
1901         }
1902         final int offsetDelta =
1903                 stackMapTableNumberOfEntries == 0
1904                         ? currentFrame[0]
1905                         : currentFrame[0] - previousFrame[0] - 1;
1906         final int previousNumlocal = previousFrame[1];
1907         final int numLocalDelta = numLocal - previousNumlocal;
1908         int type = Frame.FULL_FRAME;
1909         if (numStack == 0) {
1910             switch (numLocalDelta) {
1911                 case -3:
1912                 case -2:
1913                 case -1:
1914                     type = Frame.CHOP_FRAME;
1915                     break;
1916                 case 0:
1917                     type = offsetDelta < 64 ? Frame.SAME_FRAME : Frame.SAME_FRAME_EXTENDED;
1918                     break;
1919                 case 1:
1920                 case 2:
1921                 case 3:
1922                     type = Frame.APPEND_FRAME;
1923                     break;
1924                 default:
1925                     // Keep the FULL_FRAME type.
1926                     break;
1927             }
1928         } else if (numLocalDelta == 0 && numStack == 1) {
1929             type =
1930                     offsetDelta < 63
1931                             ? Frame.SAME_LOCALS_1_STACK_ITEM_FRAME
1932                             : Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;
1933         }
1934         if (type != Frame.FULL_FRAME) {
1935             // Verify if locals are the same as in the previous frame.
1936             int frameIndex = 3;
1937             for (int i = 0; i < previousNumlocal && i < numLocal; i++) {
1938                 if (currentFrame[frameIndex] != previousFrame[frameIndex]) {
1939                     type = Frame.FULL_FRAME;
1940                     break;
1941                 }
1942                 frameIndex++;
1943             }
1944         }
1945         switch (type) {
1946             case Frame.SAME_FRAME:
1947                 stackMapTableEntries.putByte(offsetDelta);
1948                 break;
1949             case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME:
1950                 stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);
1951                 putAbstractTypes(3 + numLocal, 4 + numLocal);
1952                 break;
1953             case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED:
1954                 stackMapTableEntries
1955                         .putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
1956                         .putShort(offsetDelta);
1957                 putAbstractTypes(3 + numLocal, 4 + numLocal);
1958                 break;
1959             case Frame.SAME_FRAME_EXTENDED:
1960                 stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);
1961                 break;
1962             case Frame.CHOP_FRAME:
1963                 stackMapTableEntries
1964                         .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)
1965                         .putShort(offsetDelta);
1966                 break;
1967             case Frame.APPEND_FRAME:
1968                 stackMapTableEntries
1969                         .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)
1970                         .putShort(offsetDelta);
1971                 putAbstractTypes(3 + previousNumlocal, 3 + numLocal);
1972                 break;
1973             case Frame.FULL_FRAME:
1974             default:
1975                 stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);
1976                 putAbstractTypes(3, 3 + numLocal);
1977                 stackMapTableEntries.putShort(numStack);
1978                 putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);
1979                 break;
1980         }
1981     }
1982 
1983     /**
1984       * Puts some abstract types of {@link #currentFrame} in {@link #stackMapTableEntries} , using the
1985       * JVMS verification_type_info format used in StackMapTable attributes.
1986       *
1987       * @param start index of the first type in {@link #currentFrame} to write.
1988       * @param end index of last type in {@link #currentFrame} to write (exclusive).
1989       */
1990     private void putAbstractTypes(final int start, final int end) {
1991         for (int i = start; i < end; ++i) {
1992             Frame.putAbstractType(symbolTable, currentFrame[i], stackMapTableEntries);
1993         }
1994     }
1995 
1996     /**
1997       * Puts the given public API frame element type in {@link #stackMapTableEntries} , using the JVMS
1998       * verification_type_info format used in StackMapTable attributes.
1999       *
2000       * @param type a frame element type described using the same format as in {@link
2001       *     MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link
2002       *     Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or
2003       *     {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating
2004       *     a NEW instruction (for uninitialized types).
2005       */
2006     private void putFrameType(final Object type) {
2007         if (type instanceof Integer) {
2008             stackMapTableEntries.putByte(((Integer) type).intValue());
2009         } else if (type instanceof String) {
2010             stackMapTableEntries
2011                     .putByte(Frame.ITEM_OBJECT)
2012                     .putShort(symbolTable.addConstantClass((String) type).index);
2013         } else {
2014             stackMapTableEntries
2015                     .putByte(Frame.ITEM_UNINITIALIZED)
2016                     .putShort(((Label) type).bytecodeOffset);
2017         }
2018     }
2019 
2020     // -----------------------------------------------------------------------------------------------
2021     // Utility methods
2022     // -----------------------------------------------------------------------------------------------
2023 
2024     /**
2025       * Returns whether the attributes of this method can be copied from the attributes of the given
2026       * method (assuming there is no method visitor between the given ClassReader and this
2027       * MethodWriter). This method should only be called just after this MethodWriter has been created,
2028       * and before any content is visited. It returns true if the attributes corresponding to the
2029       * constructor arguments (at most a Signature, an Exception, a Deprecated and a Synthetic
2030       * attribute) are the same as the corresponding attributes in the given method.
2031       *
2032       * @param source the source ClassReader from which the attributes of this method might be copied.
2033       * @param hasSyntheticAttribute whether the method_info JVMS structure from which the attributes
2034       *     of this method might be copied contains a Synthetic attribute.
2035       * @param hasDeprecatedAttribute whether the method_info JVMS structure from which the attributes
2036       *     of this method might be copied contains a Deprecated attribute.
2037       * @param descriptorIndex the descriptor_index field of the method_info JVMS structure from which
2038       *     the attributes of this method might be copied.
2039       * @param signatureIndex the constant pool index contained in the Signature attribute of the
2040       *     method_info JVMS structure from which the attributes of this method might be copied, or 0.
2041       * @param exceptionsOffset the offset in 'source.b' of the Exceptions attribute of the method_info
2042       *     JVMS structure from which the attributes of this method might be copied, or 0.
2043       * @return whether the attributes of this method can be copied from the attributes of the
2044       *     method_info JVMS structure in 'source.b', between 'methodInfoOffset' and 'methodInfoOffset'
2045       *     + 'methodInfoLength'.
2046       */
2047     boolean canCopyMethodAttributes(
2048             final ClassReader source,
2049             final boolean hasSyntheticAttribute,
2050             final boolean hasDeprecatedAttribute,
2051             final int descriptorIndex,
2052             final int signatureIndex,
2053             final int exceptionsOffset) {
2054         // If the method descriptor has changed, with more locals than the max_locals field of the
2055         // original Code attribute, if any, then the original method attributes can't be copied. A
2056         // conservative check on the descriptor changes alone ensures this (being more precise is not
2057         // worth the additional complexity, because these cases should be rare -- if a transform changes
2058         // a method descriptor, most of the time it needs to change the method's code too).
2059         if (source != symbolTable.getSource()
2060                 || descriptorIndex != this.descriptorIndex
2061                 || signatureIndex != this.signatureIndex
2062                 || hasDeprecatedAttribute != ((accessFlags & Opcodes.ACC_DEPRECATED) != 0)) {
2063             return false;
2064         }
2065         boolean needSyntheticAttribute =
2066                 symbolTable.getMajorVersion() < Opcodes.V1_5 && (accessFlags & Opcodes.ACC_SYNTHETIC) != 0;
2067         if (hasSyntheticAttribute != needSyntheticAttribute) {
2068             return false;
2069         }
2070         if (exceptionsOffset == 0) {
2071             if (numberOfExceptions != 0) {
2072                 return false;
2073             }
2074         } else if (source.readUnsignedShort(exceptionsOffset) == numberOfExceptions) {
2075             int currentExceptionOffset = exceptionsOffset + 2;
2076             for (int i = 0; i < numberOfExceptions; ++i) {
2077                 if (source.readUnsignedShort(currentExceptionOffset) != exceptionIndexTable[i]) {
2078                     return false;
2079                 }
2080                 currentExceptionOffset += 2;
2081             }
2082         }
2083         return true;
2084     }
2085 
2086     /**
2087       * Sets the source from which the attributes of this method will be copied.
2088       *
2089       * @param methodInfoOffset the offset in 'symbolTable.getSource()' of the method_info JVMS
2090       *     structure from which the attributes of this method will be copied.
2091       * @param methodInfoLength the length in 'symbolTable.getSource()' of the method_info JVMS
2092       *     structure from which the attributes of this method will be copied.
2093       */
2094     void setMethodAttributesSource(final int methodInfoOffset, final int methodInfoLength) {
2095         // Don't copy the attributes yet, instead store their location in the source class reader so
2096         // they can be copied later, in {@link #putMethodInfo}. Note that we skip the 6 header bytes
2097         // of the method_info JVMS structure.
2098         this.sourceOffset = methodInfoOffset + 6;
2099         this.sourceLength = methodInfoLength - 6;
2100     }
2101 
2102     /**
2103       * Returns the size of the method_info JVMS structure generated by this MethodWriter. Also add the
2104       * names of the attributes of this method in the constant pool.
2105       *
2106       * @return the size in bytes of the method_info JVMS structure.
2107       */
2108     int computeMethodInfoSize() {
2109         // If this method_info must be copied from an existing one, the size computation is trivial.
2110         if (sourceOffset != 0) {
2111             // sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index.
2112             return 6 + sourceLength;
2113         }
2114         // 2 bytes each for access_flags, name_index, descriptor_index and attributes_count.
2115         int size = 8;
2116         // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
2117         if (code.length > 0) {
2118             if (code.length > 65535) {
2119                 throw new MethodTooLargeException(
2120                         symbolTable.getClassName(), name, descriptor, code.length);
2121             }
2122             symbolTable.addConstantUtf8(Constants.CODE);
2123             // The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack,
2124             // max_locals, code_length and attributes_count, plus the bytecode and the exception table.
2125             size += 16 + code.length + Handler.getExceptionTableSize(firstHandler);
2126             if (stackMapTableEntries != null) {
2127                 boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
2128                 symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap");
2129                 // 6 header bytes and 2 bytes for number_of_entries.
2130                 size += 8 + stackMapTableEntries.length;
2131             }
2132             if (lineNumberTable != null) {
2133                 symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE);
2134                 // 6 header bytes and 2 bytes for line_number_table_length.
2135                 size += 8 + lineNumberTable.length;
2136             }
2137             if (localVariableTable != null) {
2138                 symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE);
2139                 // 6 header bytes and 2 bytes for local_variable_table_length.
2140                 size += 8 + localVariableTable.length;
2141             }
2142             if (localVariableTypeTable != null) {
2143                 symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE);
2144                 // 6 header bytes and 2 bytes for local_variable_type_table_length.
2145                 size += 8 + localVariableTypeTable.length;
2146             }
2147             if (lastCodeRuntimeVisibleTypeAnnotation != null) {
2148                 size +=
2149                         lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(
2150                                 Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);
2151             }
2152             if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
2153                 size +=
2154                         lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(
2155                                 Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);
2156             }
2157             if (firstCodeAttribute != null) {
2158                 size +=
2159                         firstCodeAttribute.computeAttributesSize(
2160                                 symbolTable, code.data, code.length, maxStack, maxLocals);
2161             }
2162         }
2163         if (numberOfExceptions > 0) {
2164             symbolTable.addConstantUtf8(Constants.EXCEPTIONS);
2165             size += 8 + 2 * numberOfExceptions;
2166         }
2167         size += Attribute.computeAttributesSize(symbolTable, accessFlags, signatureIndex);
2168         size +=
2169                 AnnotationWriter.computeAnnotationsSize(
2170                         lastRuntimeVisibleAnnotation,
2171                         lastRuntimeInvisibleAnnotation,
2172                         lastRuntimeVisibleTypeAnnotation,
2173                         lastRuntimeInvisibleTypeAnnotation);
2174         if (lastRuntimeVisibleParameterAnnotations != null) {
2175             size +=
2176                     AnnotationWriter.computeParameterAnnotationsSize(
2177                             Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS,
2178                             lastRuntimeVisibleParameterAnnotations,
2179                             visibleAnnotableParameterCount == 0
2180                                     ? lastRuntimeVisibleParameterAnnotations.length
2181                                     : visibleAnnotableParameterCount);
2182         }
2183         if (lastRuntimeInvisibleParameterAnnotations != null) {
2184             size +=
2185                     AnnotationWriter.computeParameterAnnotationsSize(
2186                             Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS,
2187                             lastRuntimeInvisibleParameterAnnotations,
2188                             invisibleAnnotableParameterCount == 0
2189                                     ? lastRuntimeInvisibleParameterAnnotations.length
2190                                     : invisibleAnnotableParameterCount);
2191         }
2192         if (defaultValue != null) {
2193             symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT);
2194             size += 6 + defaultValue.length;
2195         }
2196         if (parameters != null) {
2197             symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS);
2198             // 6 header bytes and 1 byte for parameters_count.
2199             size += 7 + parameters.length;
2200         }
2201         if (firstAttribute != null) {
2202             size += firstAttribute.computeAttributesSize(symbolTable);
2203         }
2204         return size;
2205     }
2206 
2207     /**
2208       * Puts the content of the method_info JVMS structure generated by this MethodWriter into the
2209       * given ByteVector.
2210       *
2211       * @param output where the method_info structure must be put.
2212       */
2213     void putMethodInfo(final ByteVector output) {
2214         boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5;
2215         int mask = useSyntheticAttribute ? Opcodes.ACC_SYNTHETIC : 0;
2216         output.putShort(accessFlags & ~mask).putShort(nameIndex).putShort(descriptorIndex);
2217         // If this method_info must be copied from an existing one, copy it now and return early.
2218         if (sourceOffset != 0) {
2219             output.putByteArray(symbolTable.getSource().classFileBuffer, sourceOffset, sourceLength);
2220             return;
2221         }
2222         // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
2223         int attributeCount = 0;
2224         if (code.length > 0) {
2225             ++attributeCount;
2226         }
2227         if (numberOfExceptions > 0) {
2228             ++attributeCount;
2229         }
2230         if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) {
2231             ++attributeCount;
2232         }
2233         if (signatureIndex != 0) {
2234             ++attributeCount;
2235         }
2236         if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) {
2237             ++attributeCount;
2238         }
2239         if (lastRuntimeVisibleAnnotation != null) {
2240             ++attributeCount;
2241         }
2242         if (lastRuntimeInvisibleAnnotation != null) {
2243             ++attributeCount;
2244         }
2245         if (lastRuntimeVisibleParameterAnnotations != null) {
2246             ++attributeCount;
2247         }
2248         if (lastRuntimeInvisibleParameterAnnotations != null) {
2249             ++attributeCount;
2250         }
2251         if (lastRuntimeVisibleTypeAnnotation != null) {
2252             ++attributeCount;
2253         }
2254         if (lastRuntimeInvisibleTypeAnnotation != null) {
2255             ++attributeCount;
2256         }
2257         if (defaultValue != null) {
2258             ++attributeCount;
2259         }
2260         if (parameters != null) {
2261             ++attributeCount;
2262         }
2263         if (firstAttribute != null) {
2264             attributeCount += firstAttribute.getAttributeCount();
2265         }
2266         // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
2267         output.putShort(attributeCount);
2268         if (code.length > 0) {
2269             // 2, 2, 4 and 2 bytes respectively for max_stack, max_locals, code_length and
2270             // attributes_count, plus the bytecode and the exception table.
2271             int size = 10 + code.length + Handler.getExceptionTableSize(firstHandler);
2272             int codeAttributeCount = 0;
2273             if (stackMapTableEntries != null) {
2274                 // 6 header bytes and 2 bytes for number_of_entries.
2275                 size += 8 + stackMapTableEntries.length;
2276                 ++codeAttributeCount;
2277             }
2278             if (lineNumberTable != null) {
2279                 // 6 header bytes and 2 bytes for line_number_table_length.
2280                 size += 8 + lineNumberTable.length;
2281                 ++codeAttributeCount;
2282             }
2283             if (localVariableTable != null) {
2284                 // 6 header bytes and 2 bytes for local_variable_table_length.
2285                 size += 8 + localVariableTable.length;
2286                 ++codeAttributeCount;
2287             }
2288             if (localVariableTypeTable != null) {
2289                 // 6 header bytes and 2 bytes for local_variable_type_table_length.
2290                 size += 8 + localVariableTypeTable.length;
2291                 ++codeAttributeCount;
2292             }
2293             if (lastCodeRuntimeVisibleTypeAnnotation != null) {
2294                 size +=
2295                         lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(
2296                                 Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);
2297                 ++codeAttributeCount;
2298             }
2299             if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
2300                 size +=
2301                         lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(
2302                                 Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);
2303                 ++codeAttributeCount;
2304             }
2305             if (firstCodeAttribute != null) {
2306                 size +=
2307                         firstCodeAttribute.computeAttributesSize(
2308                                 symbolTable, code.data, code.length, maxStack, maxLocals);
2309                 codeAttributeCount += firstCodeAttribute.getAttributeCount();
2310             }
2311             output
2312                     .putShort(symbolTable.addConstantUtf8(Constants.CODE))
2313                     .putInt(size)
2314                     .putShort(maxStack)
2315                     .putShort(maxLocals)
2316                     .putInt(code.length)
2317                     .putByteArray(code.data, 0, code.length);
2318             Handler.putExceptionTable(firstHandler, output);
2319             output.putShort(codeAttributeCount);
2320             if (stackMapTableEntries != null) {
2321                 boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
2322                 output
2323                         .putShort(
2324                                 symbolTable.addConstantUtf8(
2325                                         useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap"))
2326                         .putInt(2 + stackMapTableEntries.length)
2327                         .putShort(stackMapTableNumberOfEntries)
2328                         .putByteArray(stackMapTableEntries.data, 0, stackMapTableEntries.length);
2329             }
2330             if (lineNumberTable != null) {
2331                 output
2332                         .putShort(symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE))
2333                         .putInt(2 + lineNumberTable.length)
2334                         .putShort(lineNumberTableLength)
2335                         .putByteArray(lineNumberTable.data, 0, lineNumberTable.length);
2336             }
2337             if (localVariableTable != null) {
2338                 output
2339                         .putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE))
2340                         .putInt(2 + localVariableTable.length)
2341                         .putShort(localVariableTableLength)
2342                         .putByteArray(localVariableTable.data, 0, localVariableTable.length);
2343             }
2344             if (localVariableTypeTable != null) {
2345                 output
2346                         .putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE))
2347                         .putInt(2 + localVariableTypeTable.length)
2348                         .putShort(localVariableTypeTableLength)
2349                         .putByteArray(localVariableTypeTable.data, 0, localVariableTypeTable.length);
2350             }
2351             if (lastCodeRuntimeVisibleTypeAnnotation != null) {
2352                 lastCodeRuntimeVisibleTypeAnnotation.putAnnotations(
2353                         symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS), output);
2354             }
2355             if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
2356                 lastCodeRuntimeInvisibleTypeAnnotation.putAnnotations(
2357                         symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS), output);
2358             }
2359             if (firstCodeAttribute != null) {
2360                 firstCodeAttribute.putAttributes(
2361                         symbolTable, code.data, code.length, maxStack, maxLocals, output);
2362             }
2363         }
2364         if (numberOfExceptions > 0) {
2365             output
2366                     .putShort(symbolTable.addConstantUtf8(Constants.EXCEPTIONS))
2367                     .putInt(2 + 2 * numberOfExceptions)
2368                     .putShort(numberOfExceptions);
2369             for (int exceptionIndex : exceptionIndexTable) {
2370                 output.putShort(exceptionIndex);
2371             }
2372         }
2373         Attribute.putAttributes(symbolTable, accessFlags, signatureIndex, output);
2374         AnnotationWriter.putAnnotations(
2375                 symbolTable,
2376                 lastRuntimeVisibleAnnotation,
2377                 lastRuntimeInvisibleAnnotation,
2378                 lastRuntimeVisibleTypeAnnotation,
2379                 lastRuntimeInvisibleTypeAnnotation,
2380                 output);
2381         if (lastRuntimeVisibleParameterAnnotations != null) {
2382             AnnotationWriter.putParameterAnnotations(
2383                     symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS),
2384                     lastRuntimeVisibleParameterAnnotations,
2385                     visibleAnnotableParameterCount == 0
2386                             ? lastRuntimeVisibleParameterAnnotations.length
2387                             : visibleAnnotableParameterCount,
2388                     output);
2389         }
2390         if (lastRuntimeInvisibleParameterAnnotations != null) {
2391             AnnotationWriter.putParameterAnnotations(
2392                     symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS),
2393                     lastRuntimeInvisibleParameterAnnotations,
2394                     invisibleAnnotableParameterCount == 0
2395                             ? lastRuntimeInvisibleParameterAnnotations.length
2396                             : invisibleAnnotableParameterCount,
2397                     output);
2398         }
2399         if (defaultValue != null) {
2400             output
2401                     .putShort(symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT))
2402                     .putInt(defaultValue.length)
2403                     .putByteArray(defaultValue.data, 0, defaultValue.length);
2404         }
2405         if (parameters != null) {
2406             output
2407                     .putShort(symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS))
2408                     .putInt(1 + parameters.length)
2409                     .putByte(parametersCount)
2410                     .putByteArray(parameters.data, 0, parameters.length);
2411         }
2412         if (firstAttribute != null) {
2413             firstAttribute.putAttributes(symbolTable, output);
2414         }
2415     }
2416 
2417     /**
2418       * Collects the attributes of this method into the given set of attribute prototypes.
2419       *
2420       * @param attributePrototypes a set of attribute prototypes.
2421       */
2422     final void collectAttributePrototypes(final Attribute.Set attributePrototypes) {
2423         attributePrototypes.addAttributes(firstAttribute);
2424         attributePrototypes.addAttributes(firstCodeAttribute);
2425     }
2426 }
--- EOF ---